blob: c4ec8dc1162f9f6c0fe96746466f303600f5ae63 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000059 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000072 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Douglas Gregor171c45a2009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 if (FD->isDeleted()) {
88 Diag(Loc, diag::err_deleted_function_use);
89 Diag(D->getLocation(), diag::note_unavailable_here) << true;
90 return true;
91 }
Douglas Gregorde681d42009-02-24 04:26:15 +000092 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000093
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000094 // See if this declaration is unavailable or deprecated.
95 std::string Message;
96 switch (D->getAvailability(&Message)) {
97 case AR_Available:
98 case AR_NotYetIntroduced:
99 break;
100
101 case AR_Deprecated:
102 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103 break;
104
105 case AR_Unavailable:
106 if (Message.empty()) {
107 if (!UnknownObjCClass)
108 Diag(Loc, diag::err_unavailable) << D->getDeclName();
109 else
110 Diag(Loc, diag::warn_unavailable_fwdclass_message)
111 << D->getDeclName();
112 }
113 else
114 Diag(Loc, diag::err_unavailable_message)
115 << D->getDeclName() << Message;
116 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117 break;
118 }
119
Anders Carlsson73067a02010-10-22 23:37:08 +0000120 // Warn if this is used but marked unused.
121 if (D->hasAttr<UnusedAttr>())
122 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
Douglas Gregor171c45a2009-02-18 21:56:37 +0000124 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000125}
126
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131 // FIXME: C++0x implicitly-deleted special member functions could be
132 // detected here so that we could improve diagnostics to say, e.g.,
133 // "base class 'A' had a deleted copy constructor".
134 if (FD->isDeleted())
135 return std::string();
136
137 std::string Message;
138 if (FD->getAvailability(&Message))
139 return ": " + Message;
140
141 return std::string();
142}
143
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000152 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000153
154 // FIXME: In C++0x, if any of the arguments are parameter pack
155 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Mike Stump87c57ac2009-05-16 07:39:55 +0000159 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 bool warnNotEnoughArgs = false;
163 int isMethod = 0;
164 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165 // skip over named parameters.
166 ObjCMethodDecl::param_iterator P, E = MD->param_end();
167 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168 if (nullPos)
169 --nullPos;
170 else
171 ++i;
172 }
173 warnNotEnoughArgs = (P != E || i >= NumArgs);
174 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000176 // skip over named parameters.
177 ObjCMethodDecl::param_iterator P, E = FD->param_end();
178 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179 if (nullPos)
180 --nullPos;
181 else
182 ++i;
183 }
184 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000192 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193 unsigned NumArgsInProto = Proto->getNumArgs();
194 unsigned k;
195 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196 if (nullPos)
197 --nullPos;
198 else
199 ++i;
200 }
201 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202 }
203 if (Ty->isBlockPointerType())
204 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000205 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000206 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
214 }
215 int sentinel = i;
216 while (sentinelPos > 0 && i < NumArgs-1) {
217 --sentinelPos;
218 ++i;
219 }
220 if (sentinelPos > 0) {
221 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000238 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239 Expr::NPC_ValueDependentIsNull))
240 return;
241
242 // Unfortunately, __null has type 'int'.
243 if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000247}
248
Douglas Gregor87f95b02009-02-26 21:00:50 +0000249SourceRange Sema::getExprRange(ExprTy *E) const {
250 Expr *Ex = (Expr *)E;
251 return Ex? Ex->getSourceRange() : SourceRange();
252}
253
Chris Lattner513165e2008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000266 else if (Ty->isArrayType()) {
267 // In C90 mode, arrays only promote to pointers if the array expression is
268 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269 // type 'array of type' is converted to an expression that has type 'pointer
270 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
271 // that has type 'array of type' ...". The relevant change is "an lvalue"
272 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000273 //
274 // C++ 4.2p1:
275 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276 // T" can be converted to an rvalue of type "pointer to T".
277 //
John McCall086a4642010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 }
John Wiegley01296292011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000283}
284
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000285static void CheckForNullPointerDereference(Sema &S, Expr *E) {
286 // Check to see if we are dereferencing a null pointer. If so,
287 // and if not volatile-qualified, this is undefined behavior that the
288 // optimizer will delete, so warn about it. People sometimes try to use this
289 // to get a deterministic trap and are surprised by clang's behavior. This
290 // only handles the pattern "*null", which is a very syntactic check.
291 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
292 if (UO->getOpcode() == UO_Deref &&
293 UO->getSubExpr()->IgnoreParenCasts()->
294 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
295 !UO->getType().isVolatileQualified()) {
296 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
297 S.PDiag(diag::warn_indirection_through_null)
298 << UO->getSubExpr()->getSourceRange());
299 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
300 S.PDiag(diag::note_indirection_through_null));
301 }
302}
303
John Wiegley01296292011-04-08 18:41:53 +0000304ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000305 // C++ [conv.lval]p1:
306 // A glvalue of a non-function, non-array type T can be
307 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000308 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000309
John McCall27584242010-12-06 20:48:59 +0000310 QualType T = E->getType();
311 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000312
John McCall27584242010-12-06 20:48:59 +0000313 // Create a load out of an ObjCProperty l-value, if necessary.
314 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000315 ExprResult Res = ConvertPropertyForRValue(E);
316 if (Res.isInvalid())
317 return Owned(E);
318 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000319 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000320 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000321 }
John McCall27584242010-12-06 20:48:59 +0000322
323 // We don't want to throw lvalue-to-rvalue casts on top of
324 // expressions of certain types in C++.
325 if (getLangOptions().CPlusPlus &&
326 (E->getType() == Context.OverloadTy ||
327 T->isDependentType() ||
328 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000329 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000330
331 // The C standard is actually really unclear on this point, and
332 // DR106 tells us what the result should be but not why. It's
333 // generally best to say that void types just doesn't undergo
334 // lvalue-to-rvalue at all. Note that expressions of unqualified
335 // 'void' type are never l-values, but qualified void can be.
336 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000337 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000338
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000339 CheckForNullPointerDereference(*this, E);
340
John McCall27584242010-12-06 20:48:59 +0000341 // C++ [conv.lval]p1:
342 // [...] If T is a non-class type, the type of the prvalue is the
343 // cv-unqualified version of T. Otherwise, the type of the
344 // rvalue is T.
345 //
346 // C99 6.3.2.1p2:
347 // If the lvalue has qualified type, the value has the unqualified
348 // version of the type of the lvalue; otherwise, the value has the
349 // type of the lvalue.
350 if (T.hasQualifiers())
351 T = T.getUnqualifiedType();
352
Ted Kremenekdf26df72011-03-01 18:41:00 +0000353 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000354
John Wiegley01296292011-04-08 18:41:53 +0000355 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
356 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000357}
358
John Wiegley01296292011-04-08 18:41:53 +0000359ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
360 ExprResult Res = DefaultFunctionArrayConversion(E);
361 if (Res.isInvalid())
362 return ExprError();
363 Res = DefaultLvalueConversion(Res.take());
364 if (Res.isInvalid())
365 return ExprError();
366 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000367}
368
369
Chris Lattner513165e2008-07-25 21:10:04 +0000370/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000371/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000372/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000373/// apply if the array is an argument to the sizeof or address (&) operators.
374/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000375ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000376 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000377 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
378 if (Res.isInvalid())
379 return Owned(E);
380 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000381
382 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000383 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000384
385 // Try to perform integral promotions if the object has a theoretically
386 // promotable type.
387 if (Ty->isIntegralOrUnscopedEnumerationType()) {
388 // C99 6.3.1.1p2:
389 //
390 // The following may be used in an expression wherever an int or
391 // unsigned int may be used:
392 // - an object or expression with an integer type whose integer
393 // conversion rank is less than or equal to the rank of int
394 // and unsigned int.
395 // - A bit-field of type _Bool, int, signed int, or unsigned int.
396 //
397 // If an int can represent all values of the original type, the
398 // value is converted to an int; otherwise, it is converted to an
399 // unsigned int. These are called the integer promotions. All
400 // other types are unchanged by the integer promotions.
401
402 QualType PTy = Context.isPromotableBitField(E);
403 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000404 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
405 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000406 }
407 if (Ty->isPromotableIntegerType()) {
408 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
410 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000411 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000412 }
John Wiegley01296292011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000414}
415
Chris Lattner2ce500f2008-07-25 22:25:12 +0000416/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000417/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000418/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000419ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
420 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000421 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000422
John Wiegley01296292011-04-08 18:41:53 +0000423 ExprResult Res = UsualUnaryConversions(E);
424 if (Res.isInvalid())
425 return Owned(E);
426 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000427
Chris Lattner2ce500f2008-07-25 22:25:12 +0000428 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000429 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000430 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
431
432 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000433}
434
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000435/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
436/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000437/// interfaces passed by value.
438ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000439 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000440 ExprResult ExprRes = DefaultArgumentPromotion(E);
441 if (ExprRes.isInvalid())
442 return ExprError();
443 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000444
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000445 // __builtin_va_start takes the second argument as a "varargs" argument, but
446 // it doesn't actually do anything with it. It doesn't need to be non-pod
447 // etc.
448 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000449 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000450
John Wiegley01296292011-04-08 18:41:53 +0000451 if (E->getType()->isObjCObjectType() &&
452 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000453 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000454 << E->getType() << CT))
455 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000456
John Wiegley01296292011-04-08 18:41:53 +0000457 if (!E->getType()->isPODType() &&
458 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000459 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000460 << E->getType() << CT))
461 return ExprError();
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000462
John Wiegley01296292011-04-08 18:41:53 +0000463 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000464}
465
Chris Lattner513165e2008-07-25 21:10:04 +0000466/// UsualArithmeticConversions - Performs various conversions that are common to
467/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000468/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000469/// responsible for emitting appropriate error diagnostics.
470/// FIXME: verify the conversion rules for "complex int" are consistent with
471/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000472QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000473 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000474 if (!isCompAssign) {
475 lhsExpr = UsualUnaryConversions(lhsExpr.take());
476 if (lhsExpr.isInvalid())
477 return QualType();
478 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000479
John Wiegley01296292011-04-08 18:41:53 +0000480 rhsExpr = UsualUnaryConversions(rhsExpr.take());
481 if (rhsExpr.isInvalid())
482 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000483
Mike Stump11289f42009-09-09 15:08:12 +0000484 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000485 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000486 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000487 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000488 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000489 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000490
491 // If both types are identical, no conversion is needed.
492 if (lhs == rhs)
493 return lhs;
494
495 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
496 // The caller can deal with this (e.g. pointer + int).
497 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
498 return lhs;
499
John McCalld005ac92010-11-13 08:17:45 +0000500 // Apply unary and bitfield promotions to the LHS's type.
501 QualType lhs_unpromoted = lhs;
502 if (lhs->isPromotableIntegerType())
503 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000504 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000505 if (!LHSBitfieldPromoteTy.isNull())
506 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000507 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000508 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000509
John McCalld005ac92010-11-13 08:17:45 +0000510 // If both types are identical, no conversion is needed.
511 if (lhs == rhs)
512 return lhs;
513
514 // At this point, we have two different arithmetic types.
515
516 // Handle complex types first (C99 6.3.1.8p1).
517 bool LHSComplexFloat = lhs->isComplexType();
518 bool RHSComplexFloat = rhs->isComplexType();
519 if (LHSComplexFloat || RHSComplexFloat) {
520 // if we have an integer operand, the result is the complex type.
521
John McCallc5e62b42010-11-13 09:02:35 +0000522 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
523 if (rhs->isIntegerType()) {
524 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000525 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
526 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000527 } else {
528 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000529 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000530 }
John McCalld005ac92010-11-13 08:17:45 +0000531 return lhs;
532 }
533
John McCallc5e62b42010-11-13 09:02:35 +0000534 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
535 if (!isCompAssign) {
536 // int -> float -> _Complex float
537 if (lhs->isIntegerType()) {
538 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000539 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
540 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000541 } else {
542 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000543 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000544 }
545 }
John McCalld005ac92010-11-13 08:17:45 +0000546 return rhs;
547 }
548
549 // This handles complex/complex, complex/float, or float/complex.
550 // When both operands are complex, the shorter operand is converted to the
551 // type of the longer, and that is the type of the result. This corresponds
552 // to what is done when combining two real floating-point operands.
553 // The fun begins when size promotion occur across type domains.
554 // From H&S 6.3.4: When one operand is complex and the other is a real
555 // floating-point type, the less precise type is converted, within it's
556 // real or complex domain, to the precision of the other type. For example,
557 // when combining a "long double" with a "double _Complex", the
558 // "double _Complex" is promoted to "long double _Complex".
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560
561 // If both are complex, just cast to the more precise type.
562 if (LHSComplexFloat && RHSComplexFloat) {
563 if (order > 0) {
564 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000565 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000566 return lhs;
567
568 } else if (order < 0) {
569 // _Complex float -> _Complex double
570 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000571 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000572 return rhs;
573 }
574 return lhs;
575 }
576
577 // If just the LHS is complex, the RHS needs to be converted,
578 // and the LHS might need to be promoted.
579 if (LHSComplexFloat) {
580 if (order > 0) { // LHS is wider
581 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000582 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000583 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
584 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000585 return lhs;
586 }
587
588 // RHS is at least as wide. Find its corresponding complex type.
589 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
590
591 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000592 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000593
594 // _Complex float -> _Complex double
595 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000597
598 return result;
599 }
600
601 // Just the RHS is complex, so the LHS needs to be converted
602 // and the RHS might need to be promoted.
603 assert(RHSComplexFloat);
604
605 if (order < 0) { // RHS is wider
606 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000607 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000608 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000609 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
610 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000611 }
John McCalld005ac92010-11-13 08:17:45 +0000612 return rhs;
613 }
614
615 // LHS is at least as wide. Find its corresponding complex type.
616 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
617
618 // double -> _Complex double
619 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000620 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000621
622 // _Complex float -> _Complex double
623 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000624 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000625
626 return result;
627 }
628
629 // Now handle "real" floating types (i.e. float, double, long double).
630 bool LHSFloat = lhs->isRealFloatingType();
631 bool RHSFloat = rhs->isRealFloatingType();
632 if (LHSFloat || RHSFloat) {
633 // If we have two real floating types, convert the smaller operand
634 // to the bigger result.
635 if (LHSFloat && RHSFloat) {
636 int order = Context.getFloatingTypeOrder(lhs, rhs);
637 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000638 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000639 return lhs;
640 }
641
642 assert(order < 0 && "illegal float comparison");
643 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000645 return rhs;
646 }
647
648 // If we have an integer operand, the result is the real floating type.
649 if (LHSFloat) {
650 if (rhs->isIntegerType()) {
651 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000652 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000653 return lhs;
654 }
655
656 // Convert both sides to the appropriate complex float.
657 assert(rhs->isComplexIntegerType());
658 QualType result = Context.getComplexType(lhs);
659
660 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000661 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000662
663 // float -> _Complex float
664 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000665 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000666
667 return result;
668 }
669
670 assert(RHSFloat);
671 if (lhs->isIntegerType()) {
672 // Convert lhs to the rhs floating point type.
673 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000674 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000675 return rhs;
676 }
677
678 // Convert both sides to the appropriate complex float.
679 assert(lhs->isComplexIntegerType());
680 QualType result = Context.getComplexType(rhs);
681
682 // _Complex int -> _Complex float
683 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000685
686 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000687 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000688
689 return result;
690 }
691
692 // Handle GCC complex int extension.
693 // FIXME: if the operands are (int, _Complex long), we currently
694 // don't promote the complex. Also, signedness?
695 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
696 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
697 if (lhsComplexInt && rhsComplexInt) {
698 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
699 rhsComplexInt->getElementType());
700 assert(order && "inequal types with equal element ordering");
701 if (order > 0) {
702 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000703 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000704 return lhs;
705 }
706
707 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000708 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000709 return rhs;
710 } else if (lhsComplexInt) {
711 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000712 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000713 return lhs;
714 } else if (rhsComplexInt) {
715 // int -> _Complex int
716 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000717 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000718 return rhs;
719 }
720
721 // Finally, we have two differing integer types.
722 // The rules for this case are in C99 6.3.1.8
723 int compare = Context.getIntegerTypeOrder(lhs, rhs);
724 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
725 rhsSigned = rhs->hasSignedIntegerRepresentation();
726 if (lhsSigned == rhsSigned) {
727 // Same signedness; use the higher-ranked type
728 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000729 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000730 return lhs;
731 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000732 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000733 return rhs;
734 } else if (compare != (lhsSigned ? 1 : -1)) {
735 // The unsigned type has greater than or equal rank to the
736 // signed type, so use the unsigned type
737 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000739 return lhs;
740 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000742 return rhs;
743 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
744 // The two types are different widths; if we are here, that
745 // means the signed type is larger than the unsigned type, so
746 // use the signed type.
747 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000748 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000749 return lhs;
750 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000751 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000752 return rhs;
753 } else {
754 // The signed type is higher-ranked than the unsigned type,
755 // but isn't actually any bigger (like unsigned int and long
756 // on most 32-bit systems). Use the unsigned type corresponding
757 // to the signed type.
758 QualType result =
759 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000760 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000761 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000762 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000763 return result;
764 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000765}
766
Chris Lattner513165e2008-07-25 21:10:04 +0000767//===----------------------------------------------------------------------===//
768// Semantic Analysis for various Expression Types
769//===----------------------------------------------------------------------===//
770
771
Peter Collingbourne91147592011-04-15 00:35:48 +0000772ExprResult
773Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
774 SourceLocation DefaultLoc,
775 SourceLocation RParenLoc,
776 Expr *ControllingExpr,
777 MultiTypeArg types,
778 MultiExprArg exprs) {
779 unsigned NumAssocs = types.size();
780 assert(NumAssocs == exprs.size());
781
782 ParsedType *ParsedTypes = types.release();
783 Expr **Exprs = exprs.release();
784
785 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
786 for (unsigned i = 0; i < NumAssocs; ++i) {
787 if (ParsedTypes[i])
788 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
789 else
790 Types[i] = 0;
791 }
792
793 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
794 ControllingExpr, Types, Exprs,
795 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000796 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000797 return ER;
798}
799
800ExprResult
801Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
802 SourceLocation DefaultLoc,
803 SourceLocation RParenLoc,
804 Expr *ControllingExpr,
805 TypeSourceInfo **Types,
806 Expr **Exprs,
807 unsigned NumAssocs) {
808 bool TypeErrorFound = false,
809 IsResultDependent = ControllingExpr->isTypeDependent(),
810 ContainsUnexpandedParameterPack
811 = ControllingExpr->containsUnexpandedParameterPack();
812
813 for (unsigned i = 0; i < NumAssocs; ++i) {
814 if (Exprs[i]->containsUnexpandedParameterPack())
815 ContainsUnexpandedParameterPack = true;
816
817 if (Types[i]) {
818 if (Types[i]->getType()->containsUnexpandedParameterPack())
819 ContainsUnexpandedParameterPack = true;
820
821 if (Types[i]->getType()->isDependentType()) {
822 IsResultDependent = true;
823 } else {
824 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
825 // complete object type other than a variably modified type."
826 unsigned D = 0;
827 if (Types[i]->getType()->isIncompleteType())
828 D = diag::err_assoc_type_incomplete;
829 else if (!Types[i]->getType()->isObjectType())
830 D = diag::err_assoc_type_nonobject;
831 else if (Types[i]->getType()->isVariablyModifiedType())
832 D = diag::err_assoc_type_variably_modified;
833
834 if (D != 0) {
835 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
836 << Types[i]->getTypeLoc().getSourceRange()
837 << Types[i]->getType();
838 TypeErrorFound = true;
839 }
840
841 // C1X 6.5.1.1p2 "No two generic associations in the same generic
842 // selection shall specify compatible types."
843 for (unsigned j = i+1; j < NumAssocs; ++j)
844 if (Types[j] && !Types[j]->getType()->isDependentType() &&
845 Context.typesAreCompatible(Types[i]->getType(),
846 Types[j]->getType())) {
847 Diag(Types[j]->getTypeLoc().getBeginLoc(),
848 diag::err_assoc_compatible_types)
849 << Types[j]->getTypeLoc().getSourceRange()
850 << Types[j]->getType()
851 << Types[i]->getType();
852 Diag(Types[i]->getTypeLoc().getBeginLoc(),
853 diag::note_compat_assoc)
854 << Types[i]->getTypeLoc().getSourceRange()
855 << Types[i]->getType();
856 TypeErrorFound = true;
857 }
858 }
859 }
860 }
861 if (TypeErrorFound)
862 return ExprError();
863
864 // If we determined that the generic selection is result-dependent, don't
865 // try to compute the result expression.
866 if (IsResultDependent)
867 return Owned(new (Context) GenericSelectionExpr(
868 Context, KeyLoc, ControllingExpr,
869 Types, Exprs, NumAssocs, DefaultLoc,
870 RParenLoc, ContainsUnexpandedParameterPack));
871
872 llvm::SmallVector<unsigned, 1> CompatIndices;
873 unsigned DefaultIndex = -1U;
874 for (unsigned i = 0; i < NumAssocs; ++i) {
875 if (!Types[i])
876 DefaultIndex = i;
877 else if (Context.typesAreCompatible(ControllingExpr->getType(),
878 Types[i]->getType()))
879 CompatIndices.push_back(i);
880 }
881
882 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
883 // type compatible with at most one of the types named in its generic
884 // association list."
885 if (CompatIndices.size() > 1) {
886 // We strip parens here because the controlling expression is typically
887 // parenthesized in macro definitions.
888 ControllingExpr = ControllingExpr->IgnoreParens();
889 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
890 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
891 << (unsigned) CompatIndices.size();
892 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
893 E = CompatIndices.end(); I != E; ++I) {
894 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
895 diag::note_compat_assoc)
896 << Types[*I]->getTypeLoc().getSourceRange()
897 << Types[*I]->getType();
898 }
899 return ExprError();
900 }
901
902 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
903 // its controlling expression shall have type compatible with exactly one of
904 // the types named in its generic association list."
905 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
906 // We strip parens here because the controlling expression is typically
907 // parenthesized in macro definitions.
908 ControllingExpr = ControllingExpr->IgnoreParens();
909 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
910 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
911 return ExprError();
912 }
913
914 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
915 // type name that is compatible with the type of the controlling expression,
916 // then the result expression of the generic selection is the expression
917 // in that generic association. Otherwise, the result expression of the
918 // generic selection is the expression in the default generic association."
919 unsigned ResultIndex =
920 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
921
922 return Owned(new (Context) GenericSelectionExpr(
923 Context, KeyLoc, ControllingExpr,
924 Types, Exprs, NumAssocs, DefaultLoc,
925 RParenLoc, ContainsUnexpandedParameterPack,
926 ResultIndex));
927}
928
Steve Naroff83895f72007-09-16 03:34:24 +0000929/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000930/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
931/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
932/// multiple tokens. However, the common case is that StringToks points to one
933/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000934///
John McCalldadc5752010-08-24 06:29:42 +0000935ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000936Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000937 assert(NumStringToks && "Must have at least one string!");
938
Chris Lattner8a24e582009-01-16 18:51:42 +0000939 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000940 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000941 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000942
Chris Lattner23b7eb62007-06-15 23:05:46 +0000943 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000944 for (unsigned i = 0; i != NumStringToks; ++i)
945 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000946
Chris Lattner36fc8792008-02-11 00:02:17 +0000947 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000948 if (Literal.AnyWide)
949 StrTy = Context.getWCharType();
950 else if (Literal.Pascal)
951 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000952
953 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000954 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000955 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000956
Chris Lattner36fc8792008-02-11 00:02:17 +0000957 // Get an array type for the string, according to C99 6.4.5. This includes
958 // the nul terminator character as well as the string length for pascal
959 // strings.
960 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000961 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000962 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000963
Chris Lattner5b183d82006-11-10 05:03:26 +0000964 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000965 return Owned(StringLiteral::Create(Context, Literal.GetString(),
966 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +0000967 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +0000968 &StringTokLocs[0],
969 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000970}
971
John McCallc63de662011-02-02 13:00:07 +0000972enum CaptureResult {
973 /// No capture is required.
974 CR_NoCapture,
975
976 /// A capture is required.
977 CR_Capture,
978
John McCall351762c2011-02-07 10:33:21 +0000979 /// A by-ref capture is required.
980 CR_CaptureByRef,
981
John McCallc63de662011-02-02 13:00:07 +0000982 /// An error occurred when trying to capture the given variable.
983 CR_Error
984};
985
986/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000987///
John McCallc63de662011-02-02 13:00:07 +0000988/// \param var - the variable referenced
989/// \param DC - the context which we couldn't capture through
990static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000991diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000992 VarDecl *var, DeclContext *DC) {
993 switch (S.ExprEvalContexts.back().Context) {
994 case Sema::Unevaluated:
995 // The argument will never be evaluated, so don't complain.
996 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000997
John McCallc63de662011-02-02 13:00:07 +0000998 case Sema::PotentiallyEvaluated:
999 case Sema::PotentiallyEvaluatedIfUsed:
1000 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001001
John McCallc63de662011-02-02 13:00:07 +00001002 case Sema::PotentiallyPotentiallyEvaluated:
1003 // FIXME: delay these!
1004 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001005 }
Mike Stump11289f42009-09-09 15:08:12 +00001006
John McCallc63de662011-02-02 13:00:07 +00001007 // Don't diagnose about capture if we're not actually in code right
1008 // now; in general, there are more appropriate places that will
1009 // diagnose this.
1010 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1011
John McCall92d627e2011-03-22 23:15:50 +00001012 // Certain madnesses can happen with parameter declarations, which
1013 // we want to ignore.
1014 if (isa<ParmVarDecl>(var)) {
1015 // - If the parameter still belongs to the translation unit, then
1016 // we're actually just using one parameter in the declaration of
1017 // the next. This is useful in e.g. VLAs.
1018 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1019 return CR_NoCapture;
1020
1021 // - This particular madness can happen in ill-formed default
1022 // arguments; claim it's okay and let downstream code handle it.
1023 if (S.CurContext == var->getDeclContext()->getParent())
1024 return CR_NoCapture;
1025 }
John McCallc63de662011-02-02 13:00:07 +00001026
1027 DeclarationName functionName;
1028 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1029 functionName = fn->getDeclName();
1030 // FIXME: variable from enclosing block that we couldn't capture from!
1031
1032 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1033 << var->getIdentifier() << functionName;
1034 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1035 << var->getIdentifier();
1036
1037 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001038}
1039
John McCall351762c2011-02-07 10:33:21 +00001040/// There is a well-formed capture at a particular scope level;
1041/// propagate it through all the nested blocks.
1042static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1043 const BlockDecl::Capture &capture) {
1044 VarDecl *var = capture.getVariable();
1045
1046 // Update all the inner blocks with the capture information.
1047 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1048 i != e; ++i) {
1049 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1050 innerBlock->Captures.push_back(
1051 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1052 /*nested*/ true, capture.getCopyExpr()));
1053 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1054 }
1055
1056 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1057}
1058
1059/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001060/// given value in the current context requires a variable capture.
1061///
1062/// This also keeps the captures set in the BlockScopeInfo records
1063/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001064static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001065 ValueDecl *value) {
1066 // Only variables ever require capture.
1067 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001068 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001069
1070 // Fast path: variables from the current context never require capture.
1071 DeclContext *DC = S.CurContext;
1072 if (var->getDeclContext() == DC) return CR_NoCapture;
1073
1074 // Only variables with local storage require capture.
1075 // FIXME: What about 'const' variables in C++?
1076 if (!var->hasLocalStorage()) return CR_NoCapture;
1077
1078 // Otherwise, we need to capture.
1079
1080 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001081 do {
1082 // Only blocks (and eventually C++0x closures) can capture; other
1083 // scopes don't work.
1084 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001085 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001086
1087 BlockScopeInfo *blockScope =
1088 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1089 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1090
John McCall351762c2011-02-07 10:33:21 +00001091 // Check whether we've already captured it in this block. If so,
1092 // we're done.
1093 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1094 return propagateCapture(S, functionScopesIndex,
1095 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001096
1097 functionScopesIndex--;
1098 DC = cast<BlockDecl>(DC)->getDeclContext();
1099 } while (var->getDeclContext() != DC);
1100
John McCall351762c2011-02-07 10:33:21 +00001101 // Okay, we descended all the way to the block that defines the variable.
1102 // Actually try to capture it.
1103 QualType type = var->getType();
1104
1105 // Prohibit variably-modified types.
1106 if (type->isVariablyModifiedType()) {
1107 S.Diag(loc, diag::err_ref_vm_type);
1108 S.Diag(var->getLocation(), diag::note_declared_at);
1109 return CR_Error;
1110 }
1111
1112 // Prohibit arrays, even in __block variables, but not references to
1113 // them.
1114 if (type->isArrayType()) {
1115 S.Diag(loc, diag::err_ref_array_type);
1116 S.Diag(var->getLocation(), diag::note_declared_at);
1117 return CR_Error;
1118 }
1119
1120 S.MarkDeclarationReferenced(loc, var);
1121
1122 // The BlocksAttr indicates the variable is bound by-reference.
1123 bool byRef = var->hasAttr<BlocksAttr>();
1124
1125 // Build a copy expression.
1126 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001127 const RecordType *rtype;
1128 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1129 (rtype = type->getAs<RecordType>())) {
1130
1131 // The capture logic needs the destructor, so make sure we mark it.
1132 // Usually this is unnecessary because most local variables have
1133 // their destructors marked at declaration time, but parameters are
1134 // an exception because it's technically only the call site that
1135 // actually requires the destructor.
1136 if (isa<ParmVarDecl>(var))
1137 S.FinalizeVarWithDestructor(var, rtype);
1138
John McCall351762c2011-02-07 10:33:21 +00001139 // According to the blocks spec, the capture of a variable from
1140 // the stack requires a const copy constructor. This is not true
1141 // of the copy/move done to move a __block variable to the heap.
1142 type.addConst();
1143
1144 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1145 ExprResult result =
1146 S.PerformCopyInitialization(
1147 InitializedEntity::InitializeBlock(var->getLocation(),
1148 type, false),
1149 loc, S.Owned(declRef));
1150
1151 // Build a full-expression copy expression if initialization
1152 // succeeded and used a non-trivial constructor. Recover from
1153 // errors by pretending that the copy isn't necessary.
1154 if (!result.isInvalid() &&
1155 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1156 result = S.MaybeCreateExprWithCleanups(result);
1157 copyExpr = result.take();
1158 }
1159 }
1160
1161 // We're currently at the declarer; go back to the closure.
1162 functionScopesIndex++;
1163 BlockScopeInfo *blockScope =
1164 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1165
1166 // Build a valid capture in this scope.
1167 blockScope->Captures.push_back(
1168 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1169 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1170
1171 // Propagate that to inner captures if necessary.
1172 return propagateCapture(S, functionScopesIndex,
1173 blockScope->Captures.back());
1174}
1175
1176static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1177 const DeclarationNameInfo &NameInfo,
1178 bool byRef) {
1179 assert(isa<VarDecl>(vd) && "capturing non-variable");
1180
1181 VarDecl *var = cast<VarDecl>(vd);
1182 assert(var->hasLocalStorage() && "capturing non-local");
1183 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1184
1185 QualType exprType = var->getType().getNonReferenceType();
1186
1187 BlockDeclRefExpr *BDRE;
1188 if (!byRef) {
1189 // The variable will be bound by copy; make it const within the
1190 // closure, but record that this was done in the expression.
1191 bool constAdded = !exprType.isConstQualified();
1192 exprType.addConst();
1193
1194 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1195 NameInfo.getLoc(), false,
1196 constAdded);
1197 } else {
1198 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1199 NameInfo.getLoc(), true);
1200 }
1201
1202 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001203}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001204
John McCalldadc5752010-08-24 06:29:42 +00001205ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001206Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001207 SourceLocation Loc,
1208 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001209 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001210 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001211}
1212
John McCallf4cd4f92011-02-09 01:13:10 +00001213/// BuildDeclRefExpr - Build an expression that references a
1214/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001215ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001216Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001217 const DeclarationNameInfo &NameInfo,
1218 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001219 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCall086a4642010-11-24 05:12:34 +00001221 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001222 SS? SS->getWithLocInContext(Context)
1223 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001224 D, NameInfo, Ty, VK);
1225
1226 // Just in case we're building an illegal pointer-to-member.
1227 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1228 E->setObjectKind(OK_BitField);
1229
1230 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001231}
1232
John McCallfeb624a2010-11-23 20:48:44 +00001233static ExprResult
1234BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1235 const CXXScopeSpec &SS, FieldDecl *Field,
1236 DeclAccessPair FoundDecl,
1237 const DeclarationNameInfo &MemberNameInfo);
1238
John McCalldadc5752010-08-24 06:29:42 +00001239ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001240Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1241 SourceLocation loc,
1242 IndirectFieldDecl *indirectField,
1243 Expr *baseObjectExpr,
1244 SourceLocation opLoc) {
1245 // First, build the expression that refers to the base object.
1246
1247 bool baseObjectIsPointer = false;
1248 Qualifiers baseQuals;
1249
1250 // Case 1: the base of the indirect field is not a field.
1251 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001252 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001253 if (baseVariable) {
1254 assert(baseVariable->getType()->isRecordType());
1255
1256 // In principle we could have a member access expression that
1257 // accesses an anonymous struct/union that's a static member of
1258 // the base object's class. However, under the current standard,
1259 // static data members cannot be anonymous structs or unions.
1260 // Supporting this is as easy as building a MemberExpr here.
1261 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1262
1263 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1264
1265 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001266 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001267 if (result.isInvalid()) return ExprError();
1268
1269 baseObjectExpr = result.take();
1270 baseObjectIsPointer = false;
1271 baseQuals = baseObjectExpr->getType().getQualifiers();
1272
1273 // Case 2: the base of the indirect field is a field and the user
1274 // wrote a member expression.
1275 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001276 // The caller provided the base object expression. Determine
1277 // whether its a pointer and whether it adds any qualifiers to the
1278 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001279 QualType objectType = baseObjectExpr->getType();
1280
1281 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1282 baseObjectIsPointer = true;
1283 objectType = ptr->getPointeeType();
1284 } else {
1285 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001286 }
John McCallf3a88602011-02-03 08:15:49 +00001287 baseQuals = objectType.getQualifiers();
1288
1289 // Case 3: the base of the indirect field is a field and we should
1290 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001291 } else {
1292 // We've found a member of an anonymous struct/union that is
1293 // inside a non-anonymous struct/union, so in a well-formed
1294 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001295 CXXMethodDecl *method = tryCaptureCXXThis();
1296 if (!method) {
1297 Diag(loc, diag::err_invalid_member_use_in_static_method)
1298 << indirectField->getDeclName();
1299 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001300 }
1301
John McCallf3a88602011-02-03 08:15:49 +00001302 // Our base object expression is "this".
1303 baseObjectExpr =
1304 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1305 /*isImplicit=*/ true);
1306 baseObjectIsPointer = true;
1307 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001308 }
1309
1310 // Build the implicit member references to the field of the
1311 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001312 Expr *result = baseObjectExpr;
1313 IndirectFieldDecl::chain_iterator
1314 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001315
John McCallf3a88602011-02-03 08:15:49 +00001316 // Build the first member access in the chain with full information.
1317 if (!baseVariable) {
1318 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001319
John McCallf3a88602011-02-03 08:15:49 +00001320 // FIXME: use the real found-decl info!
1321 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001322
John McCallf3a88602011-02-03 08:15:49 +00001323 // Make a nameInfo that properly uses the anonymous name.
1324 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001325
John McCallf3a88602011-02-03 08:15:49 +00001326 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001327 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001328 memberNameInfo).take();
1329 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001330
John McCallf3a88602011-02-03 08:15:49 +00001331 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001332 }
1333
John McCallf3a88602011-02-03 08:15:49 +00001334 // In all cases, we should now skip the first declaration in the chain.
1335 ++FI;
1336
Douglas Gregore10f36d2011-02-18 02:44:58 +00001337 while (FI != FEnd) {
1338 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001339
1340 // FIXME: these are somewhat meaningless
1341 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1342 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001343
1344 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001345 (FI == FEnd? SS : EmptySS), field,
1346 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001347 .take();
1348 }
1349
1350 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001351}
1352
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001353/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001354/// possibly a list of template arguments.
1355///
1356/// If this produces template arguments, it is permitted to call
1357/// DecomposeTemplateName.
1358///
1359/// This actually loses a lot of source location information for
1360/// non-standard name kinds; we should consider preserving that in
1361/// some way.
1362static void DecomposeUnqualifiedId(Sema &SemaRef,
1363 const UnqualifiedId &Id,
1364 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001365 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001366 const TemplateArgumentListInfo *&TemplateArgs) {
1367 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1368 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1369 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1370
1371 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1372 Id.TemplateId->getTemplateArgs(),
1373 Id.TemplateId->NumArgs);
1374 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1375 TemplateArgsPtr.release();
1376
John McCall3e56fd42010-08-23 07:28:44 +00001377 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001378 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1379 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001380 TemplateArgs = &Buffer;
1381 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001382 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001383 TemplateArgs = 0;
1384 }
1385}
1386
John McCall2d74de92009-12-01 22:10:20 +00001387/// Determines if the given class is provably not derived from all of
1388/// the prospective base classes.
1389static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1390 CXXRecordDecl *Record,
1391 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001392 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001393 return false;
1394
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001395 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001396 if (!RD) return false;
1397 Record = cast<CXXRecordDecl>(RD);
1398
John McCall2d74de92009-12-01 22:10:20 +00001399 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1400 E = Record->bases_end(); I != E; ++I) {
1401 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1402 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1403 if (!BaseRT) return false;
1404
1405 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001406 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1407 return false;
1408 }
1409
1410 return true;
1411}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001412
John McCall2d74de92009-12-01 22:10:20 +00001413enum IMAKind {
1414 /// The reference is definitely not an instance member access.
1415 IMA_Static,
1416
1417 /// The reference may be an implicit instance member access.
1418 IMA_Mixed,
1419
1420 /// The reference may be to an instance member, but it is invalid if
1421 /// so, because the context is not an instance method.
1422 IMA_Mixed_StaticContext,
1423
1424 /// The reference may be to an instance member, but it is invalid if
1425 /// so, because the context is from an unrelated class.
1426 IMA_Mixed_Unrelated,
1427
1428 /// The reference is definitely an implicit instance member access.
1429 IMA_Instance,
1430
1431 /// The reference may be to an unresolved using declaration.
1432 IMA_Unresolved,
1433
1434 /// The reference may be to an unresolved using declaration and the
1435 /// context is not an instance method.
1436 IMA_Unresolved_StaticContext,
1437
John McCall2d74de92009-12-01 22:10:20 +00001438 /// All possible referrents are instance members and the current
1439 /// context is not an instance method.
1440 IMA_Error_StaticContext,
1441
1442 /// All possible referrents are instance members of an unrelated
1443 /// class.
1444 IMA_Error_Unrelated
1445};
1446
1447/// The given lookup names class member(s) and is not being used for
1448/// an address-of-member expression. Classify the type of access
1449/// according to whether it's possible that this reference names an
1450/// instance member. This is best-effort; it is okay to
1451/// conservatively answer "yes", in which case some errors will simply
1452/// not be caught until template-instantiation.
1453static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1454 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001455 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001456
John McCall87fe5d52010-05-20 01:18:31 +00001457 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001458 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001459 (!isa<CXXMethodDecl>(DC) ||
1460 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001461
1462 if (R.isUnresolvableResult())
1463 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1464
1465 // Collect all the declaring classes of instance members we find.
1466 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001467 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001468 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001470 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001471
John McCalla8ae2222010-04-06 21:38:20 +00001472 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001473 if (dyn_cast<FieldDecl>(D))
1474 hasField = true;
1475
John McCall2d74de92009-12-01 22:10:20 +00001476 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001477 Classes.insert(R->getCanonicalDecl());
1478 }
1479 else
1480 hasNonInstance = true;
1481 }
1482
1483 // If we didn't find any instance members, it can't be an implicit
1484 // member reference.
1485 if (Classes.empty())
1486 return IMA_Static;
1487
1488 // If the current context is not an instance method, it can't be
1489 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001490 if (isStaticContext) {
1491 if (hasNonInstance)
1492 return IMA_Mixed_StaticContext;
1493
1494 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1495 // C++0x [expr.prim.general]p10:
1496 // An id-expression that denotes a non-static data member or non-static
1497 // member function of a class can only be used:
1498 // (...)
1499 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1500 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1501 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1502 if (isUnevaluatedExpression)
1503 return IMA_Mixed_StaticContext;
1504 }
1505
1506 return IMA_Error_StaticContext;
1507 }
John McCall2d74de92009-12-01 22:10:20 +00001508
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001509 CXXRecordDecl *
1510 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1511
1512 // [class.mfct.non-static]p3:
1513 // ...is used in the body of a non-static member function of class X,
1514 // if name lookup (3.4.1) resolves the name in the id-expression to a
1515 // non-static non-type member of some class C [...]
1516 // ...if C is not X or a base class of X, the class member access expression
1517 // is ill-formed.
1518 if (R.getNamingClass() &&
1519 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1520 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1521 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1522
John McCall2d74de92009-12-01 22:10:20 +00001523 // If we can prove that the current context is unrelated to all the
1524 // declaring classes, it can't be an implicit member reference (in
1525 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001526 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001527 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1528
1529 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1530}
1531
1532/// Diagnose a reference to a field with no object available.
1533static void DiagnoseInstanceReference(Sema &SemaRef,
1534 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001535 NamedDecl *rep,
1536 const DeclarationNameInfo &nameInfo) {
1537 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001538 SourceRange Range(Loc);
1539 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1540
John McCallf3a88602011-02-03 08:15:49 +00001541 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001542 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1543 if (MD->isStatic()) {
1544 // "invalid use of member 'x' in static member function"
1545 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001546 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001547 return;
1548 }
1549 }
1550
1551 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001552 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001553 return;
1554 }
1555
1556 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001557}
1558
John McCalld681c392009-12-16 08:11:27 +00001559/// Diagnose an empty lookup.
1560///
1561/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001562bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1563 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001564 DeclarationName Name = R.getLookupName();
1565
John McCalld681c392009-12-16 08:11:27 +00001566 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001567 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001568 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1569 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001570 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001571 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001572 diagnostic_suggest = diag::err_undeclared_use_suggest;
1573 }
John McCalld681c392009-12-16 08:11:27 +00001574
Douglas Gregor598b08f2009-12-31 05:20:13 +00001575 // If the original lookup was an unqualified lookup, fake an
1576 // unqualified lookup. This is useful when (for example) the
1577 // original lookup would not have found something because it was a
1578 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001579 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001580 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001581 if (isa<CXXRecordDecl>(DC)) {
1582 LookupQualifiedName(R, DC);
1583
1584 if (!R.empty()) {
1585 // Don't give errors about ambiguities in this lookup.
1586 R.suppressDiagnostics();
1587
1588 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1589 bool isInstance = CurMethod &&
1590 CurMethod->isInstance() &&
1591 DC == CurMethod->getParent();
1592
1593 // Give a code modification hint to insert 'this->'.
1594 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1595 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001596 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001597 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1598 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001599 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001600 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001601 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001602 Diag(R.getNameLoc(), diagnostic) << Name
1603 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1604 QualType DepThisType = DepMethod->getThisType(Context);
1605 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1606 R.getNameLoc(), DepThisType, false);
1607 TemplateArgumentListInfo TList;
1608 if (ULE->hasExplicitTemplateArgs())
1609 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001610
Douglas Gregore16af532011-02-28 18:50:33 +00001611 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001612 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001613 CXXDependentScopeMemberExpr *DepExpr =
1614 CXXDependentScopeMemberExpr::Create(
1615 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001616 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001617 R.getLookupNameInfo(), &TList);
1618 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001619 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001620 // FIXME: we should be able to handle this case too. It is correct
1621 // to add this-> here. This is a workaround for PR7947.
1622 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001623 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001624 } else {
John McCalld681c392009-12-16 08:11:27 +00001625 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001626 }
John McCalld681c392009-12-16 08:11:27 +00001627
1628 // Do we really want to note all of these?
1629 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1630 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1631
1632 // Tell the callee to try to recover.
1633 return false;
1634 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001635
1636 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001637 }
1638 }
1639
Douglas Gregor598b08f2009-12-31 05:20:13 +00001640 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001641 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001642 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001643 if (!R.empty()) {
1644 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1645 if (SS.isEmpty())
1646 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1647 << FixItHint::CreateReplacement(R.getNameLoc(),
1648 R.getLookupName().getAsString());
1649 else
1650 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1651 << Name << computeDeclContext(SS, false) << R.getLookupName()
1652 << SS.getRange()
1653 << FixItHint::CreateReplacement(R.getNameLoc(),
1654 R.getLookupName().getAsString());
1655 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1656 Diag(ND->getLocation(), diag::note_previous_decl)
1657 << ND->getDeclName();
1658
1659 // Tell the callee to try to recover.
1660 return false;
1661 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001662
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001663 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1664 // FIXME: If we ended up with a typo for a type name or
1665 // Objective-C class name, we're in trouble because the parser
1666 // is in the wrong place to recover. Suggest the typo
1667 // correction, but don't make it a fix-it since we're not going
1668 // to recover well anyway.
1669 if (SS.isEmpty())
1670 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1671 else
1672 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1673 << Name << computeDeclContext(SS, false) << R.getLookupName()
1674 << SS.getRange();
1675
1676 // Don't try to recover; it won't work.
1677 return true;
1678 }
1679 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001680 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001681 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001682 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001683 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001684 else
Douglas Gregor25363982010-01-01 00:15:04 +00001685 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001686 << Name << computeDeclContext(SS, false) << Corrected
1687 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001688 return true;
1689 }
Douglas Gregor25363982010-01-01 00:15:04 +00001690 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001691 }
1692
1693 // Emit a special diagnostic for failed member lookups.
1694 // FIXME: computing the declaration context might fail here (?)
1695 if (!SS.isEmpty()) {
1696 Diag(R.getNameLoc(), diag::err_no_member)
1697 << Name << computeDeclContext(SS, false)
1698 << SS.getRange();
1699 return true;
1700 }
1701
John McCalld681c392009-12-16 08:11:27 +00001702 // Give up, we can't recover.
1703 Diag(R.getNameLoc(), diagnostic) << Name;
1704 return true;
1705}
1706
Douglas Gregor05fcf842010-11-02 20:36:02 +00001707ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1708 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001709 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1710 if (!IDecl)
1711 return 0;
1712 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1713 if (!ClassImpDecl)
1714 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001715 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001716 if (!property)
1717 return 0;
1718 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001719 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1720 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001721 return 0;
1722 return property;
1723}
1724
Douglas Gregor05fcf842010-11-02 20:36:02 +00001725bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1726 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1727 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1728 if (!IDecl)
1729 return false;
1730 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1731 if (!ClassImpDecl)
1732 return false;
1733 if (ObjCPropertyImplDecl *PIDecl
1734 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1735 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1736 PIDecl->getPropertyIvarDecl())
1737 return false;
1738
1739 return true;
1740}
1741
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001742ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1743 IdentifierInfo *II,
1744 SourceLocation NameLoc) {
1745 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001746 bool LookForIvars;
1747 if (Lookup.empty())
1748 LookForIvars = true;
1749 else if (CurMeth->isClassMethod())
1750 LookForIvars = false;
1751 else
1752 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001753 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1754 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001755 if (!LookForIvars)
1756 return 0;
1757
Fariborz Jahanian18722982010-07-17 00:59:30 +00001758 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1759 if (!IDecl)
1760 return 0;
1761 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001762 if (!ClassImpDecl)
1763 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001764 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001765 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001766 if (!property)
1767 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001768 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001769 DynamicImplSeen =
1770 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001771 // property implementation has a designated ivar. No need to assume a new
1772 // one.
1773 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1774 return 0;
1775 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001776 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001777 QualType PropType = Context.getCanonicalType(property->getType());
1778 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001779 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001780 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001781 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001782 (Expr *)0, true);
1783 ClassImpDecl->addDecl(Ivar);
1784 IDecl->makeDeclVisibleInContext(Ivar, false);
1785 property->setPropertyIvarDecl(Ivar);
1786 return Ivar;
1787 }
1788 return 0;
1789}
1790
John McCalldadc5752010-08-24 06:29:42 +00001791ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001792 CXXScopeSpec &SS,
1793 UnqualifiedId &Id,
1794 bool HasTrailingLParen,
1795 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001796 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1797 "cannot be direct & operand and have a trailing lparen");
1798
1799 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001800 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001801
John McCall10eae182009-11-30 22:42:35 +00001802 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001803
1804 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001805 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001806 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001807 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001808
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001809 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001810 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001811 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001812
John McCalle66edc12009-11-24 19:00:30 +00001813 // C++ [temp.dep.expr]p3:
1814 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001815 // -- an identifier that was declared with a dependent type,
1816 // (note: handled after lookup)
1817 // -- a template-id that is dependent,
1818 // (note: handled in BuildTemplateIdExpr)
1819 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001820 // -- a nested-name-specifier that contains a class-name that
1821 // names a dependent type.
1822 // Determine whether this is a member of an unknown specialization;
1823 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001824 bool DependentID = false;
1825 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1826 Name.getCXXNameType()->isDependentType()) {
1827 DependentID = true;
1828 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001829 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001830 if (RequireCompleteDeclContext(SS, DC))
1831 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001832 } else {
1833 DependentID = true;
1834 }
1835 }
1836
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001837 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001838 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001839 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001840
Fariborz Jahanian86151342010-07-22 23:33:21 +00001841 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001842 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001843 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001844 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001845 // Lookup the template name again to correctly establish the context in
1846 // which it was found. This is really unfortunate as we already did the
1847 // lookup to determine that it was a template name in the first place. If
1848 // this becomes a performance hit, we can work harder to preserve those
1849 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001850 bool MemberOfUnknownSpecialization;
1851 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1852 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001853
1854 if (MemberOfUnknownSpecialization ||
1855 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1856 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1857 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001858 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001859 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001860 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregora5226932011-02-04 13:35:07 +00001862 // If the result might be in a dependent base class, this is a dependent
1863 // id-expression.
1864 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1865 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1866 TemplateArgs);
1867
John McCalle66edc12009-11-24 19:00:30 +00001868 // If this reference is in an Objective-C method, then we need to do
1869 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001870 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001871 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001872 if (E.isInvalid())
1873 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001875 if (Expr *Ex = E.takeAs<Expr>())
1876 return Owned(Ex);
1877
1878 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001879 if (getLangOptions().ObjCDefaultSynthProperties &&
1880 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001881 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001882 if (const ObjCPropertyDecl *Property =
1883 canSynthesizeProvisionalIvar(II)) {
1884 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1885 Diag(Property->getLocation(), diag::note_property_declare);
1886 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001887 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1888 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001889 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001890 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001891 // for further use, this must be set to false if in class method.
1892 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001893 }
Chris Lattner59a25942008-03-31 00:36:02 +00001894 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001895
John McCalle66edc12009-11-24 19:00:30 +00001896 if (R.isAmbiguous())
1897 return ExprError();
1898
Douglas Gregor171c45a2009-02-18 21:56:37 +00001899 // Determine whether this name might be a candidate for
1900 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001901 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001902
John McCalle66edc12009-11-24 19:00:30 +00001903 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001904 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001905 // in C90, extension in C99, forbidden in C++).
1906 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1907 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1908 if (D) R.addDecl(D);
1909 }
1910
1911 // If this name wasn't predeclared and if this is not a function
1912 // call, diagnose the problem.
1913 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001914 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001915 return ExprError();
1916
1917 assert(!R.empty() &&
1918 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001919
1920 // If we found an Objective-C instance variable, let
1921 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001922 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001923 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1924 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001925 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001926 assert(E.isInvalid() || E.get());
1927 return move(E);
1928 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001929 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001930 }
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCalle66edc12009-11-24 19:00:30 +00001932 // This is guaranteed from this point on.
1933 assert(!R.empty() || ADL);
1934
John McCall2d74de92009-12-01 22:10:20 +00001935 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001936 // C++ [class.mfct.non-static]p3:
1937 // When an id-expression that is not part of a class member access
1938 // syntax and not used to form a pointer to member is used in the
1939 // body of a non-static member function of class X, if name lookup
1940 // resolves the name in the id-expression to a non-static non-type
1941 // member of some class C, the id-expression is transformed into a
1942 // class member access expression using (*this) as the
1943 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001944 //
1945 // But we don't actually need to do this for '&' operands if R
1946 // resolved to a function or overloaded function set, because the
1947 // expression is ill-formed if it actually works out to be a
1948 // non-static member function:
1949 //
1950 // C++ [expr.ref]p4:
1951 // Otherwise, if E1.E2 refers to a non-static member function. . .
1952 // [t]he expression can be used only as the left-hand operand of a
1953 // member function call.
1954 //
1955 // There are other safeguards against such uses, but it's important
1956 // to get this right here so that we don't end up making a
1957 // spuriously dependent expression if we're inside a dependent
1958 // instance method.
John McCall57500772009-12-16 12:17:52 +00001959 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001960 bool MightBeImplicitMember;
1961 if (!isAddressOfOperand)
1962 MightBeImplicitMember = true;
1963 else if (!SS.isEmpty())
1964 MightBeImplicitMember = false;
1965 else if (R.isOverloadedResult())
1966 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001967 else if (R.isUnresolvableResult())
1968 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001969 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001970 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1971 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001972
1973 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001974 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001975 }
1976
John McCalle66edc12009-11-24 19:00:30 +00001977 if (TemplateArgs)
1978 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001979
John McCalle66edc12009-11-24 19:00:30 +00001980 return BuildDeclarationNameExpr(SS, R, ADL);
1981}
1982
John McCall57500772009-12-16 12:17:52 +00001983/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001984ExprResult
John McCall57500772009-12-16 12:17:52 +00001985Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1986 LookupResult &R,
1987 const TemplateArgumentListInfo *TemplateArgs) {
1988 switch (ClassifyImplicitMemberAccess(*this, R)) {
1989 case IMA_Instance:
1990 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1991
John McCall57500772009-12-16 12:17:52 +00001992 case IMA_Mixed:
1993 case IMA_Mixed_Unrelated:
1994 case IMA_Unresolved:
1995 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1996
1997 case IMA_Static:
1998 case IMA_Mixed_StaticContext:
1999 case IMA_Unresolved_StaticContext:
2000 if (TemplateArgs)
2001 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2002 return BuildDeclarationNameExpr(SS, R, false);
2003
2004 case IMA_Error_StaticContext:
2005 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002006 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2007 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002008 return ExprError();
2009 }
2010
2011 llvm_unreachable("unexpected instance member access kind");
2012 return ExprError();
2013}
2014
John McCall10eae182009-11-30 22:42:35 +00002015/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2016/// declaration name, generally during template instantiation.
2017/// There's a large number of things which don't need to be done along
2018/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002019ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002020Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002021 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002022 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002023 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002024 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002025
John McCall0b66eb32010-05-01 00:40:08 +00002026 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002027 return ExprError();
2028
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002029 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002030 LookupQualifiedName(R, DC);
2031
2032 if (R.isAmbiguous())
2033 return ExprError();
2034
2035 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002036 Diag(NameInfo.getLoc(), diag::err_no_member)
2037 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002038 return ExprError();
2039 }
2040
2041 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2042}
2043
2044/// LookupInObjCMethod - The parser has read a name in, and Sema has
2045/// detected that we're currently inside an ObjC method. Perform some
2046/// additional lookup.
2047///
2048/// Ideally, most of this would be done by lookup, but there's
2049/// actually quite a lot of extra work involved.
2050///
2051/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002052ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002053Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002054 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002055 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002056 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002057
John McCalle66edc12009-11-24 19:00:30 +00002058 // There are two cases to handle here. 1) scoped lookup could have failed,
2059 // in which case we should look for an ivar. 2) scoped lookup could have
2060 // found a decl, but that decl is outside the current instance method (i.e.
2061 // a global variable). In these two cases, we do a lookup for an ivar with
2062 // this name, if the lookup sucedes, we replace it our current decl.
2063
2064 // If we're in a class method, we don't normally want to look for
2065 // ivars. But if we don't find anything else, and there's an
2066 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002067 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002068
2069 bool LookForIvars;
2070 if (Lookup.empty())
2071 LookForIvars = true;
2072 else if (IsClassMethod)
2073 LookForIvars = false;
2074 else
2075 LookForIvars = (Lookup.isSingleResult() &&
2076 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002077 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002078 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002079 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002080 ObjCInterfaceDecl *ClassDeclared;
2081 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2082 // Diagnose using an ivar in a class method.
2083 if (IsClassMethod)
2084 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2085 << IV->getDeclName());
2086
2087 // If we're referencing an invalid decl, just return this as a silent
2088 // error node. The error diagnostic was already emitted on the decl.
2089 if (IV->isInvalidDecl())
2090 return ExprError();
2091
2092 // Check if referencing a field with __attribute__((deprecated)).
2093 if (DiagnoseUseOfDecl(IV, Loc))
2094 return ExprError();
2095
2096 // Diagnose the use of an ivar outside of the declaring class.
2097 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2098 ClassDeclared != IFace)
2099 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2100
2101 // FIXME: This should use a new expr for a direct reference, don't
2102 // turn this into Self->ivar, just return a BareIVarExpr or something.
2103 IdentifierInfo &II = Context.Idents.get("self");
2104 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002105 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002106 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002107 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002108 SelfName, false, false);
2109 if (SelfExpr.isInvalid())
2110 return ExprError();
2111
John Wiegley01296292011-04-08 18:41:53 +00002112 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2113 if (SelfExpr.isInvalid())
2114 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002115
John McCalle66edc12009-11-24 19:00:30 +00002116 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002117 Expr *base = SelfExpr.take();
2118 base = base->IgnoreParenImpCasts();
2119 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2120 const NamedDecl *ND = DE->getDecl();
2121 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002122 // relax the rule such that it is allowed to have a shadow 'self'
2123 // where stand-alone ivar can be found in this 'self' object.
2124 // This is to match gcc's behavior.
2125 ObjCInterfaceDecl *selfIFace = 0;
2126 if (const ObjCObjectPointerType *OPT =
2127 base->getType()->getAsObjCInterfacePointerType())
2128 selfIFace = OPT->getInterfaceDecl();
2129 if (!selfIFace ||
2130 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002131 Diag(Loc, diag::error_implicit_ivar_access)
2132 << IV->getDeclName();
2133 Diag(ND->getLocation(), diag::note_declared_at);
2134 return ExprError();
2135 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002136 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002137 }
John McCalle66edc12009-11-24 19:00:30 +00002138 return Owned(new (Context)
2139 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002140 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002141 }
Chris Lattner87313662010-04-12 05:10:17 +00002142 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002143 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002144 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002145 ObjCInterfaceDecl *ClassDeclared;
2146 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2147 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2148 IFace == ClassDeclared)
2149 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2150 }
2151 }
2152
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002153 if (Lookup.empty() && II && AllowBuiltinCreation) {
2154 // FIXME. Consolidate this with similar code in LookupName.
2155 if (unsigned BuiltinID = II->getBuiltinID()) {
2156 if (!(getLangOptions().CPlusPlus &&
2157 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2158 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2159 S, Lookup.isForRedeclaration(),
2160 Lookup.getNameLoc());
2161 if (D) Lookup.addDecl(D);
2162 }
2163 }
2164 }
John McCalle66edc12009-11-24 19:00:30 +00002165 // Sentinel value saying that we didn't do anything special.
2166 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002167}
John McCalld14a8642009-11-21 08:51:07 +00002168
John McCall16df1e52010-03-30 21:47:33 +00002169/// \brief Cast a base object to a member's actual type.
2170///
2171/// Logically this happens in three phases:
2172///
2173/// * First we cast from the base type to the naming class.
2174/// The naming class is the class into which we were looking
2175/// when we found the member; it's the qualifier type if a
2176/// qualifier was provided, and otherwise it's the base type.
2177///
2178/// * Next we cast from the naming class to the declaring class.
2179/// If the member we found was brought into a class's scope by
2180/// a using declaration, this is that class; otherwise it's
2181/// the class declaring the member.
2182///
2183/// * Finally we cast from the declaring class to the "true"
2184/// declaring class of the member. This conversion does not
2185/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002186ExprResult
2187Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002188 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002189 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002190 NamedDecl *Member) {
2191 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2192 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002193 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002194
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002195 QualType DestRecordType;
2196 QualType DestType;
2197 QualType FromRecordType;
2198 QualType FromType = From->getType();
2199 bool PointerConversions = false;
2200 if (isa<FieldDecl>(Member)) {
2201 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002202
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002203 if (FromType->getAs<PointerType>()) {
2204 DestType = Context.getPointerType(DestRecordType);
2205 FromRecordType = FromType->getPointeeType();
2206 PointerConversions = true;
2207 } else {
2208 DestType = DestRecordType;
2209 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002210 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002211 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2212 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002213 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002214
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002215 DestType = Method->getThisType(Context);
2216 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002217
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002218 if (FromType->getAs<PointerType>()) {
2219 FromRecordType = FromType->getPointeeType();
2220 PointerConversions = true;
2221 } else {
2222 FromRecordType = FromType;
2223 DestType = DestRecordType;
2224 }
2225 } else {
2226 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002227 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002228 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002229
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002230 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002231 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002232
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002233 // If the unqualified types are the same, no conversion is necessary.
2234 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002235 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002236
John McCall16df1e52010-03-30 21:47:33 +00002237 SourceRange FromRange = From->getSourceRange();
2238 SourceLocation FromLoc = FromRange.getBegin();
2239
John McCall2536c6d2010-08-25 10:28:54 +00002240 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002241
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002242 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002243 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002244 // class name.
2245 //
2246 // If the member was a qualified name and the qualified referred to a
2247 // specific base subobject type, we'll cast to that intermediate type
2248 // first and then to the object in which the member is declared. That allows
2249 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2250 //
2251 // class Base { public: int x; };
2252 // class Derived1 : public Base { };
2253 // class Derived2 : public Base { };
2254 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2255 //
2256 // void VeryDerived::f() {
2257 // x = 17; // error: ambiguous base subobjects
2258 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2259 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002260 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002261 QualType QType = QualType(Qualifier->getAsType(), 0);
2262 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2263 assert(QType->isRecordType() && "lookup done with non-record type");
2264
2265 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2266
2267 // In C++98, the qualifier type doesn't actually have to be a base
2268 // type of the object type, in which case we just ignore it.
2269 // Otherwise build the appropriate casts.
2270 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002271 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002272 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002273 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002274 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002275
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002276 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002277 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002278 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2279 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002280
2281 FromType = QType;
2282 FromRecordType = QRecordType;
2283
2284 // If the qualifier type was the same as the destination type,
2285 // we're done.
2286 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002287 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002288 }
2289 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002290
John McCall16df1e52010-03-30 21:47:33 +00002291 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002292
John McCall16df1e52010-03-30 21:47:33 +00002293 // If we actually found the member through a using declaration, cast
2294 // down to the using declaration's type.
2295 //
2296 // Pointer equality is fine here because only one declaration of a
2297 // class ever has member declarations.
2298 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2299 assert(isa<UsingShadowDecl>(FoundDecl));
2300 QualType URecordType = Context.getTypeDeclType(
2301 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2302
2303 // We only need to do this if the naming-class to declaring-class
2304 // conversion is non-trivial.
2305 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2306 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002307 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002308 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002309 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002310 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002311
John McCall16df1e52010-03-30 21:47:33 +00002312 QualType UType = URecordType;
2313 if (PointerConversions)
2314 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002315 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2316 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002317 FromType = UType;
2318 FromRecordType = URecordType;
2319 }
2320
2321 // We don't do access control for the conversion from the
2322 // declaring class to the true declaring class.
2323 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002324 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002325
John McCallcf142162010-08-07 06:22:56 +00002326 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002327 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2328 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002329 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002330 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002331
John Wiegley01296292011-04-08 18:41:53 +00002332 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2333 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002334}
Douglas Gregor3256d042009-06-30 15:47:41 +00002335
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002336/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002337static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002338 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002339 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002340 const DeclarationNameInfo &MemberNameInfo,
2341 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002342 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002343 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002344 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002345 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002346 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002347}
2348
John McCallfeb624a2010-11-23 20:48:44 +00002349static ExprResult
2350BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2351 const CXXScopeSpec &SS, FieldDecl *Field,
2352 DeclAccessPair FoundDecl,
2353 const DeclarationNameInfo &MemberNameInfo) {
2354 // x.a is an l-value if 'a' has a reference type. Otherwise:
2355 // x.a is an l-value/x-value/pr-value if the base is (and note
2356 // that *x is always an l-value), except that if the base isn't
2357 // an ordinary object then we must have an rvalue.
2358 ExprValueKind VK = VK_LValue;
2359 ExprObjectKind OK = OK_Ordinary;
2360 if (!IsArrow) {
2361 if (BaseExpr->getObjectKind() == OK_Ordinary)
2362 VK = BaseExpr->getValueKind();
2363 else
2364 VK = VK_RValue;
2365 }
2366 if (VK != VK_RValue && Field->isBitField())
2367 OK = OK_BitField;
2368
2369 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2370 QualType MemberType = Field->getType();
2371 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2372 MemberType = Ref->getPointeeType();
2373 VK = VK_LValue;
2374 } else {
2375 QualType BaseType = BaseExpr->getType();
2376 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2377
2378 Qualifiers BaseQuals = BaseType.getQualifiers();
2379
2380 // GC attributes are never picked up by members.
2381 BaseQuals.removeObjCGCAttr();
2382
2383 // CVR attributes from the base are picked up by members,
2384 // except that 'mutable' members don't pick up 'const'.
2385 if (Field->isMutable()) BaseQuals.removeConst();
2386
2387 Qualifiers MemberQuals
2388 = S.Context.getCanonicalType(MemberType).getQualifiers();
2389
2390 // TR 18037 does not allow fields to be declared with address spaces.
2391 assert(!MemberQuals.hasAddressSpace());
2392
2393 Qualifiers Combined = BaseQuals + MemberQuals;
2394 if (Combined != MemberQuals)
2395 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2396 }
2397
2398 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002399 ExprResult Base =
2400 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2401 FoundDecl, Field);
2402 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002403 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002404 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002405 Field, FoundDecl, MemberNameInfo,
2406 MemberType, VK, OK));
2407}
2408
John McCall2d74de92009-12-01 22:10:20 +00002409/// Builds an implicit member access expression. The current context
2410/// is known to be an instance method, and the given unqualified lookup
2411/// set is known to contain only instance members, at least one of which
2412/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002413ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002414Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2415 LookupResult &R,
2416 const TemplateArgumentListInfo *TemplateArgs,
2417 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002418 assert(!R.empty() && !R.isAmbiguous());
2419
John McCallf3a88602011-02-03 08:15:49 +00002420 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002421
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002422 // We may have found a field within an anonymous union or struct
2423 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002424 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002425 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002426 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002427
John McCallf3a88602011-02-03 08:15:49 +00002428 // If this is known to be an instance access, go ahead and build an
2429 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002430 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002431 CXXMethodDecl *method = tryCaptureCXXThis();
2432 assert(method && "didn't correctly pre-flight capture of 'this'");
2433
2434 QualType thisType = method->getThisType(Context);
2435 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002436 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002437 SourceLocation Loc = R.getNameLoc();
2438 if (SS.getRange().isValid())
2439 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002440 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002441 }
2442
John McCallf3a88602011-02-03 08:15:49 +00002443 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002444 /*OpLoc*/ SourceLocation(),
2445 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002446 SS,
2447 /*FirstQualifierInScope*/ 0,
2448 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002449}
2450
John McCalle66edc12009-11-24 19:00:30 +00002451bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002452 const LookupResult &R,
2453 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002454 // Only when used directly as the postfix-expression of a call.
2455 if (!HasTrailingLParen)
2456 return false;
2457
2458 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002459 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002460 return false;
2461
2462 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002463 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002464 return false;
2465
2466 // Turn off ADL when we find certain kinds of declarations during
2467 // normal lookup:
2468 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2469 NamedDecl *D = *I;
2470
2471 // C++0x [basic.lookup.argdep]p3:
2472 // -- a declaration of a class member
2473 // Since using decls preserve this property, we check this on the
2474 // original decl.
John McCall57500772009-12-16 12:17:52 +00002475 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002476 return false;
2477
2478 // C++0x [basic.lookup.argdep]p3:
2479 // -- a block-scope function declaration that is not a
2480 // using-declaration
2481 // NOTE: we also trigger this for function templates (in fact, we
2482 // don't check the decl type at all, since all other decl types
2483 // turn off ADL anyway).
2484 if (isa<UsingShadowDecl>(D))
2485 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2486 else if (D->getDeclContext()->isFunctionOrMethod())
2487 return false;
2488
2489 // C++0x [basic.lookup.argdep]p3:
2490 // -- a declaration that is neither a function or a function
2491 // template
2492 // And also for builtin functions.
2493 if (isa<FunctionDecl>(D)) {
2494 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2495
2496 // But also builtin functions.
2497 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2498 return false;
2499 } else if (!isa<FunctionTemplateDecl>(D))
2500 return false;
2501 }
2502
2503 return true;
2504}
2505
2506
John McCalld14a8642009-11-21 08:51:07 +00002507/// Diagnoses obvious problems with the use of the given declaration
2508/// as an expression. This is only actually called for lookups that
2509/// were not overloaded, and it doesn't promise that the declaration
2510/// will in fact be used.
2511static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002512 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002513 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2514 return true;
2515 }
2516
2517 if (isa<ObjCInterfaceDecl>(D)) {
2518 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2519 return true;
2520 }
2521
2522 if (isa<NamespaceDecl>(D)) {
2523 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2524 return true;
2525 }
2526
2527 return false;
2528}
2529
John McCalldadc5752010-08-24 06:29:42 +00002530ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002531Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002532 LookupResult &R,
2533 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002534 // If this is a single, fully-resolved result and we don't need ADL,
2535 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002536 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002537 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2538 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002539
2540 // We only need to check the declaration if there's exactly one
2541 // result, because in the overloaded case the results can only be
2542 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002543 if (R.isSingleResult() &&
2544 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002545 return ExprError();
2546
John McCall58cc69d2010-01-27 01:50:18 +00002547 // Otherwise, just build an unresolved lookup expression. Suppress
2548 // any lookup-related diagnostics; we'll hash these out later, when
2549 // we've picked a target.
2550 R.suppressDiagnostics();
2551
John McCalld14a8642009-11-21 08:51:07 +00002552 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002553 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002554 SS.getWithLocInContext(Context),
2555 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002556 NeedsADL, R.isOverloadedResult(),
2557 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002558
2559 return Owned(ULE);
2560}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002561
John McCalld14a8642009-11-21 08:51:07 +00002562/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002563ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002564Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002565 const DeclarationNameInfo &NameInfo,
2566 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002567 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002568 assert(!isa<FunctionTemplateDecl>(D) &&
2569 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002570
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002571 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002572 if (CheckDeclInExpr(*this, Loc, D))
2573 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002574
Douglas Gregore7488b92009-12-01 16:58:18 +00002575 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2576 // Specifically diagnose references to class templates that are missing
2577 // a template argument list.
2578 Diag(Loc, diag::err_template_decl_ref)
2579 << Template << SS.getRange();
2580 Diag(Template->getLocation(), diag::note_template_decl_here);
2581 return ExprError();
2582 }
2583
2584 // Make sure that we're referring to a value.
2585 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2586 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002587 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002588 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002589 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002590 return ExprError();
2591 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002592
Douglas Gregor171c45a2009-02-18 21:56:37 +00002593 // Check whether this declaration can be used. Note that we suppress
2594 // this check when we're going to perform argument-dependent lookup
2595 // on this function name, because this might not be the function
2596 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002597 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002598 return ExprError();
2599
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002600 // Only create DeclRefExpr's for valid Decl's.
2601 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002602 return ExprError();
2603
John McCallf3a88602011-02-03 08:15:49 +00002604 // Handle members of anonymous structs and unions. If we got here,
2605 // and the reference is to a class member indirect field, then this
2606 // must be the subject of a pointer-to-member expression.
2607 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2608 if (!indirectField->isCXXClassMember())
2609 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2610 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002611
Chris Lattner2a9d9892008-10-20 05:16:36 +00002612 // If the identifier reference is inside a block, and it refers to a value
2613 // that is outside the block, create a BlockDeclRefExpr instead of a
2614 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2615 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002616 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002617 // We do not do this for things like enum constants, global variables, etc,
2618 // as they do not get snapshotted.
2619 //
John McCall351762c2011-02-07 10:33:21 +00002620 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002621 case CR_Error:
2622 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002623
John McCallc63de662011-02-02 13:00:07 +00002624 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002625 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2626 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2627
2628 case CR_CaptureByRef:
2629 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2630 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002631
2632 case CR_NoCapture: {
2633 // If this reference is not in a block or if the referenced
2634 // variable is within the block, create a normal DeclRefExpr.
2635
2636 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002637 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002638
2639 switch (D->getKind()) {
2640 // Ignore all the non-ValueDecl kinds.
2641#define ABSTRACT_DECL(kind)
2642#define VALUE(type, base)
2643#define DECL(type, base) \
2644 case Decl::type:
2645#include "clang/AST/DeclNodes.inc"
2646 llvm_unreachable("invalid value decl kind");
2647 return ExprError();
2648
2649 // These shouldn't make it here.
2650 case Decl::ObjCAtDefsField:
2651 case Decl::ObjCIvar:
2652 llvm_unreachable("forming non-member reference to ivar?");
2653 return ExprError();
2654
2655 // Enum constants are always r-values and never references.
2656 // Unresolved using declarations are dependent.
2657 case Decl::EnumConstant:
2658 case Decl::UnresolvedUsingValue:
2659 valueKind = VK_RValue;
2660 break;
2661
2662 // Fields and indirect fields that got here must be for
2663 // pointer-to-member expressions; we just call them l-values for
2664 // internal consistency, because this subexpression doesn't really
2665 // exist in the high-level semantics.
2666 case Decl::Field:
2667 case Decl::IndirectField:
2668 assert(getLangOptions().CPlusPlus &&
2669 "building reference to field in C?");
2670
2671 // These can't have reference type in well-formed programs, but
2672 // for internal consistency we do this anyway.
2673 type = type.getNonReferenceType();
2674 valueKind = VK_LValue;
2675 break;
2676
2677 // Non-type template parameters are either l-values or r-values
2678 // depending on the type.
2679 case Decl::NonTypeTemplateParm: {
2680 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2681 type = reftype->getPointeeType();
2682 valueKind = VK_LValue; // even if the parameter is an r-value reference
2683 break;
2684 }
2685
2686 // For non-references, we need to strip qualifiers just in case
2687 // the template parameter was declared as 'const int' or whatever.
2688 valueKind = VK_RValue;
2689 type = type.getUnqualifiedType();
2690 break;
2691 }
2692
2693 case Decl::Var:
2694 // In C, "extern void blah;" is valid and is an r-value.
2695 if (!getLangOptions().CPlusPlus &&
2696 !type.hasQualifiers() &&
2697 type->isVoidType()) {
2698 valueKind = VK_RValue;
2699 break;
2700 }
2701 // fallthrough
2702
2703 case Decl::ImplicitParam:
2704 case Decl::ParmVar:
2705 // These are always l-values.
2706 valueKind = VK_LValue;
2707 type = type.getNonReferenceType();
2708 break;
2709
2710 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002711 const FunctionType *fty = type->castAs<FunctionType>();
2712
2713 // If we're referring to a function with an __unknown_anytype
2714 // result type, make the entire expression __unknown_anytype.
2715 if (fty->getResultType() == Context.UnknownAnyTy) {
2716 type = Context.UnknownAnyTy;
2717 valueKind = VK_RValue;
2718 break;
2719 }
2720
John McCallf4cd4f92011-02-09 01:13:10 +00002721 // Functions are l-values in C++.
2722 if (getLangOptions().CPlusPlus) {
2723 valueKind = VK_LValue;
2724 break;
2725 }
2726
2727 // C99 DR 316 says that, if a function type comes from a
2728 // function definition (without a prototype), that type is only
2729 // used for checking compatibility. Therefore, when referencing
2730 // the function, we pretend that we don't have the full function
2731 // type.
John McCall2979fe02011-04-12 00:42:48 +00002732 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2733 isa<FunctionProtoType>(fty))
2734 type = Context.getFunctionNoProtoType(fty->getResultType(),
2735 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002736
2737 // Functions are r-values in C.
2738 valueKind = VK_RValue;
2739 break;
2740 }
2741
2742 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002743 // If we're referring to a method with an __unknown_anytype
2744 // result type, make the entire expression __unknown_anytype.
2745 // This should only be possible with a type written directly.
2746 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2747 if (proto->getResultType() == Context.UnknownAnyTy) {
2748 type = Context.UnknownAnyTy;
2749 valueKind = VK_RValue;
2750 break;
2751 }
2752
John McCallf4cd4f92011-02-09 01:13:10 +00002753 // C++ methods are l-values if static, r-values if non-static.
2754 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2755 valueKind = VK_LValue;
2756 break;
2757 }
2758 // fallthrough
2759
2760 case Decl::CXXConversion:
2761 case Decl::CXXDestructor:
2762 case Decl::CXXConstructor:
2763 valueKind = VK_RValue;
2764 break;
2765 }
2766
2767 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2768 }
2769
John McCallc63de662011-02-02 13:00:07 +00002770 }
John McCall7decc9e2010-11-18 06:31:45 +00002771
John McCall351762c2011-02-07 10:33:21 +00002772 llvm_unreachable("unknown capture result");
2773 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002774}
Chris Lattnere168f762006-11-10 05:29:30 +00002775
John McCall2979fe02011-04-12 00:42:48 +00002776ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002777 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002778
Chris Lattnere168f762006-11-10 05:29:30 +00002779 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002780 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002781 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2782 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2783 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002784 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002785
Chris Lattnera81a0272008-01-12 08:14:25 +00002786 // Pre-defined identifiers are of type char[x], where x is the length of the
2787 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002788
Anders Carlsson2fb08242009-09-08 18:24:21 +00002789 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002790 if (!currentDecl && getCurBlock())
2791 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002792 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002793 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002794 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002795 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002796
Anders Carlsson0b209a82009-09-11 01:22:35 +00002797 QualType ResTy;
2798 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2799 ResTy = Context.DependentTy;
2800 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002801 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002802
Anders Carlsson0b209a82009-09-11 01:22:35 +00002803 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002804 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002805 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2806 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002807 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002808}
2809
John McCalldadc5752010-08-24 06:29:42 +00002810ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002811 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002812 bool Invalid = false;
2813 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2814 if (Invalid)
2815 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002816
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002817 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2818 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002819 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002820 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002821
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002822 QualType Ty;
2823 if (!getLangOptions().CPlusPlus)
2824 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2825 else if (Literal.isWide())
2826 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002827 else if (Literal.isMultiChar())
2828 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002829 else
2830 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002831
Sebastian Redl20614a72009-01-20 22:23:13 +00002832 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2833 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002834 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002835}
2836
John McCalldadc5752010-08-24 06:29:42 +00002837ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002838 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002839 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2840 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002841 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002842 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002843 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002844 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002845 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002846
Chris Lattner23b7eb62007-06-15 23:05:46 +00002847 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002848 // Add padding so that NumericLiteralParser can overread by one character.
2849 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002850 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002851
Chris Lattner67ca9252007-05-21 01:08:44 +00002852 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002853 bool Invalid = false;
2854 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2855 if (Invalid)
2856 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002857
Mike Stump11289f42009-09-09 15:08:12 +00002858 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002859 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002860 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002861 return ExprError();
2862
Chris Lattner1c20a172007-08-26 03:42:43 +00002863 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002864
Chris Lattner1c20a172007-08-26 03:42:43 +00002865 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002866 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002867 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002868 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002869 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002870 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002871 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002872 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002873
2874 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2875
John McCall53b93a02009-12-24 09:08:04 +00002876 using llvm::APFloat;
2877 APFloat Val(Format);
2878
2879 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002880
2881 // Overflow is always an error, but underflow is only an error if
2882 // we underflowed to zero (APFloat reports denormals as underflow).
2883 if ((result & APFloat::opOverflow) ||
2884 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002885 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002886 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002887 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002888 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002889 APFloat::getLargest(Format).toString(buffer);
2890 } else {
John McCall62abc942010-02-26 23:35:57 +00002891 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002892 APFloat::getSmallest(Format).toString(buffer);
2893 }
2894
2895 Diag(Tok.getLocation(), diagnostic)
2896 << Ty
2897 << llvm::StringRef(buffer.data(), buffer.size());
2898 }
2899
2900 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002901 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002902
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002903 if (Ty == Context.DoubleTy) {
2904 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002905 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002906 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2907 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002908 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002909 }
2910 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002911 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002912 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002913 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002914 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002915
Neil Boothac582c52007-08-29 22:00:19 +00002916 // long long is a C99 feature.
2917 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002918 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002919 Diag(Tok.getLocation(), diag::ext_longlong);
2920
Chris Lattner67ca9252007-05-21 01:08:44 +00002921 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002922 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002923
Chris Lattner67ca9252007-05-21 01:08:44 +00002924 if (Literal.GetIntegerValue(ResultVal)) {
2925 // If this value didn't fit into uintmax_t, warn and force to ull.
2926 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002927 Ty = Context.UnsignedLongLongTy;
2928 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002929 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002930 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002931 // If this value fits into a ULL, try to figure out what else it fits into
2932 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002933
Chris Lattner67ca9252007-05-21 01:08:44 +00002934 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2935 // be an unsigned int.
2936 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2937
2938 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002939 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002940 if (!Literal.isLong && !Literal.isLongLong) {
2941 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002942 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002943
Chris Lattner67ca9252007-05-21 01:08:44 +00002944 // Does it fit in a unsigned int?
2945 if (ResultVal.isIntN(IntSize)) {
2946 // Does it fit in a signed int?
2947 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002948 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002949 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002950 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002951 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002952 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002953 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002954
Chris Lattner67ca9252007-05-21 01:08:44 +00002955 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002956 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002957 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002958
Chris Lattner67ca9252007-05-21 01:08:44 +00002959 // Does it fit in a unsigned long?
2960 if (ResultVal.isIntN(LongSize)) {
2961 // Does it fit in a signed long?
2962 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002963 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002964 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002965 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002966 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002967 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002968 }
2969
Chris Lattner67ca9252007-05-21 01:08:44 +00002970 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002971 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002972 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002973
Chris Lattner67ca9252007-05-21 01:08:44 +00002974 // Does it fit in a unsigned long long?
2975 if (ResultVal.isIntN(LongLongSize)) {
2976 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002977 // To be compatible with MSVC, hex integer literals ending with the
2978 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002979 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2980 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002981 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002982 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002983 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002984 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002985 }
2986 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002987
Chris Lattner67ca9252007-05-21 01:08:44 +00002988 // If we still couldn't decide a type, we probably have something that
2989 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002990 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002991 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002992 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002993 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002994 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002995
Chris Lattner55258cf2008-05-09 05:59:00 +00002996 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002997 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002998 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002999 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003000 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003001
Chris Lattner1c20a172007-08-26 03:42:43 +00003002 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3003 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003004 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003005 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003006
3007 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003008}
3009
John McCalldadc5752010-08-24 06:29:42 +00003010ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003011 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003012 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003013 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003014}
3015
Steve Naroff71b59a92007-06-04 22:22:31 +00003016/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003017/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003018bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3019 SourceLocation OpLoc,
3020 SourceRange ExprRange,
3021 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003022 if (exprType->isDependentType())
3023 return false;
3024
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003025 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3026 // the result is the size of the referenced type."
3027 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3028 // result shall be the alignment of the referenced type."
3029 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3030 exprType = Ref->getPointeeType();
3031
Peter Collingbournee190dee2011-03-11 19:24:49 +00003032 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3033 // scalar or vector data type argument..."
3034 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3035 // type (C99 6.2.5p18) or void.
3036 if (ExprKind == UETT_VecStep) {
3037 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3038 exprType->isVectorType())) {
3039 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3040 << exprType << ExprRange;
3041 return true;
3042 }
3043 }
3044
Steve Naroff043d45d2007-05-15 02:32:35 +00003045 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00003046 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003047 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003048 if (ExprKind == UETT_SizeOf)
3049 Diag(OpLoc, diag::ext_sizeof_function_type)
3050 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003051 return false;
3052 }
Mike Stump11289f42009-09-09 15:08:12 +00003053
Peter Collingbournee190dee2011-03-11 19:24:49 +00003054 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3055 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00003056 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003057 if (ExprKind != UETT_VecStep)
3058 Diag(OpLoc, diag::ext_sizeof_void_type)
3059 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003060 return false;
3061 }
Mike Stump11289f42009-09-09 15:08:12 +00003062
Chris Lattner62975a72009-04-24 00:30:45 +00003063 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003064 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003065 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003066 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003067
Chris Lattner62975a72009-04-24 00:30:45 +00003068 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00003069 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003070 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003071 << exprType << (ExprKind == UETT_SizeOf)
3072 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003073 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00003074 }
Mike Stump11289f42009-09-09 15:08:12 +00003075
Chris Lattner62975a72009-04-24 00:30:45 +00003076 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003077}
3078
John McCall36e7fe32010-10-12 00:20:44 +00003079static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3080 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003081 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003082
Mike Stump11289f42009-09-09 15:08:12 +00003083 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003084 if (isa<DeclRefExpr>(E))
3085 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003086
3087 // Cannot know anything else if the expression is dependent.
3088 if (E->isTypeDependent())
3089 return false;
3090
Douglas Gregor71235ec2009-05-02 02:18:30 +00003091 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00003092 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00003093 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003094 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003095
3096 // Alignment of a field access is always okay, so long as it isn't a
3097 // bit-field.
3098 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003099 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003100 return false;
3101
Peter Collingbournee190dee2011-03-11 19:24:49 +00003102 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3103 UETT_AlignOf);
3104}
3105
3106bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3107 SourceRange ExprRange) {
3108 E = E->IgnoreParens();
3109
3110 // Cannot know anything else if the expression is dependent.
3111 if (E->isTypeDependent())
3112 return false;
3113
3114 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3115 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003116}
3117
Douglas Gregor0950e412009-03-13 21:01:28 +00003118/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003119ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003120Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3121 SourceLocation OpLoc,
3122 UnaryExprOrTypeTrait ExprKind,
3123 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003124 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003125 return ExprError();
3126
John McCallbcd03502009-12-07 02:54:59 +00003127 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003128
Douglas Gregor0950e412009-03-13 21:01:28 +00003129 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003130 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003131 return ExprError();
3132
3133 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003134 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3135 Context.getSizeType(),
3136 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003137}
3138
3139/// \brief Build a sizeof or alignof expression given an expression
3140/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003141ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003142Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3143 UnaryExprOrTypeTrait ExprKind,
3144 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003145 // Verify that the operand is valid.
3146 bool isInvalid = false;
3147 if (E->isTypeDependent()) {
3148 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003149 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00003150 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003151 } else if (ExprKind == UETT_VecStep) {
3152 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003153 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00003154 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3155 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003156 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003157 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003158 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00003159 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00003160 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003161 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3162 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003163 }
3164
3165 if (isInvalid)
3166 return ExprError();
3167
3168 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003169 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3170 Context.getSizeType(),
3171 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003172}
3173
Peter Collingbournee190dee2011-03-11 19:24:49 +00003174/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3175/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003176/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003177ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003178Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3179 UnaryExprOrTypeTrait ExprKind, bool isType,
3180 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003181 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003182 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003183
Sebastian Redl6f282892008-11-11 17:56:53 +00003184 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003185 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003186 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003187 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003188 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003189
Douglas Gregor0950e412009-03-13 21:01:28 +00003190 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00003191 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00003192 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3193 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00003194
Douglas Gregor0950e412009-03-13 21:01:28 +00003195 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003196}
3197
John Wiegley01296292011-04-08 18:41:53 +00003198static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003199 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003200 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003201 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003202
John McCall34376a62010-12-04 03:47:34 +00003203 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003204 if (V.get()->getObjectKind() != OK_Ordinary) {
3205 V = S.DefaultLvalueConversion(V.take());
3206 if (V.isInvalid())
3207 return QualType();
3208 }
John McCall34376a62010-12-04 03:47:34 +00003209
Chris Lattnere267f5d2007-08-26 05:39:26 +00003210 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003211 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003212 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003213
Chris Lattnere267f5d2007-08-26 05:39:26 +00003214 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003215 if (V.get()->getType()->isArithmeticType())
3216 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003217
John McCall36226622010-10-12 02:09:17 +00003218 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003219 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003220 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003221 if (PR.get() != V.get()) {
3222 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003223 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003224 }
3225
Chris Lattnere267f5d2007-08-26 05:39:26 +00003226 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003227 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003228 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003229 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003230}
3231
3232
Chris Lattnere168f762006-11-10 05:29:30 +00003233
John McCalldadc5752010-08-24 06:29:42 +00003234ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003235Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003236 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003237 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003238 switch (Kind) {
3239 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003240 case tok::plusplus: Opc = UO_PostInc; break;
3241 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003242 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003243
John McCallb268a282010-08-23 23:25:46 +00003244 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003245}
3246
John McCall4bc41ae2010-11-18 19:01:18 +00003247/// Expressions of certain arbitrary types are forbidden by C from
3248/// having l-value type. These are:
3249/// - 'void', but not qualified void
3250/// - function types
3251///
3252/// The exact rule here is C99 6.3.2.1:
3253/// An lvalue is an expression with an object type or an incomplete
3254/// type other than void.
3255static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3256 return ((T->isVoidType() && !T.hasQualifiers()) ||
3257 T->isFunctionType());
3258}
3259
John McCalldadc5752010-08-24 06:29:42 +00003260ExprResult
John McCallb268a282010-08-23 23:25:46 +00003261Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3262 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003263 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003264 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003265 if (Result.isInvalid()) return ExprError();
3266 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003267
John McCallb268a282010-08-23 23:25:46 +00003268 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003269
Douglas Gregor40412ac2008-11-19 17:17:41 +00003270 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003271 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003272 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003273 Context.DependentTy,
3274 VK_LValue, OK_Ordinary,
3275 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003276 }
3277
Mike Stump11289f42009-09-09 15:08:12 +00003278 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003279 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003280 LHSExp->getType()->isEnumeralType() ||
3281 RHSExp->getType()->isRecordType() ||
3282 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003283 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003284 }
3285
John McCallb268a282010-08-23 23:25:46 +00003286 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003287}
3288
3289
John McCalldadc5752010-08-24 06:29:42 +00003290ExprResult
John McCallb268a282010-08-23 23:25:46 +00003291Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3292 Expr *Idx, SourceLocation RLoc) {
3293 Expr *LHSExp = Base;
3294 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003295
Chris Lattner36d572b2007-07-16 00:14:47 +00003296 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003297 if (!LHSExp->getType()->getAs<VectorType>()) {
3298 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3299 if (Result.isInvalid())
3300 return ExprError();
3301 LHSExp = Result.take();
3302 }
3303 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3304 if (Result.isInvalid())
3305 return ExprError();
3306 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003307
Chris Lattner36d572b2007-07-16 00:14:47 +00003308 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003309 ExprValueKind VK = VK_LValue;
3310 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003311
Steve Naroffc1aadb12007-03-28 21:49:40 +00003312 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003313 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003314 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003315 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003316 Expr *BaseExpr, *IndexExpr;
3317 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003318 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3319 BaseExpr = LHSExp;
3320 IndexExpr = RHSExp;
3321 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003322 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003323 BaseExpr = LHSExp;
3324 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003325 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003326 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003327 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003328 BaseExpr = RHSExp;
3329 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003330 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003331 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003332 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003333 BaseExpr = LHSExp;
3334 IndexExpr = RHSExp;
3335 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003336 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003337 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003338 // Handle the uncommon case of "123[Ptr]".
3339 BaseExpr = RHSExp;
3340 IndexExpr = LHSExp;
3341 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003342 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003343 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003344 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003345 VK = LHSExp->getValueKind();
3346 if (VK != VK_RValue)
3347 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003348
Chris Lattner36d572b2007-07-16 00:14:47 +00003349 // FIXME: need to deal with const...
3350 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003351 } else if (LHSTy->isArrayType()) {
3352 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003353 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003354 // wasn't promoted because of the C90 rule that doesn't
3355 // allow promoting non-lvalue arrays. Warn, then
3356 // force the promotion here.
3357 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3358 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003359 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3360 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003361 LHSTy = LHSExp->getType();
3362
3363 BaseExpr = LHSExp;
3364 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003365 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003366 } else if (RHSTy->isArrayType()) {
3367 // Same as previous, except for 123[f().a] case
3368 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3369 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003370 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3371 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003372 RHSTy = RHSExp->getType();
3373
3374 BaseExpr = RHSExp;
3375 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003376 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003377 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003378 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3379 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003380 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003381 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003382 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003383 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3384 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003385
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003386 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003387 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3388 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003389 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3390
Douglas Gregorac1fb652009-03-24 19:52:54 +00003391 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003392 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3393 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003394 // incomplete types are not object types.
3395 if (ResultType->isFunctionType()) {
3396 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3397 << ResultType << BaseExpr->getSourceRange();
3398 return ExprError();
3399 }
Mike Stump11289f42009-09-09 15:08:12 +00003400
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003401 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3402 // GNU extension: subscripting on pointer to void
3403 Diag(LLoc, diag::ext_gnu_void_ptr)
3404 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003405
3406 // C forbids expressions of unqualified void type from being l-values.
3407 // See IsCForbiddenLValueType.
3408 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003409 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003410 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003411 PDiag(diag::err_subscript_incomplete_type)
3412 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003413 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003414
Chris Lattner62975a72009-04-24 00:30:45 +00003415 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003416 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003417 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3418 << ResultType << BaseExpr->getSourceRange();
3419 return ExprError();
3420 }
Mike Stump11289f42009-09-09 15:08:12 +00003421
John McCall4bc41ae2010-11-18 19:01:18 +00003422 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3423 !IsCForbiddenLValueType(Context, ResultType));
3424
Mike Stump4e1f26a2009-02-19 03:04:26 +00003425 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003426 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003427}
3428
John McCall4bc41ae2010-11-18 19:01:18 +00003429/// Check an ext-vector component access expression.
3430///
3431/// VK should be set in advance to the value kind of the base
3432/// expression.
3433static QualType
3434CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3435 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003436 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003437 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3438 // see FIXME there.
3439 //
3440 // FIXME: This logic can be greatly simplified by splitting it along
3441 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003442 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003443
Steve Narofff8fd09e2007-07-27 22:15:19 +00003444 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003445 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003446
Mike Stump4e1f26a2009-02-19 03:04:26 +00003447 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003448 // special names that indicate a subset of exactly half the elements are
3449 // to be selected.
3450 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003451
Nate Begemanbb70bf62009-01-18 01:47:54 +00003452 // This flag determines whether or not CompName has an 's' char prefix,
3453 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003454 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003455
John McCall4bc41ae2010-11-18 19:01:18 +00003456 bool HasRepeated = false;
3457 bool HasIndex[16] = {};
3458
3459 int Idx;
3460
Nate Begemanf322eab2008-05-09 06:41:27 +00003461 // Check that we've found one of the special components, or that the component
3462 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003463 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003464 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3465 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003466 } else if (!HexSwizzle &&
3467 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3468 do {
3469 if (HasIndex[Idx]) HasRepeated = true;
3470 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003471 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003472 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3473 } else {
3474 if (HexSwizzle) compStr++;
3475 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3476 if (HasIndex[Idx]) HasRepeated = true;
3477 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003478 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003479 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003480 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003481
Mike Stump4e1f26a2009-02-19 03:04:26 +00003482 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003483 // We didn't get to the end of the string. This means the component names
3484 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003485 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003486 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003487 return QualType();
3488 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003489
Nate Begemanbb70bf62009-01-18 01:47:54 +00003490 // Ensure no component accessor exceeds the width of the vector type it
3491 // operates on.
3492 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003493 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003494
3495 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003496 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003497
3498 while (*compStr) {
3499 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003500 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003501 << baseType << SourceRange(CompLoc);
3502 return QualType();
3503 }
3504 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003505 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003506
Steve Narofff8fd09e2007-07-27 22:15:19 +00003507 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003508 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003509 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003510 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003511 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003512 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003513 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003514 if (HexSwizzle)
3515 CompSize--;
3516
Steve Narofff8fd09e2007-07-27 22:15:19 +00003517 if (CompSize == 1)
3518 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003519
John McCall4bc41ae2010-11-18 19:01:18 +00003520 if (HasRepeated) VK = VK_RValue;
3521
3522 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003523 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003524 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003525 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3526 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3527 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003528 }
3529 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003530}
3531
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003532static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003533 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003534 const Selector &Sel,
3535 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003536 if (Member)
3537 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3538 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003539 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003540 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003542 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3543 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003544 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3545 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003546 return D;
3547 }
3548 return 0;
3549}
3550
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003551static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3552 IdentifierInfo *Member,
3553 const Selector &Sel,
3554 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003555 // Check protocols on qualified interfaces.
3556 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003557 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003558 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003559 if (Member)
3560 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3561 GDecl = PD;
3562 break;
3563 }
3564 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003565 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003566 GDecl = OMD;
3567 break;
3568 }
3569 }
3570 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003571 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003572 E = QIdTy->qual_end(); I != E; ++I) {
3573 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003574 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3575 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003576 if (GDecl)
3577 return GDecl;
3578 }
3579 }
3580 return GDecl;
3581}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003582
John McCalldadc5752010-08-24 06:29:42 +00003583ExprResult
John McCallb268a282010-08-23 23:25:46 +00003584Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003585 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003586 const CXXScopeSpec &SS,
3587 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003588 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003589 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003590 // Even in dependent contexts, try to diagnose base expressions with
3591 // obviously wrong types, e.g.:
3592 //
3593 // T* t;
3594 // t.f;
3595 //
3596 // In Obj-C++, however, the above expression is valid, since it could be
3597 // accessing the 'f' property if T is an Obj-C interface. The extra check
3598 // allows this, while still reporting an error if T is a struct pointer.
3599 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003600 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003601 if (PT && (!getLangOptions().ObjC1 ||
3602 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003603 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003604 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003605 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003606 return ExprError();
3607 }
3608 }
3609
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003610 assert(BaseType->isDependentType() ||
3611 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003612 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003613
3614 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3615 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003616 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003617 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003618 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003619 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003620 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003621}
3622
3623/// We know that the given qualified member reference points only to
3624/// declarations which do not belong to the static type of the base
3625/// expression. Diagnose the problem.
3626static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3627 Expr *BaseExpr,
3628 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003629 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003630 NamedDecl *rep,
3631 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003632 // If this is an implicit member access, use a different set of
3633 // diagnostics.
3634 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003635 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003636
John McCallf3a88602011-02-03 08:15:49 +00003637 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3638 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003639}
3640
3641// Check whether the declarations we found through a nested-name
3642// specifier in a member expression are actually members of the base
3643// type. The restriction here is:
3644//
3645// C++ [expr.ref]p2:
3646// ... In these cases, the id-expression shall name a
3647// member of the class or of one of its base classes.
3648//
3649// So it's perfectly legitimate for the nested-name specifier to name
3650// an unrelated class, and for us to find an overload set including
3651// decls from classes which are not superclasses, as long as the decl
3652// we actually pick through overload resolution is from a superclass.
3653bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3654 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003655 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003656 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003657 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3658 if (!BaseRT) {
3659 // We can't check this yet because the base type is still
3660 // dependent.
3661 assert(BaseType->isDependentType());
3662 return false;
3663 }
3664 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003665
3666 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003667 // If this is an implicit member reference and we find a
3668 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003669 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003670 return false;
John McCall10eae182009-11-30 22:42:35 +00003671
John McCall2d74de92009-12-01 22:10:20 +00003672 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003673 DeclContext *DC = (*I)->getDeclContext();
3674 while (DC->isTransparentContext())
3675 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003676
Douglas Gregora9c3e822010-07-28 22:27:52 +00003677 if (!DC->isRecord())
3678 continue;
3679
John McCall2d74de92009-12-01 22:10:20 +00003680 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003681 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003682
3683 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3684 return false;
3685 }
3686
John McCallf3a88602011-02-03 08:15:49 +00003687 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3688 R.getRepresentativeDecl(),
3689 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003690 return true;
3691}
3692
3693static bool
3694LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3695 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003696 SourceLocation OpLoc, CXXScopeSpec &SS,
3697 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003698 RecordDecl *RDecl = RTy->getDecl();
3699 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003700 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003701 << BaseRange))
3702 return true;
3703
John McCalle9cccd82010-06-16 08:42:20 +00003704 if (HasTemplateArgs) {
3705 // LookupTemplateName doesn't expect these both to exist simultaneously.
3706 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3707
3708 bool MOUS;
3709 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3710 return false;
3711 }
3712
John McCall2d74de92009-12-01 22:10:20 +00003713 DeclContext *DC = RDecl;
3714 if (SS.isSet()) {
3715 // If the member name was a qualified-id, look into the
3716 // nested-name-specifier.
3717 DC = SemaRef.computeDeclContext(SS, false);
3718
John McCall0b66eb32010-05-01 00:40:08 +00003719 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003720 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3721 << SS.getRange() << DC;
3722 return true;
3723 }
3724
John McCall2d74de92009-12-01 22:10:20 +00003725 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003726
John McCall2d74de92009-12-01 22:10:20 +00003727 if (!isa<TypeDecl>(DC)) {
3728 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3729 << DC << SS.getRange();
3730 return true;
John McCall10eae182009-11-30 22:42:35 +00003731 }
3732 }
3733
John McCall2d74de92009-12-01 22:10:20 +00003734 // The record definition is complete, now look up the member.
3735 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003736
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003737 if (!R.empty())
3738 return false;
3739
3740 // We didn't find anything with the given name, so try to correct
3741 // for typos.
3742 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003743 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003744 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003745 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3746 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3747 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003748 << FixItHint::CreateReplacement(R.getNameLoc(),
3749 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003750 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3751 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3752 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003753 return false;
3754 } else {
3755 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003756 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003757 }
3758
John McCall10eae182009-11-30 22:42:35 +00003759 return false;
3760}
3761
John McCalldadc5752010-08-24 06:29:42 +00003762ExprResult
John McCallb268a282010-08-23 23:25:46 +00003763Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003764 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003765 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003766 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003767 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003768 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003769 if (BaseType->isDependentType() ||
3770 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003771 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003772 IsArrow, OpLoc,
3773 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003774 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003775
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003776 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003777
John McCall2d74de92009-12-01 22:10:20 +00003778 // Implicit member accesses.
3779 if (!Base) {
3780 QualType RecordTy = BaseType;
3781 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3782 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3783 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003784 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003785 return ExprError();
3786
3787 // Explicit member accesses.
3788 } else {
John Wiegley01296292011-04-08 18:41:53 +00003789 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003790 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003791 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003792 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003793
John Wiegley01296292011-04-08 18:41:53 +00003794 if (BaseResult.isInvalid())
3795 return ExprError();
3796 Base = BaseResult.take();
3797
John McCall2d74de92009-12-01 22:10:20 +00003798 if (Result.isInvalid()) {
3799 Owned(Base);
3800 return ExprError();
3801 }
3802
3803 if (Result.get())
3804 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003805
3806 // LookupMemberExpr can modify Base, and thus change BaseType
3807 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003808 }
3809
John McCallb268a282010-08-23 23:25:46 +00003810 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003811 OpLoc, IsArrow, SS, FirstQualifierInScope,
3812 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003813}
3814
John McCalldadc5752010-08-24 06:29:42 +00003815ExprResult
John McCallb268a282010-08-23 23:25:46 +00003816Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003817 SourceLocation OpLoc, bool IsArrow,
3818 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003819 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003820 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003821 const TemplateArgumentListInfo *TemplateArgs,
3822 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003823 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003824 if (IsArrow) {
3825 assert(BaseType->isPointerType());
3826 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3827 }
John McCalla8ae2222010-04-06 21:38:20 +00003828 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003829
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003830 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3831 DeclarationName MemberName = MemberNameInfo.getName();
3832 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003833
3834 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003835 return ExprError();
3836
John McCall10eae182009-11-30 22:42:35 +00003837 if (R.empty()) {
3838 // Rederive where we looked up.
3839 DeclContext *DC = (SS.isSet()
3840 ? computeDeclContext(SS, false)
3841 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003842
John McCall10eae182009-11-30 22:42:35 +00003843 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003844 << MemberName << DC
3845 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003846 return ExprError();
3847 }
3848
John McCall38836f02010-01-15 08:34:02 +00003849 // Diagnose lookups that find only declarations from a non-base
3850 // type. This is possible for either qualified lookups (which may
3851 // have been qualified with an unrelated type) or implicit member
3852 // expressions (which were found with unqualified lookup and thus
3853 // may have come from an enclosing scope). Note that it's okay for
3854 // lookup to find declarations from a non-base type as long as those
3855 // aren't the ones picked by overload resolution.
3856 if ((SS.isSet() || !BaseExpr ||
3857 (isa<CXXThisExpr>(BaseExpr) &&
3858 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003859 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003860 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003861 return ExprError();
3862
3863 // Construct an unresolved result if we in fact got an unresolved
3864 // result.
3865 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003866 // Suppress any lookup-related diagnostics; we'll do these when we
3867 // pick a member.
3868 R.suppressDiagnostics();
3869
John McCall10eae182009-11-30 22:42:35 +00003870 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003871 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003872 BaseExpr, BaseExprType,
3873 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003874 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003875 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003876 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003877
3878 return Owned(MemExpr);
3879 }
3880
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003881 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003882 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003883 NamedDecl *MemberDecl = R.getFoundDecl();
3884
3885 // FIXME: diagnose the presence of template arguments now.
3886
3887 // If the decl being referenced had an error, return an error for this
3888 // sub-expr without emitting another error, in order to avoid cascading
3889 // error cases.
3890 if (MemberDecl->isInvalidDecl())
3891 return ExprError();
3892
John McCall2d74de92009-12-01 22:10:20 +00003893 // Handle the implicit-member-access case.
3894 if (!BaseExpr) {
3895 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003896 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003897 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003898
Douglas Gregorb15af892010-01-07 23:12:05 +00003899 SourceLocation Loc = R.getNameLoc();
3900 if (SS.getRange().isValid())
3901 Loc = SS.getRange().getBegin();
3902 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003903 }
3904
John McCall10eae182009-11-30 22:42:35 +00003905 bool ShouldCheckUse = true;
3906 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3907 // Don't diagnose the use of a virtual member function unless it's
3908 // explicitly qualified.
3909 if (MD->isVirtual() && !SS.isSet())
3910 ShouldCheckUse = false;
3911 }
3912
3913 // Check the use of this member.
3914 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3915 Owned(BaseExpr);
3916 return ExprError();
3917 }
3918
John McCall34376a62010-12-04 03:47:34 +00003919 // Perform a property load on the base regardless of whether we
3920 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003921 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3922 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3923 if (Result.isInvalid())
3924 return ExprError();
3925 BaseExpr = Result.take();
3926 }
John McCall34376a62010-12-04 03:47:34 +00003927
John McCallfeb624a2010-11-23 20:48:44 +00003928 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3929 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3930 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003931
Francois Pichet783dd6e2010-11-21 06:08:52 +00003932 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3933 // We may have found a field within an anonymous union or struct
3934 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003935 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003936 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003937
John McCall10eae182009-11-30 22:42:35 +00003938 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3939 MarkDeclarationReferenced(MemberLoc, Var);
3940 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003941 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003942 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003943 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003944 }
3945
John McCall7decc9e2010-11-18 06:31:45 +00003946 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00003947 ExprValueKind valueKind;
3948 QualType type;
3949 if (MemberFn->isInstance()) {
3950 valueKind = VK_RValue;
3951 type = Context.BoundMemberTy;
3952 } else {
3953 valueKind = VK_LValue;
3954 type = MemberFn->getType();
3955 }
3956
John McCall10eae182009-11-30 22:42:35 +00003957 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3958 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003959 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00003960 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003961 }
John McCall7decc9e2010-11-18 06:31:45 +00003962 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003963
3964 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3965 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3966 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003967 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003968 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003969 }
3970
3971 Owned(BaseExpr);
3972
Douglas Gregor861eb802010-04-25 20:55:08 +00003973 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003974 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003975 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003976 << MemberName << BaseType << int(IsArrow);
3977 else
3978 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3979 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003980
Douglas Gregor861eb802010-04-25 20:55:08 +00003981 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3982 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003983 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003984 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003985}
3986
John McCall68fc88ec2010-12-15 16:46:44 +00003987/// Given that normal member access failed on the given expression,
3988/// and given that the expression's type involves builtin-id or
3989/// builtin-Class, decide whether substituting in the redefinition
3990/// types would be profitable. The redefinition type is whatever
3991/// this translation unit tried to typedef to id/Class; we store
3992/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00003993static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00003994 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00003995 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00003996 if (!opty) return false;
3997
3998 const ObjCObjectType *ty = opty->getObjectType();
3999
4000 QualType redef;
4001 if (ty->isObjCId()) {
4002 redef = S.Context.ObjCIdRedefinitionType;
4003 } else if (ty->isObjCClass()) {
4004 redef = S.Context.ObjCClassRedefinitionType;
4005 } else {
4006 return false;
4007 }
4008
4009 // Do the substitution as long as the redefinition type isn't just a
4010 // possibly-qualified pointer to builtin-id or builtin-Class again.
4011 opty = redef->getAs<ObjCObjectPointerType>();
4012 if (opty && !opty->getObjectType()->getInterface() != 0)
4013 return false;
4014
John Wiegley01296292011-04-08 18:41:53 +00004015 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004016 return true;
4017}
4018
John McCall10eae182009-11-30 22:42:35 +00004019/// Look up the given member of the given non-type-dependent
4020/// expression. This can return in one of two ways:
4021/// * If it returns a sentinel null-but-valid result, the caller will
4022/// assume that lookup was performed and the results written into
4023/// the provided structure. It will take over from there.
4024/// * Otherwise, the returned expression will be produced in place of
4025/// an ordinary member expression.
4026///
4027/// The ObjCImpDecl bit is a gross hack that will need to be properly
4028/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004029ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004030Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004031 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004032 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004033 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004034 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004035
Steve Naroffeaaae462007-12-16 21:42:28 +00004036 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004037 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004038
John Wiegley01296292011-04-08 18:41:53 +00004039 if (IsArrow) {
4040 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4041 if (BaseExpr.isInvalid())
4042 return ExprError();
4043 }
4044
4045 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004046 assert(!BaseType->isDependentType());
4047
4048 DeclarationName MemberName = R.getLookupName();
4049 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004050
John McCall68fc88ec2010-12-15 16:46:44 +00004051 // For later type-checking purposes, turn arrow accesses into dot
4052 // accesses. The only access type we support that doesn't follow
4053 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4054 // and those never use arrows, so this is unaffected.
4055 if (IsArrow) {
4056 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4057 BaseType = Ptr->getPointeeType();
4058 else if (const ObjCObjectPointerType *Ptr
4059 = BaseType->getAs<ObjCObjectPointerType>())
4060 BaseType = Ptr->getPointeeType();
4061 else if (BaseType->isRecordType()) {
4062 // Recover from arrow accesses to records, e.g.:
4063 // struct MyRecord foo;
4064 // foo->bar
4065 // This is actually well-formed in C++ if MyRecord has an
4066 // overloaded operator->, but that should have been dealt with
4067 // by now.
4068 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004069 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004070 << FixItHint::CreateReplacement(OpLoc, ".");
4071 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004072 } else if (BaseType == Context.BoundMemberTy) {
4073 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004074 } else {
4075 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004076 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004077 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004078 }
4079 }
4080
John McCall68fc88ec2010-12-15 16:46:44 +00004081 // Handle field access to simple records.
4082 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004083 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004084 RTy, OpLoc, SS, HasTemplateArgs))
4085 return ExprError();
4086
4087 // Returning valid-but-null is how we indicate to the caller that
4088 // the lookup result was filled in.
4089 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004090 }
John McCall10eae182009-11-30 22:42:35 +00004091
John McCall68fc88ec2010-12-15 16:46:44 +00004092 // Handle ivar access to Objective-C objects.
4093 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004094 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004095
4096 // There are three cases for the base type:
4097 // - builtin id (qualified or unqualified)
4098 // - builtin Class (qualified or unqualified)
4099 // - an interface
4100 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4101 if (!IDecl) {
4102 // There's an implicit 'isa' ivar on all objects.
4103 // But we only actually find it this way on objects of type 'id',
4104 // apparently.
4105 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004106 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004107 Context.getObjCClassType()));
4108
4109 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4110 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4111 ObjCImpDecl, HasTemplateArgs);
4112 goto fail;
4113 }
4114
4115 ObjCInterfaceDecl *ClassDeclared;
4116 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4117
4118 if (!IV) {
4119 // Attempt to correct for typos in ivar names.
4120 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4121 LookupMemberName);
4122 if (CorrectTypo(Res, 0, 0, IDecl, false,
4123 IsArrow ? CTC_ObjCIvarLookup
4124 : CTC_ObjCPropertyLookup) &&
4125 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4126 Diag(R.getNameLoc(),
4127 diag::err_typecheck_member_reference_ivar_suggest)
4128 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4129 << FixItHint::CreateReplacement(R.getNameLoc(),
4130 IV->getNameAsString());
4131 Diag(IV->getLocation(), diag::note_previous_decl)
4132 << IV->getDeclName();
4133 } else {
4134 Res.clear();
4135 Res.setLookupName(Member);
4136
4137 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4138 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004139 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004140 return ExprError();
4141 }
4142 }
4143
4144 // If the decl being referenced had an error, return an error for this
4145 // sub-expr without emitting another error, in order to avoid cascading
4146 // error cases.
4147 if (IV->isInvalidDecl())
4148 return ExprError();
4149
4150 // Check whether we can reference this field.
4151 if (DiagnoseUseOfDecl(IV, MemberLoc))
4152 return ExprError();
4153 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4154 IV->getAccessControl() != ObjCIvarDecl::Package) {
4155 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4156 if (ObjCMethodDecl *MD = getCurMethodDecl())
4157 ClassOfMethodDecl = MD->getClassInterface();
4158 else if (ObjCImpDecl && getCurFunctionDecl()) {
4159 // Case of a c-function declared inside an objc implementation.
4160 // FIXME: For a c-style function nested inside an objc implementation
4161 // class, there is no implementation context available, so we pass
4162 // down the context as argument to this routine. Ideally, this context
4163 // need be passed down in the AST node and somehow calculated from the
4164 // AST for a function decl.
4165 if (ObjCImplementationDecl *IMPD =
4166 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4167 ClassOfMethodDecl = IMPD->getClassInterface();
4168 else if (ObjCCategoryImplDecl* CatImplClass =
4169 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4170 ClassOfMethodDecl = CatImplClass->getClassInterface();
4171 }
4172
4173 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4174 if (ClassDeclared != IDecl ||
4175 ClassOfMethodDecl != ClassDeclared)
4176 Diag(MemberLoc, diag::error_private_ivar_access)
4177 << IV->getDeclName();
4178 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4179 // @protected
4180 Diag(MemberLoc, diag::error_protected_ivar_access)
4181 << IV->getDeclName();
4182 }
4183
4184 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004185 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004186 IsArrow));
4187 }
4188
4189 // Objective-C property access.
4190 const ObjCObjectPointerType *OPT;
4191 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4192 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004193 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4194 if (BaseExpr.isInvalid())
4195 return ExprError();
4196
4197 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004198
4199 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4200
4201 const ObjCObjectType *OT = OPT->getObjectType();
4202
4203 // id, with and without qualifiers.
4204 if (OT->isObjCId()) {
4205 // Check protocols on qualified interfaces.
4206 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4207 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4208 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4209 // Check the use of this declaration
4210 if (DiagnoseUseOfDecl(PD, MemberLoc))
4211 return ExprError();
4212
4213 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4214 VK_LValue,
4215 OK_ObjCProperty,
4216 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004217 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004218 }
4219
4220 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4221 // Check the use of this method.
4222 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4223 return ExprError();
4224 Selector SetterSel =
4225 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4226 PP.getSelectorTable(), Member);
4227 ObjCMethodDecl *SMD = 0;
4228 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4229 SetterSel, Context))
4230 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4231 QualType PType = OMD->getSendResultType();
4232
4233 ExprValueKind VK = VK_LValue;
4234 if (!getLangOptions().CPlusPlus &&
4235 IsCForbiddenLValueType(Context, PType))
4236 VK = VK_RValue;
4237 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4238
4239 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4240 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004241 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004242 }
4243 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004244 // Use of id.member can only be for a property reference. Do not
4245 // use the 'id' redefinition in this case.
4246 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004247 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4248 ObjCImpDecl, HasTemplateArgs);
4249
4250 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4251 << MemberName << BaseType);
4252 }
4253
4254 // 'Class', unqualified only.
4255 if (OT->isObjCClass()) {
4256 // Only works in a method declaration (??!).
4257 ObjCMethodDecl *MD = getCurMethodDecl();
4258 if (!MD) {
4259 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4260 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4261 ObjCImpDecl, HasTemplateArgs);
4262
4263 goto fail;
4264 }
4265
4266 // Also must look for a getter name which uses property syntax.
4267 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004268 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4269 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004270 if ((Getter = IFace->lookupClassMethod(Sel))) {
4271 // Check the use of this method.
4272 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4273 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004274 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004275 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004276 // If we found a getter then this may be a valid dot-reference, we
4277 // will look for the matching setter, in case it is needed.
4278 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004279 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4280 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004281 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4282 if (!Setter) {
4283 // If this reference is in an @implementation, also check for 'private'
4284 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004285 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004286 }
4287 // Look through local category implementations associated with the class.
4288 if (!Setter)
4289 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004290
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004291 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4292 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004293
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004294 if (Getter || Setter) {
4295 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004296
John McCall4bc41ae2010-11-18 19:01:18 +00004297 ExprValueKind VK = VK_LValue;
4298 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004299 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004300 if (!getLangOptions().CPlusPlus &&
4301 IsCForbiddenLValueType(Context, PType))
4302 VK = VK_RValue;
4303 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004304 // Get the expression type from Setter's incoming parameter.
4305 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004306 }
4307 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4308
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004309 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004310 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4311 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004312 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004313 }
John McCall68fc88ec2010-12-15 16:46:44 +00004314
4315 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4316 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4317 ObjCImpDecl, HasTemplateArgs);
4318
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004319 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004320 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004321 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004322
John McCall68fc88ec2010-12-15 16:46:44 +00004323 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004324 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004325 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004326 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004327
Chris Lattnerb63a7452008-07-21 04:28:12 +00004328 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004329 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004330 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004331 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004332 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004333 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4334 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004335 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004336 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004337
John Wiegley01296292011-04-08 18:41:53 +00004338 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004339 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004340 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004341
John McCall68fc88ec2010-12-15 16:46:44 +00004342 // Adjust builtin-sel to the appropriate redefinition type if that's
4343 // not just a pointer to builtin-sel again.
4344 if (IsArrow &&
4345 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4346 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004347 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4348 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004349 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4350 ObjCImpDecl, HasTemplateArgs);
4351 }
4352
4353 // Failure cases.
4354 fail:
4355
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004356 // Recover from dot accesses to pointers, e.g.:
4357 // type *foo;
4358 // foo.bar
4359 // This is actually well-formed in two cases:
4360 // - 'type' is an Objective C type
4361 // - 'bar' is a pseudo-destructor name which happens to refer to
4362 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004363 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004364 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4365 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004366 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004367 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004368 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004369
4370 // Recurse as an -> access.
4371 IsArrow = true;
4372 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4373 ObjCImpDecl, HasTemplateArgs);
4374 }
John McCall68fc88ec2010-12-15 16:46:44 +00004375 }
4376
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004377 // If the user is trying to apply -> or . to a function name, it's probably
4378 // because they forgot parentheses to call that function.
4379 bool TryCall = false;
4380 bool Overloaded = false;
4381 UnresolvedSet<8> AllOverloads;
John Wiegley01296292011-04-08 18:41:53 +00004382 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004383 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4384 TryCall = true;
4385 Overloaded = true;
John Wiegley01296292011-04-08 18:41:53 +00004386 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004387 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4388 AllOverloads.addDecl(Fun);
4389 TryCall = true;
4390 }
4391 }
John McCall68fc88ec2010-12-15 16:46:44 +00004392
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004393 if (TryCall) {
4394 // Plunder the overload set for something that would make the member
4395 // expression valid.
4396 UnresolvedSet<4> ViableOverloads;
4397 bool HasViableZeroArgOverload = false;
4398 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4399 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004400 // Our overload set may include TemplateDecls, which we'll ignore for the
4401 // purposes of determining whether we can issue a '()' fixit.
4402 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4403 QualType ResultTy = OverloadDecl->getResultType();
4404 if ((!IsArrow && ResultTy->isRecordType()) ||
4405 (IsArrow && ResultTy->isPointerType() &&
4406 ResultTy->getPointeeType()->isRecordType())) {
4407 ViableOverloads.addDecl(*it);
4408 if (OverloadDecl->getMinRequiredArguments() == 0) {
4409 HasViableZeroArgOverload = true;
4410 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004411 }
John McCall68fc88ec2010-12-15 16:46:44 +00004412 }
4413 }
4414
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004415 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley01296292011-04-08 18:41:53 +00004416 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004417 << (AllOverloads.size() > 1) << 0
John Wiegley01296292011-04-08 18:41:53 +00004418 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004419 int ViableOverloadCount = ViableOverloads.size();
4420 int I;
4421 for (I = 0; I < ViableOverloadCount; ++I) {
4422 // FIXME: Magic number for max shown overloads stolen from
4423 // OverloadCandidateSet::NoteCandidates.
4424 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4425 break;
4426 }
4427 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4428 diag::note_member_ref_possible_intended_overload);
4429 }
4430 if (I != ViableOverloadCount) {
John Wiegley01296292011-04-08 18:41:53 +00004431 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004432 << int(ViableOverloadCount - I);
4433 }
4434 return ExprError();
4435 }
4436 } else {
4437 // We don't have an expression that's convenient to get a Decl from, but we
4438 // can at least check if the type is "function of 0 arguments which returns
4439 // an acceptable type".
4440 const FunctionType *Fun = NULL;
4441 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4442 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4443 TryCall = true;
4444 }
4445 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4446 TryCall = true;
John McCall0009fcc2011-04-26 20:42:42 +00004447 } else if (BaseType == Context.BoundMemberTy) {
4448 // Look for the bound-member type. If it's still overloaded,
4449 // give up, although we probably should have fallen into the
4450 // OverloadExpr case above if we actually have an overloaded
4451 // bound member.
4452 QualType fnType = Expr::findBoundMemberType(BaseExpr.get());
4453 if (!fnType.isNull()) {
4454 TryCall = true;
4455 Fun = fnType->castAs<FunctionType>();
4456 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004457 }
John McCall68fc88ec2010-12-15 16:46:44 +00004458
4459 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004460 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4461 if (FPT->getNumArgs() == 0) {
4462 QualType ResultTy = Fun->getResultType();
4463 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4464 (IsArrow && ResultTy->isPointerType() &&
4465 ResultTy->getPointeeType()->isRecordType());
4466 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004467 }
John McCall68fc88ec2010-12-15 16:46:44 +00004468 }
4469 }
4470
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004471 if (TryCall) {
4472 // At this point, we know BaseExpr looks like it's potentially callable with
4473 // 0 arguments, and that it returns something of a reasonable type, so we
4474 // can emit a fixit and carry on pretending that BaseExpr was actually a
4475 // CallExpr.
4476 SourceLocation ParenInsertionLoc =
John Wiegley01296292011-04-08 18:41:53 +00004477 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4478 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004479 << int(Overloaded) << 1
John Wiegley01296292011-04-08 18:41:53 +00004480 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004481 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley01296292011-04-08 18:41:53 +00004482 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004483 MultiExprArg(*this, 0, 0),
4484 ParenInsertionLoc);
4485 if (NewBase.isInvalid())
4486 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004487 BaseExpr = NewBase;
4488 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004489 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4490 ObjCImpDecl, HasTemplateArgs);
4491 }
4492
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004493 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004494 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004495
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004496 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004497}
4498
John McCall10eae182009-11-30 22:42:35 +00004499/// The main callback when the parser finds something like
4500/// expression . [nested-name-specifier] identifier
4501/// expression -> [nested-name-specifier] identifier
4502/// where 'identifier' encompasses a fairly broad spectrum of
4503/// possibilities, including destructor and operator references.
4504///
4505/// \param OpKind either tok::arrow or tok::period
4506/// \param HasTrailingLParen whether the next token is '(', which
4507/// is used to diagnose mis-uses of special members that can
4508/// only be called
4509/// \param ObjCImpDecl the current ObjC @implementation decl;
4510/// this is an ugly hack around the fact that ObjC @implementations
4511/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004512ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004513 SourceLocation OpLoc,
4514 tok::TokenKind OpKind,
4515 CXXScopeSpec &SS,
4516 UnqualifiedId &Id,
4517 Decl *ObjCImpDecl,
4518 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004519 if (SS.isSet() && SS.isInvalid())
4520 return ExprError();
4521
Francois Pichet64225792011-01-18 05:04:39 +00004522 // Warn about the explicit constructor calls Microsoft extension.
4523 if (getLangOptions().Microsoft &&
4524 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4525 Diag(Id.getSourceRange().getBegin(),
4526 diag::ext_ms_explicit_constructor_call);
4527
John McCall10eae182009-11-30 22:42:35 +00004528 TemplateArgumentListInfo TemplateArgsBuffer;
4529
4530 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004531 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004532 const TemplateArgumentListInfo *TemplateArgs;
4533 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004534 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004535
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004536 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004537 bool IsArrow = (OpKind == tok::arrow);
4538
4539 NamedDecl *FirstQualifierInScope
4540 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4541 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4542
4543 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004544 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004545 if (Result.isInvalid()) return ExprError();
4546 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004547
Douglas Gregor41f90302010-04-12 20:54:26 +00004548 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4549 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004550 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004551 IsArrow, OpLoc,
4552 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004553 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004554 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004555 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004556 ExprResult BaseResult = Owned(Base);
4557 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004558 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004559 if (BaseResult.isInvalid())
4560 return ExprError();
4561 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004562
John McCalle9cccd82010-06-16 08:42:20 +00004563 if (Result.isInvalid()) {
4564 Owned(Base);
4565 return ExprError();
4566 }
John McCall10eae182009-11-30 22:42:35 +00004567
John McCalle9cccd82010-06-16 08:42:20 +00004568 if (Result.get()) {
4569 // The only way a reference to a destructor can be used is to
4570 // immediately call it, which falls into this case. If the
4571 // next token is not a '(', produce a diagnostic and build the
4572 // call now.
4573 if (!HasTrailingLParen &&
4574 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004575 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004576
John McCalle9cccd82010-06-16 08:42:20 +00004577 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004578 }
4579
John McCallb268a282010-08-23 23:25:46 +00004580 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004581 OpLoc, IsArrow, SS, FirstQualifierInScope,
4582 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004583 }
4584
4585 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004586}
4587
John McCalldadc5752010-08-24 06:29:42 +00004588ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004589 FunctionDecl *FD,
4590 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004591 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004592 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004593 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004594 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004595 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004596 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004597 return ExprError();
4598 }
4599
4600 if (Param->hasUninstantiatedDefaultArg()) {
4601 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004602
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004603 // Instantiate the expression.
4604 MultiLevelTemplateArgumentList ArgList
4605 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004606
Nico Weber44887f62010-11-29 18:19:25 +00004607 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004608 = ArgList.getInnermost();
4609 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4610 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004611
Nico Weber44887f62010-11-29 18:19:25 +00004612 ExprResult Result;
4613 {
4614 // C++ [dcl.fct.default]p5:
4615 // The names in the [default argument] expression are bound, and
4616 // the semantic constraints are checked, at the point where the
4617 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004618 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004619 Result = SubstExpr(UninstExpr, ArgList);
4620 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004621 if (Result.isInvalid())
4622 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004623
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004624 // Check the expression as an initializer for the parameter.
4625 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004626 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004627 InitializationKind Kind
4628 = InitializationKind::CreateCopy(Param->getLocation(),
4629 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4630 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004631
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004632 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4633 Result = InitSeq.Perform(*this, Entity, Kind,
4634 MultiExprArg(*this, &ResultE, 1));
4635 if (Result.isInvalid())
4636 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004637
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004638 // Build the default argument expression.
4639 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4640 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004641 }
4642
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004643 // If the default expression creates temporaries, we need to
4644 // push them to the current stack of expression temporaries so they'll
4645 // be properly destroyed.
4646 // FIXME: We should really be rebuilding the default argument with new
4647 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004648 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4649 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4650 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4651 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4652 ExprTemporaries.push_back(Temporary);
4653 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004654
4655 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004656 // Just mark all of the declarations in this potentially-evaluated expression
4657 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004658 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004659 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004660}
4661
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004662/// ConvertArgumentsForCall - Converts the arguments specified in
4663/// Args/NumArgs to the parameter types of the function FDecl with
4664/// function prototype Proto. Call is the call expression itself, and
4665/// Fn is the function expression. For a C++ member function, this
4666/// routine does not attempt to convert the object argument. Returns
4667/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004668bool
4669Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004670 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004671 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004672 Expr **Args, unsigned NumArgs,
4673 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004674 // Bail out early if calling a builtin with custom typechecking.
4675 // We don't need to do this in the
4676 if (FDecl)
4677 if (unsigned ID = FDecl->getBuiltinID())
4678 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4679 return false;
4680
Mike Stump4e1f26a2009-02-19 03:04:26 +00004681 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004682 // assignment, to the types of the corresponding parameter, ...
4683 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004684 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004685
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004686 // If too few arguments are available (and we don't have default
4687 // arguments for the remaining parameters), don't make the call.
4688 if (NumArgs < NumArgsInProto) {
4689 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4690 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004691 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004692 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004693 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004694 }
4695
4696 // If too many are passed and not variadic, error on the extras and drop
4697 // them.
4698 if (NumArgs > NumArgsInProto) {
4699 if (!Proto->isVariadic()) {
4700 Diag(Args[NumArgsInProto]->getLocStart(),
4701 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004702 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004703 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004704 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4705 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004706
4707 // Emit the location of the prototype.
4708 if (FDecl && !FDecl->getBuiltinID())
4709 Diag(FDecl->getLocStart(),
4710 diag::note_typecheck_call_too_many_args)
4711 << FDecl;
4712
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004713 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004714 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004715 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004716 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004717 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004718 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004719 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004720 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4721 if (Fn->getType()->isBlockPointerType())
4722 CallType = VariadicBlock; // Block
4723 else if (isa<MemberExpr>(Fn))
4724 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004725 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004726 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004727 if (Invalid)
4728 return true;
4729 unsigned TotalNumArgs = AllArgs.size();
4730 for (unsigned i = 0; i < TotalNumArgs; ++i)
4731 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004732
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004733 return false;
4734}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004735
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004736bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4737 FunctionDecl *FDecl,
4738 const FunctionProtoType *Proto,
4739 unsigned FirstProtoArg,
4740 Expr **Args, unsigned NumArgs,
4741 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004742 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004743 unsigned NumArgsInProto = Proto->getNumArgs();
4744 unsigned NumArgsToCheck = NumArgs;
4745 bool Invalid = false;
4746 if (NumArgs != NumArgsInProto)
4747 // Use default arguments for missing arguments
4748 NumArgsToCheck = NumArgsInProto;
4749 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004750 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004751 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004752 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004753
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004754 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004755 if (ArgIx < NumArgs) {
4756 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004757
Eli Friedman3164fb12009-03-22 22:00:50 +00004758 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4759 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004760 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004761 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004762 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004763
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004764 // Pass the argument
4765 ParmVarDecl *Param = 0;
4766 if (FDecl && i < FDecl->getNumParams())
4767 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004768
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004769 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004770 Param? InitializedEntity::InitializeParameter(Context, Param)
4771 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004772 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004773 SourceLocation(),
4774 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004775 if (ArgE.isInvalid())
4776 return true;
4777
4778 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004779 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004780 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004781
John McCalldadc5752010-08-24 06:29:42 +00004782 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004783 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004784 if (ArgExpr.isInvalid())
4785 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004786
Anders Carlsson355933d2009-08-25 03:49:14 +00004787 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004788 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004789 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004790 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004791
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004792 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004793 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004794
4795 // Assume that extern "C" functions with variadic arguments that
4796 // return __unknown_anytype aren't *really* variadic.
4797 if (Proto->getResultType() == Context.UnknownAnyTy &&
4798 FDecl && FDecl->isExternC()) {
4799 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4800 ExprResult arg;
4801 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4802 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4803 else
4804 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4805 Invalid |= arg.isInvalid();
4806 AllArgs.push_back(arg.take());
4807 }
4808
4809 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4810 } else {
4811 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4812 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4813 Invalid |= Arg.isInvalid();
4814 AllArgs.push_back(Arg.take());
4815 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004816 }
4817 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004818 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004819}
4820
John McCall2979fe02011-04-12 00:42:48 +00004821/// Given a function expression of unknown-any type, try to rebuild it
4822/// to have a function type.
4823static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4824
Steve Naroff83895f72007-09-16 03:34:24 +00004825/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004826/// This provides the location of the left/right parens and a list of comma
4827/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004828ExprResult
John McCallb268a282010-08-23 23:25:46 +00004829Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004830 MultiExprArg args, SourceLocation RParenLoc,
4831 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004832 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004833
4834 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004835 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004836 if (Result.isInvalid()) return ExprError();
4837 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004838
John McCallb268a282010-08-23 23:25:46 +00004839 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004840
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004841 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004842 // If this is a pseudo-destructor expression, build the call immediately.
4843 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4844 if (NumArgs > 0) {
4845 // Pseudo-destructor calls should not have any arguments.
4846 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004847 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004848 SourceRange(Args[0]->getLocStart(),
4849 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004850
Douglas Gregorad8a3362009-09-04 17:36:40 +00004851 NumArgs = 0;
4852 }
Mike Stump11289f42009-09-09 15:08:12 +00004853
Douglas Gregorad8a3362009-09-04 17:36:40 +00004854 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004855 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004856 }
Mike Stump11289f42009-09-09 15:08:12 +00004857
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004858 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004859 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004860 // FIXME: Will need to cache the results of name lookup (including ADL) in
4861 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004862 bool Dependent = false;
4863 if (Fn->isTypeDependent())
4864 Dependent = true;
4865 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4866 Dependent = true;
4867
Peter Collingbourne41f85462011-02-09 21:07:24 +00004868 if (Dependent) {
4869 if (ExecConfig) {
4870 return Owned(new (Context) CUDAKernelCallExpr(
4871 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4872 Context.DependentTy, VK_RValue, RParenLoc));
4873 } else {
4874 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4875 Context.DependentTy, VK_RValue,
4876 RParenLoc));
4877 }
4878 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004879
4880 // Determine whether this is a call to an object (C++ [over.call.object]).
4881 if (Fn->getType()->isRecordType())
4882 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004883 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004884
John McCall2979fe02011-04-12 00:42:48 +00004885 if (Fn->getType() == Context.UnknownAnyTy) {
4886 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4887 if (result.isInvalid()) return ExprError();
4888 Fn = result.take();
4889 }
4890
John McCall0009fcc2011-04-26 20:42:42 +00004891 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004892 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004893 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004894 }
John McCall0009fcc2011-04-26 20:42:42 +00004895 }
John McCall10eae182009-11-30 22:42:35 +00004896
John McCall0009fcc2011-04-26 20:42:42 +00004897 // Check for overloaded calls. This can happen even in C due to extensions.
4898 if (Fn->getType() == Context.OverloadTy) {
4899 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4900
4901 // We aren't supposed to apply this logic if there's an '&' involved.
4902 if (!find.IsAddressOfOperand) {
4903 OverloadExpr *ovl = find.Expression;
4904 if (isa<UnresolvedLookupExpr>(ovl)) {
4905 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4906 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4907 RParenLoc, ExecConfig);
4908 } else {
John McCall2d74de92009-12-01 22:10:20 +00004909 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004910 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004911 }
4912 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004913 }
4914
Douglas Gregore254f902009-02-04 00:32:51 +00004915 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004916
Eli Friedmane14b1992009-12-26 03:35:45 +00004917 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004918
John McCall57500772009-12-16 12:17:52 +00004919 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004920 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4921 if (UnOp->getOpcode() == UO_AddrOf)
4922 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4923
John McCall57500772009-12-16 12:17:52 +00004924 if (isa<DeclRefExpr>(NakedFn))
4925 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00004926 else if (isa<MemberExpr>(NakedFn))
4927 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004928
Peter Collingbourne41f85462011-02-09 21:07:24 +00004929 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4930 ExecConfig);
4931}
4932
4933ExprResult
4934Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4935 MultiExprArg execConfig, SourceLocation GGGLoc) {
4936 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4937 if (!ConfigDecl)
4938 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4939 << "cudaConfigureCall");
4940 QualType ConfigQTy = ConfigDecl->getType();
4941
4942 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4943 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4944
4945 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004946}
4947
John McCall57500772009-12-16 12:17:52 +00004948/// BuildResolvedCallExpr - Build a call to a resolved expression,
4949/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004950/// unary-convert to an expression of function-pointer or
4951/// block-pointer type.
4952///
4953/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004954ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004955Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4956 SourceLocation LParenLoc,
4957 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004958 SourceLocation RParenLoc,
4959 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004960 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4961
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004962 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004963 ExprResult Result = UsualUnaryConversions(Fn);
4964 if (Result.isInvalid())
4965 return ExprError();
4966 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004967
Chris Lattner08464942007-12-28 05:29:59 +00004968 // Make the call expr early, before semantic checks. This guarantees cleanup
4969 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004970 CallExpr *TheCall;
4971 if (Config) {
4972 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4973 cast<CallExpr>(Config),
4974 Args, NumArgs,
4975 Context.BoolTy,
4976 VK_RValue,
4977 RParenLoc);
4978 } else {
4979 TheCall = new (Context) CallExpr(Context, Fn,
4980 Args, NumArgs,
4981 Context.BoolTy,
4982 VK_RValue,
4983 RParenLoc);
4984 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004985
John McCallbebede42011-02-26 05:39:39 +00004986 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4987
4988 // Bail out early if calling a builtin with custom typechecking.
4989 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4990 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4991
John McCall31996342011-04-07 08:22:57 +00004992 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004993 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004994 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004995 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4996 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004997 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004998 if (FuncT == 0)
4999 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5000 << Fn->getType() << Fn->getSourceRange());
5001 } else if (const BlockPointerType *BPT =
5002 Fn->getType()->getAs<BlockPointerType>()) {
5003 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5004 } else {
John McCall31996342011-04-07 08:22:57 +00005005 // Handle calls to expressions of unknown-any type.
5006 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005007 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005008 if (rewrite.isInvalid()) return ExprError();
5009 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00005010 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005011 goto retry;
5012 }
5013
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005014 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5015 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005016 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005017
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005018 if (getLangOptions().CUDA) {
5019 if (Config) {
5020 // CUDA: Kernel calls must be to global functions
5021 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5022 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5023 << FDecl->getName() << Fn->getSourceRange());
5024
5025 // CUDA: Kernel function must have 'void' return type
5026 if (!FuncT->getResultType()->isVoidType())
5027 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5028 << Fn->getType() << Fn->getSourceRange());
5029 }
5030 }
5031
Eli Friedman3164fb12009-03-22 22:00:50 +00005032 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005033 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00005034 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005035 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005036 return ExprError();
5037
Chris Lattner08464942007-12-28 05:29:59 +00005038 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005039 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00005040 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005041
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005042 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00005043 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005044 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005045 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005046 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005047 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005048
Douglas Gregord8e97de2009-04-02 15:37:10 +00005049 if (FDecl) {
5050 // Check if we have too few/too many template arguments, based
5051 // on our knowledge of the function definition.
5052 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005053 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005054 const FunctionProtoType *Proto
5055 = Def->getType()->getAs<FunctionProtoType>();
5056 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005057 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5058 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005059 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005060
5061 // If the function we're calling isn't a function prototype, but we have
5062 // a function prototype from a prior declaratiom, use that prototype.
5063 if (!FDecl->hasPrototype())
5064 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005065 }
5066
Steve Naroff0b661582007-08-28 23:30:39 +00005067 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005068 for (unsigned i = 0; i != NumArgs; i++) {
5069 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005070
5071 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005072 InitializedEntity Entity
5073 = InitializedEntity::InitializeParameter(Context,
5074 Proto->getArgType(i));
5075 ExprResult ArgE = PerformCopyInitialization(Entity,
5076 SourceLocation(),
5077 Owned(Arg));
5078 if (ArgE.isInvalid())
5079 return true;
5080
5081 Arg = ArgE.takeAs<Expr>();
5082
5083 } else {
John Wiegley01296292011-04-08 18:41:53 +00005084 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5085
5086 if (ArgE.isInvalid())
5087 return true;
5088
5089 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005090 }
5091
Douglas Gregor83025412010-10-26 05:45:40 +00005092 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5093 Arg->getType(),
5094 PDiag(diag::err_call_incomplete_argument)
5095 << Arg->getSourceRange()))
5096 return ExprError();
5097
Chris Lattner08464942007-12-28 05:29:59 +00005098 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005099 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005100 }
Chris Lattner08464942007-12-28 05:29:59 +00005101
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005102 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5103 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005104 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5105 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005106
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005107 // Check for sentinels
5108 if (NDecl)
5109 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005110
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005111 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005112 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005113 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005114 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005115
John McCallbebede42011-02-26 05:39:39 +00005116 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005117 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005118 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005119 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005120 return ExprError();
5121 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005122
John McCallb268a282010-08-23 23:25:46 +00005123 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005124}
5125
John McCalldadc5752010-08-24 06:29:42 +00005126ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005127Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005128 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005129 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005130 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005131 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005132
5133 TypeSourceInfo *TInfo;
5134 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5135 if (!TInfo)
5136 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5137
John McCallb268a282010-08-23 23:25:46 +00005138 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005139}
5140
John McCalldadc5752010-08-24 06:29:42 +00005141ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005142Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005143 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005144 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005145
Eli Friedman37a186d2008-05-20 05:22:08 +00005146 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005147 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5148 PDiag(diag::err_illegal_decl_array_incomplete_type)
5149 << SourceRange(LParenLoc,
5150 literalExpr->getSourceRange().getEnd())))
5151 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005152 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005153 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5154 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005155 } else if (!literalType->isDependentType() &&
5156 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005157 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005158 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005159 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005160 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005161
Douglas Gregor85dabae2009-12-16 01:38:02 +00005162 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005163 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005164 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005165 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005166 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005167 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005168 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005169 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005170 &literalType);
5171 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005172 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005173 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005174
Chris Lattner79413952008-12-04 23:50:19 +00005175 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005176 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005177 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005178 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005179 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005180
John McCall7decc9e2010-11-18 06:31:45 +00005181 // In C, compound literals are l-values for some reason.
5182 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5183
John McCall5d7aa7f2010-01-19 22:33:45 +00005184 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005185 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005186}
5187
John McCalldadc5752010-08-24 06:29:42 +00005188ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005189Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005190 SourceLocation RBraceLoc) {
5191 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005192 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005193
Steve Naroff30d242c2007-09-15 18:49:24 +00005194 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005195 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005196
Ted Kremenekac034612010-04-13 23:39:13 +00005197 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5198 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005199 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005200 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005201}
5202
John McCalld7646252010-11-14 08:17:51 +00005203/// Prepares for a scalar cast, performing all the necessary stages
5204/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005205static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005206 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5207 // Also, callers should have filtered out the invalid cases with
5208 // pointers. Everything else should be possible.
5209
John Wiegley01296292011-04-08 18:41:53 +00005210 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005211 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005212 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005213
John McCall8cb679e2010-11-15 09:13:47 +00005214 switch (SrcTy->getScalarTypeKind()) {
5215 case Type::STK_MemberPointer:
5216 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005217
John McCall8cb679e2010-11-15 09:13:47 +00005218 case Type::STK_Pointer:
5219 switch (DestTy->getScalarTypeKind()) {
5220 case Type::STK_Pointer:
5221 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005222 CK_AnyPointerToObjCPointerCast :
5223 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005224 case Type::STK_Bool:
5225 return CK_PointerToBoolean;
5226 case Type::STK_Integral:
5227 return CK_PointerToIntegral;
5228 case Type::STK_Floating:
5229 case Type::STK_FloatingComplex:
5230 case Type::STK_IntegralComplex:
5231 case Type::STK_MemberPointer:
5232 llvm_unreachable("illegal cast from pointer");
5233 }
5234 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005235
John McCall8cb679e2010-11-15 09:13:47 +00005236 case Type::STK_Bool: // casting from bool is like casting from an integer
5237 case Type::STK_Integral:
5238 switch (DestTy->getScalarTypeKind()) {
5239 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005240 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005241 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005242 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005243 case Type::STK_Bool:
5244 return CK_IntegralToBoolean;
5245 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005246 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005247 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005248 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005249 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005250 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5251 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005252 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005253 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005254 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5255 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005256 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005257 case Type::STK_MemberPointer:
5258 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005259 }
5260 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005261
John McCall8cb679e2010-11-15 09:13:47 +00005262 case Type::STK_Floating:
5263 switch (DestTy->getScalarTypeKind()) {
5264 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005265 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005266 case Type::STK_Bool:
5267 return CK_FloatingToBoolean;
5268 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005269 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005270 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005271 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5272 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005273 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005274 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005275 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5276 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005277 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005278 case Type::STK_Pointer:
5279 llvm_unreachable("valid float->pointer cast?");
5280 case Type::STK_MemberPointer:
5281 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005282 }
5283 break;
5284
John McCall8cb679e2010-11-15 09:13:47 +00005285 case Type::STK_FloatingComplex:
5286 switch (DestTy->getScalarTypeKind()) {
5287 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005288 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005289 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005290 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005291 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005292 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005293 if (S.Context.hasSameType(ET, DestTy))
5294 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005295 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005296 return CK_FloatingCast;
5297 }
John McCall8cb679e2010-11-15 09:13:47 +00005298 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005299 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005300 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005301 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5302 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005303 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005304 case Type::STK_Pointer:
5305 llvm_unreachable("valid complex float->pointer cast?");
5306 case Type::STK_MemberPointer:
5307 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005308 }
5309 break;
5310
John McCall8cb679e2010-11-15 09:13:47 +00005311 case Type::STK_IntegralComplex:
5312 switch (DestTy->getScalarTypeKind()) {
5313 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005314 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005315 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005316 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005317 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005318 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005319 if (S.Context.hasSameType(ET, DestTy))
5320 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005321 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005322 return CK_IntegralCast;
5323 }
John McCall8cb679e2010-11-15 09:13:47 +00005324 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005325 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005326 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005327 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5328 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005329 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005330 case Type::STK_Pointer:
5331 llvm_unreachable("valid complex int->pointer cast?");
5332 case Type::STK_MemberPointer:
5333 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005334 }
5335 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005336 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005337
John McCalld7646252010-11-14 08:17:51 +00005338 llvm_unreachable("Unhandled scalar cast");
5339 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005340}
5341
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005342/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005343ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5344 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5345 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005346 if (castExpr->getType() == Context.UnknownAnyTy)
5347 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5348
Sebastian Redl9f831db2009-07-25 15:41:38 +00005349 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005350 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5351 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005352 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005353 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005354
John McCall3aef3d82011-04-10 19:13:55 +00005355 assert(!castExpr->getType()->isPlaceholderType());
5356
John McCall7decc9e2010-11-18 06:31:45 +00005357 // We only support r-value casts in C.
5358 VK = VK_RValue;
5359
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005360 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5361 // type needs to be scalar.
5362 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005363 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005364 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5365 if (castExprRes.isInvalid())
5366 return ExprError();
5367 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005368
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005369 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005370 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005371 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005372 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005373
John Wiegley01296292011-04-08 18:41:53 +00005374 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5375 if (castExprRes.isInvalid())
5376 return ExprError();
5377 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005378
Eli Friedmane98194d2010-07-17 20:43:49 +00005379 if (RequireCompleteType(TyR.getBegin(), castType,
5380 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005381 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005382
Anders Carlssonef918ac2009-10-16 02:35:04 +00005383 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005384 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005385 (castType->isStructureType() || castType->isUnionType())) {
5386 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005387 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005388 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5389 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005390 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005391 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005392 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005393
Anders Carlsson525b76b2009-10-16 02:48:28 +00005394 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005395 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005396 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005397 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005398 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005399 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005400 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005401 castExpr->getType()) &&
5402 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005403 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5404 << castExpr->getSourceRange();
5405 break;
5406 }
5407 }
John Wiegley01296292011-04-08 18:41:53 +00005408 if (Field == FieldEnd) {
5409 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005410 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005411 return ExprError();
5412 }
John McCalle3027922010-08-25 11:45:40 +00005413 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005414 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005415 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005416
Anders Carlsson525b76b2009-10-16 02:48:28 +00005417 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005418 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005419 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005420 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005421 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005422
John McCalld7646252010-11-14 08:17:51 +00005423 // The type we're casting to is known to be a scalar or vector.
5424
5425 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005426 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005427 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005428 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005429 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005430 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005431 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005433
5434 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005435 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005436
Anton Yartsev28ccef72011-03-27 09:32:40 +00005437 if (castType->isVectorType()) {
5438 if (castType->getAs<VectorType>()->getVectorKind() ==
5439 VectorType::AltiVecVector &&
5440 (castExpr->getType()->isIntegerType() ||
5441 castExpr->getType()->isFloatingType())) {
5442 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005443 return Owned(castExpr);
5444 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5445 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005446 } else
John Wiegley01296292011-04-08 18:41:53 +00005447 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005448 }
John Wiegley01296292011-04-08 18:41:53 +00005449 if (castExpr->getType()->isVectorType()) {
5450 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5451 return ExprError();
5452 else
5453 return Owned(castExpr);
5454 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005455
John McCalld7646252010-11-14 08:17:51 +00005456 // The source and target types are both scalars, i.e.
5457 // - arithmetic types (fundamental, enum, and complex)
5458 // - all kinds of pointers
5459 // Note that member pointers were filtered out with C++, above.
5460
John Wiegley01296292011-04-08 18:41:53 +00005461 if (isa<ObjCSelectorExpr>(castExpr)) {
5462 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5463 return ExprError();
5464 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005465
John McCalld7646252010-11-14 08:17:51 +00005466 // If either type is a pointer, the other type has to be either an
5467 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005468 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005469 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005470 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005471 castExprType->isArithmeticType()) {
5472 Diag(castExpr->getLocStart(),
5473 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005474 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005475 return ExprError();
5476 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005477 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005478 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5479 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005480 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005481 return ExprError();
5482 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005483 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005484
John Wiegley01296292011-04-08 18:41:53 +00005485 castExprRes = Owned(castExpr);
5486 Kind = PrepareScalarCast(*this, castExprRes, castType);
5487 if (castExprRes.isInvalid())
5488 return ExprError();
5489 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005490
John McCalld7646252010-11-14 08:17:51 +00005491 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005492 CheckCastAlign(castExpr, castType, TyR);
5493
John Wiegley01296292011-04-08 18:41:53 +00005494 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005495}
5496
Anders Carlsson525b76b2009-10-16 02:48:28 +00005497bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005498 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005499 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005500
Anders Carlssonde71adf2007-11-27 05:51:55 +00005501 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005502 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005503 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005504 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005505 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005506 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005507 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005508 } else
5509 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005510 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005511 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005512
John McCalle3027922010-08-25 11:45:40 +00005513 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005514 return false;
5515}
5516
John Wiegley01296292011-04-08 18:41:53 +00005517ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5518 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005519 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005520
Anders Carlsson43d70f82009-10-16 05:23:41 +00005521 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005522
Nate Begemanc8961a42009-06-27 22:05:55 +00005523 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5524 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005525 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005526 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5527 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005528 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005529 return ExprError();
5530 }
John McCalle3027922010-08-25 11:45:40 +00005531 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005532 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005533 }
5534
Nate Begemanbd956c42009-06-28 02:36:38 +00005535 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005536 // conversion will take place first from scalar to elt type, and then
5537 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005538 if (SrcTy->isPointerType())
5539 return Diag(R.getBegin(),
5540 diag::err_invalid_conversion_between_vector_and_scalar)
5541 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005542
5543 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005544 ExprResult CastExprRes = Owned(CastExpr);
5545 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5546 if (CastExprRes.isInvalid())
5547 return ExprError();
5548 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005549
John McCalle3027922010-08-25 11:45:40 +00005550 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005551 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005552}
5553
John McCalldadc5752010-08-24 06:29:42 +00005554ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005555Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005556 SourceLocation RParenLoc, Expr *castExpr) {
5557 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005558 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005559
John McCall97513962010-01-15 18:39:57 +00005560 TypeSourceInfo *castTInfo;
5561 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5562 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005563 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005564
Nate Begeman5ec4b312009-08-10 23:49:36 +00005565 // If the Expr being casted is a ParenListExpr, handle it specially.
5566 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005567 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005568 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005569
John McCallb268a282010-08-23 23:25:46 +00005570 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005571}
5572
John McCalldadc5752010-08-24 06:29:42 +00005573ExprResult
John McCallebe54742010-01-15 18:56:44 +00005574Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005575 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005576 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005577 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005578 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005579 ExprResult CastResult =
5580 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5581 Kind, VK, BasePath);
5582 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005583 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005584 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005585
John McCallcf142162010-08-07 06:22:56 +00005586 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005587 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005588 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005589 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005590}
5591
Nate Begeman5ec4b312009-08-10 23:49:36 +00005592/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5593/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005594ExprResult
John McCallb268a282010-08-23 23:25:46 +00005595Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005596 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5597 if (!E)
5598 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005599
John McCalldadc5752010-08-24 06:29:42 +00005600 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005601
Nate Begeman5ec4b312009-08-10 23:49:36 +00005602 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005603 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5604 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005605
John McCallb268a282010-08-23 23:25:46 +00005606 if (Result.isInvalid()) return ExprError();
5607
5608 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005609}
5610
John McCalldadc5752010-08-24 06:29:42 +00005611ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005612Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005613 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005614 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005615 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005616 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005617 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005618
Anton Yartsev28ccef72011-03-27 09:32:40 +00005619 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005620 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005621 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5622 if (PE->getNumExprs() == 0) {
5623 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5624 return ExprError();
5625 }
John Thompson781ad172010-06-30 22:55:51 +00005626 if (PE->getNumExprs() == 1) {
5627 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005628 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005629 }
5630 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005631 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005632 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005633
Anton Yartsev28ccef72011-03-27 09:32:40 +00005634 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005635 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005636 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005637 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005638 // '(...)' form of vector initialization in AltiVec: the number of
5639 // initializers must be one or must match the size of the vector.
5640 // If a single value is specified in the initializer then it will be
5641 // replicated to all the components of the vector
5642 if (Ty->getAs<VectorType>()->getVectorKind() ==
5643 VectorType::AltiVecVector) {
5644 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5645 // The number of initializers must be one or must match the size of the
5646 // vector. If a single value is specified in the initializer then it will
5647 // be replicated to all the components of the vector
5648 if (PE->getNumExprs() == 1) {
5649 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005650 ExprResult Literal = Owned(PE->getExpr(0));
5651 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5652 PrepareScalarCast(*this, Literal, ElemTy));
5653 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005654 }
5655 else if (PE->getNumExprs() < numElems) {
5656 Diag(PE->getExprLoc(),
5657 diag::err_incorrect_number_of_vector_initializers);
5658 return ExprError();
5659 }
5660 else
5661 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5662 initExprs.push_back(PE->getExpr(i));
5663 }
5664 else
5665 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5666 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005667
5668 // FIXME: This means that pretty-printing the final AST will produce curly
5669 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005670 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5671 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005672 initExprs.size(), RParenLoc);
5673 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005674 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005675 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005676 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005677 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005678 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005679 if (Result.isInvalid()) return ExprError();
5680 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005681 }
5682}
5683
John McCalldadc5752010-08-24 06:29:42 +00005684ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005685 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005686 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005687 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005688 unsigned nexprs = Val.size();
5689 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005690 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5691 Expr *expr;
5692 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5693 expr = new (Context) ParenExpr(L, R, exprs[0]);
5694 else
5695 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005696 return Owned(expr);
5697}
5698
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005699/// \brief Emit a specialized diagnostic when one expression is a null pointer
5700/// constant and the other is not a pointer.
5701bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5702 SourceLocation QuestionLoc) {
5703 Expr *NullExpr = LHS;
5704 Expr *NonPointerExpr = RHS;
5705 Expr::NullPointerConstantKind NullKind =
5706 NullExpr->isNullPointerConstant(Context,
5707 Expr::NPC_ValueDependentIsNotNull);
5708
5709 if (NullKind == Expr::NPCK_NotNull) {
5710 NullExpr = RHS;
5711 NonPointerExpr = LHS;
5712 NullKind =
5713 NullExpr->isNullPointerConstant(Context,
5714 Expr::NPC_ValueDependentIsNotNull);
5715 }
5716
5717 if (NullKind == Expr::NPCK_NotNull)
5718 return false;
5719
5720 if (NullKind == Expr::NPCK_ZeroInteger) {
5721 // In this case, check to make sure that we got here from a "NULL"
5722 // string in the source code.
5723 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005724 SourceLocation loc = NullExpr->getExprLoc();
5725 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005726 return false;
5727 }
5728
5729 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5730 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5731 << NonPointerExpr->getType() << DiagType
5732 << NonPointerExpr->getSourceRange();
5733 return true;
5734}
5735
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005736/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5737/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005738/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005739QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005740 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005741 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005742
John McCall3aef3d82011-04-10 19:13:55 +00005743 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005744 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005745 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005746
John McCall3aef3d82011-04-10 19:13:55 +00005747 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005748 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005749 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005750
Sebastian Redl1a99f442009-04-16 17:51:27 +00005751 // C++ is sufficiently different to merit its own checker.
5752 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005753 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005754
5755 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005756 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005757
John Wiegley01296292011-04-08 18:41:53 +00005758 Cond = UsualUnaryConversions(Cond.take());
5759 if (Cond.isInvalid())
5760 return QualType();
5761 LHS = UsualUnaryConversions(LHS.take());
5762 if (LHS.isInvalid())
5763 return QualType();
5764 RHS = UsualUnaryConversions(RHS.take());
5765 if (RHS.isInvalid())
5766 return QualType();
5767
5768 QualType CondTy = Cond.get()->getType();
5769 QualType LHSTy = LHS.get()->getType();
5770 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005771
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005772 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005773 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005774 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5775 // Throw an error if its not either.
5776 if (getLangOptions().OpenCL) {
5777 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005778 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005779 diag::err_typecheck_cond_expect_scalar_or_vector)
5780 << CondTy;
5781 return QualType();
5782 }
5783 }
5784 else {
John Wiegley01296292011-04-08 18:41:53 +00005785 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005786 << CondTy;
5787 return QualType();
5788 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005789 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005790
Chris Lattnere2949f42008-01-06 22:42:25 +00005791 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005792 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5793 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005794
Nate Begemanabb5a732010-09-20 22:41:17 +00005795 // OpenCL: If the condition is a vector, and both operands are scalar,
5796 // attempt to implicity convert them to the vector type to act like the
5797 // built in select.
5798 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5799 // Both operands should be of scalar type.
5800 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005801 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005802 << CondTy;
5803 return QualType();
5804 }
5805 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005806 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005807 << CondTy;
5808 return QualType();
5809 }
5810 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005811 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5812 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005813 }
5814
Chris Lattnere2949f42008-01-06 22:42:25 +00005815 // If both operands have arithmetic type, do the usual arithmetic conversions
5816 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005817 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5818 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005819 if (LHS.isInvalid() || RHS.isInvalid())
5820 return QualType();
5821 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005822 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005823
Chris Lattnere2949f42008-01-06 22:42:25 +00005824 // If both operands are the same structure or union type, the result is that
5825 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005826 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5827 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005828 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005829 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005830 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005831 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005832 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005833 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005834
Chris Lattnere2949f42008-01-06 22:42:25 +00005835 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005836 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005837 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5838 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005839 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5840 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005841 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005842 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5843 << LHS.get()->getSourceRange();
5844 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5845 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005846 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005847 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005848 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5849 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005850 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005851 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005852 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005853 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005854 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005855 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005856 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005857 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5858 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005859 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005860 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005861
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005862 // All objective-c pointer type analysis is done here.
5863 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5864 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005865 if (LHS.isInvalid() || RHS.isInvalid())
5866 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005867 if (!compositeType.isNull())
5868 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005869
5870
Steve Naroff05efa972009-07-01 14:36:47 +00005871 // Handle block pointer types.
5872 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5873 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5874 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5875 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005876 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5877 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005878 return destType;
5879 }
5880 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005881 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005882 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005883 }
Steve Naroff05efa972009-07-01 14:36:47 +00005884 // We have 2 block pointer types.
5885 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5886 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005887 return LHSTy;
5888 }
Steve Naroff05efa972009-07-01 14:36:47 +00005889 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005890 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5891 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005892
Steve Naroff05efa972009-07-01 14:36:47 +00005893 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5894 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005895 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005896 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005897 // In this situation, we assume void* type. No especially good
5898 // reason, but this is what gcc does, and we do have to pick
5899 // to get a consistent AST.
5900 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005901 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5902 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005903 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005904 }
Steve Naroff05efa972009-07-01 14:36:47 +00005905 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005906 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5907 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005908 return LHSTy;
5909 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005910
Steve Naroff05efa972009-07-01 14:36:47 +00005911 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5912 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5913 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005914 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5915 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005916
5917 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5918 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5919 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005920 QualType destPointee
5921 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005922 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005923 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005924 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005925 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005926 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005927 return destType;
5928 }
5929 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005930 QualType destPointee
5931 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005932 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005933 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005934 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005935 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005936 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005937 return destType;
5938 }
5939
5940 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5941 // Two identical pointer types are always compatible.
5942 return LHSTy;
5943 }
5944 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5945 rhptee.getUnqualifiedType())) {
5946 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005947 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005948 // In this situation, we assume void* type. No especially good
5949 // reason, but this is what gcc does, and we do have to pick
5950 // to get a consistent AST.
5951 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005952 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5953 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005954 return incompatTy;
5955 }
5956 // The pointer types are compatible.
5957 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5958 // differently qualified versions of compatible types, the result type is
5959 // a pointer to an appropriately qualified version of the *composite*
5960 // type.
5961 // FIXME: Need to calculate the composite type.
5962 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005963 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5964 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005965 return LHSTy;
5966 }
Mike Stump11289f42009-09-09 15:08:12 +00005967
John McCalle84af4e2010-11-13 01:35:44 +00005968 // GCC compatibility: soften pointer/integer mismatch. Note that
5969 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005970 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5971 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005972 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5973 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005974 return RHSTy;
5975 }
5976 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5977 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005978 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5979 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005980 return LHSTy;
5981 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005982
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005983 // Emit a better diagnostic if one of the expressions is a null pointer
5984 // constant and the other is not a pointer type. In this case, the user most
5985 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005986 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005987 return QualType();
5988
Chris Lattnere2949f42008-01-06 22:42:25 +00005989 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005990 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005991 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005992 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005993}
5994
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005995/// FindCompositeObjCPointerType - Helper method to find composite type of
5996/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005997QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005998 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005999 QualType LHSTy = LHS.get()->getType();
6000 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006001
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006002 // Handle things like Class and struct objc_class*. Here we case the result
6003 // to the pseudo-builtin, because that will be implicitly cast back to the
6004 // redefinition type if an attempt is made to access its fields.
6005 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006006 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006007 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006008 return LHSTy;
6009 }
6010 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006011 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006012 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006013 return RHSTy;
6014 }
6015 // And the same for struct objc_object* / id
6016 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006017 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006018 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006019 return LHSTy;
6020 }
6021 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006022 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006023 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006024 return RHSTy;
6025 }
6026 // And the same for struct objc_selector* / SEL
6027 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006028 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006029 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006030 return LHSTy;
6031 }
6032 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006033 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006034 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006035 return RHSTy;
6036 }
6037 // Check constraints for Objective-C object pointers types.
6038 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006039
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006040 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6041 // Two identical object pointer types are always compatible.
6042 return LHSTy;
6043 }
6044 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6045 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6046 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006047
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006048 // If both operands are interfaces and either operand can be
6049 // assigned to the other, use that type as the composite
6050 // type. This allows
6051 // xxx ? (A*) a : (B*) b
6052 // where B is a subclass of A.
6053 //
6054 // Additionally, as for assignment, if either type is 'id'
6055 // allow silent coercion. Finally, if the types are
6056 // incompatible then make sure to use 'id' as the composite
6057 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006058
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006059 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6060 // It could return the composite type.
6061 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6062 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6063 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6064 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6065 } else if ((LHSTy->isObjCQualifiedIdType() ||
6066 RHSTy->isObjCQualifiedIdType()) &&
6067 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6068 // Need to handle "id<xx>" explicitly.
6069 // GCC allows qualified id and any Objective-C type to devolve to
6070 // id. Currently localizing to here until clear this should be
6071 // part of ObjCQualifiedIdTypesAreCompatible.
6072 compositeType = Context.getObjCIdType();
6073 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6074 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006075 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006076 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6077 ;
6078 else {
6079 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6080 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006081 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006082 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006083 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6084 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006085 return incompatTy;
6086 }
6087 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006088 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6089 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006090 return compositeType;
6091 }
6092 // Check Objective-C object pointer types and 'void *'
6093 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6094 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6095 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6096 QualType destPointee
6097 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6098 QualType destType = Context.getPointerType(destPointee);
6099 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006100 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006101 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006102 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006103 return destType;
6104 }
6105 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6106 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6107 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6108 QualType destPointee
6109 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6110 QualType destType = Context.getPointerType(destPointee);
6111 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006112 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006113 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006114 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006115 return destType;
6116 }
6117 return QualType();
6118}
6119
Steve Naroff83895f72007-09-16 03:34:24 +00006120/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006121/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006122ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006123 SourceLocation ColonLoc,
6124 Expr *CondExpr, Expr *LHSExpr,
6125 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006126 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6127 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006128 OpaqueValueExpr *opaqueValue = 0;
6129 Expr *commonExpr = 0;
6130 if (LHSExpr == 0) {
6131 commonExpr = CondExpr;
6132
6133 // We usually want to apply unary conversions *before* saving, except
6134 // in the special case of a C++ l-value conditional.
6135 if (!(getLangOptions().CPlusPlus
6136 && !commonExpr->isTypeDependent()
6137 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6138 && commonExpr->isGLValue()
6139 && commonExpr->isOrdinaryOrBitFieldObject()
6140 && RHSExpr->isOrdinaryOrBitFieldObject()
6141 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006142 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6143 if (commonRes.isInvalid())
6144 return ExprError();
6145 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006146 }
6147
6148 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6149 commonExpr->getType(),
6150 commonExpr->getValueKind(),
6151 commonExpr->getObjectKind());
6152 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006153 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006154
John McCall7decc9e2010-11-18 06:31:45 +00006155 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006156 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006157 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6158 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006159 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006160 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6161 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006162 return ExprError();
6163
John McCallc07a0c72011-02-17 10:25:35 +00006164 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006165 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6166 LHS.take(), ColonLoc,
6167 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006168
6169 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006170 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6171 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006172}
6173
John McCallaba90822011-01-31 23:13:11 +00006174// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006175// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006176// routine is it effectively iqnores the qualifiers on the top level pointee.
6177// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6178// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006179static Sema::AssignConvertType
6180checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6181 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6182 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006183
Steve Naroff1f4d7272007-05-11 04:00:31 +00006184 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006185 const Type *lhptee, *rhptee;
6186 Qualifiers lhq, rhq;
6187 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6188 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006189
John McCallaba90822011-01-31 23:13:11 +00006190 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006191
6192 // C99 6.5.16.1p1: This following citation is common to constraints
6193 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6194 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006195 Qualifiers lq;
6196
6197 if (!lhq.compatiblyIncludes(rhq)) {
6198 // Treat address-space mismatches as fatal. TODO: address subspaces
6199 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6200 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6201
John McCall78535952011-03-26 02:56:45 +00006202 // It's okay to add or remove GC qualifiers when converting to
6203 // and from void*.
6204 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6205 && (lhptee->isVoidType() || rhptee->isVoidType()))
6206 ; // keep old
6207
John McCall4fff8f62011-02-01 00:10:29 +00006208 // For GCC compatibility, other qualifier mismatches are treated
6209 // as still compatible in C.
6210 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6211 }
Steve Naroff3f597292007-05-11 22:18:03 +00006212
Mike Stump4e1f26a2009-02-19 03:04:26 +00006213 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6214 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006215 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006216 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006217 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006218 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006219
Chris Lattner0a788432008-01-03 22:56:36 +00006220 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006221 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006222 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006223 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006224
Chris Lattner0a788432008-01-03 22:56:36 +00006225 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006226 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006227 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006228
6229 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006230 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006231 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006232 }
John McCall4fff8f62011-02-01 00:10:29 +00006233
Mike Stump4e1f26a2009-02-19 03:04:26 +00006234 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006235 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006236 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6237 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006238 // Check if the pointee types are compatible ignoring the sign.
6239 // We explicitly check for char so that we catch "char" vs
6240 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006241 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006242 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006243 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006244 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006245
Chris Lattnerec3a1562009-10-17 20:33:28 +00006246 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006247 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006248 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006249 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006250
John McCall4fff8f62011-02-01 00:10:29 +00006251 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006252 // Types are compatible ignoring the sign. Qualifier incompatibility
6253 // takes priority over sign incompatibility because the sign
6254 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006255 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006256 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006257
John McCallaba90822011-01-31 23:13:11 +00006258 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006259 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006260
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006261 // If we are a multi-level pointer, it's possible that our issue is simply
6262 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6263 // the eventual target type is the same and the pointers have the same
6264 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006265 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006266 do {
John McCall4fff8f62011-02-01 00:10:29 +00006267 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6268 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006269 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006270
John McCall4fff8f62011-02-01 00:10:29 +00006271 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006272 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006273 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006274
Eli Friedman80160bd2009-03-22 23:59:44 +00006275 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006276 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006277 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006278 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006279}
6280
John McCallaba90822011-01-31 23:13:11 +00006281/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006282/// block pointer types are compatible or whether a block and normal pointer
6283/// are compatible. It is more restrict than comparing two function pointer
6284// types.
John McCallaba90822011-01-31 23:13:11 +00006285static Sema::AssignConvertType
6286checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6287 QualType rhsType) {
6288 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6289 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6290
Steve Naroff081c7422008-09-04 15:10:53 +00006291 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006292
Steve Naroff081c7422008-09-04 15:10:53 +00006293 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006294 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6295 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006296
John McCallaba90822011-01-31 23:13:11 +00006297 // In C++, the types have to match exactly.
6298 if (S.getLangOptions().CPlusPlus)
6299 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006300
John McCallaba90822011-01-31 23:13:11 +00006301 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006302
Steve Naroff081c7422008-09-04 15:10:53 +00006303 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006304 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6305 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006306
John McCallaba90822011-01-31 23:13:11 +00006307 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6308 return Sema::IncompatibleBlockPointer;
6309
Steve Naroff081c7422008-09-04 15:10:53 +00006310 return ConvTy;
6311}
6312
John McCallaba90822011-01-31 23:13:11 +00006313/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006314/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006315static Sema::AssignConvertType
6316checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6317 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6318 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6319
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006320 if (lhsType->isObjCBuiltinType()) {
6321 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006322 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6323 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006324 return Sema::IncompatiblePointer;
6325 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006326 }
6327 if (rhsType->isObjCBuiltinType()) {
6328 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006329 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6330 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006331 return Sema::IncompatiblePointer;
6332 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006333 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006334 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006335 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006336 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006337 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006338
John McCallaba90822011-01-31 23:13:11 +00006339 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6340 return Sema::CompatiblePointerDiscardsQualifiers;
6341
6342 if (S.Context.typesAreCompatible(lhsType, rhsType))
6343 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006344 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006345 return Sema::IncompatibleObjCQualifiedId;
6346 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006347}
6348
John McCall29600e12010-11-16 02:32:08 +00006349Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006350Sema::CheckAssignmentConstraints(SourceLocation Loc,
6351 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006352 // Fake up an opaque expression. We don't actually care about what
6353 // cast operations are required, so if CheckAssignmentConstraints
6354 // adds casts to this they'll be wasted, but fortunately that doesn't
6355 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006356 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006357 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006358 CastKind K = CK_Invalid;
6359
6360 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6361}
6362
Mike Stump4e1f26a2009-02-19 03:04:26 +00006363/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6364/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006365/// pointers. Here are some objectionable examples that GCC considers warnings:
6366///
6367/// int a, *pint;
6368/// short *pshort;
6369/// struct foo *pfoo;
6370///
6371/// pint = pshort; // warning: assignment from incompatible pointer type
6372/// a = pint; // warning: assignment makes integer from pointer without a cast
6373/// pint = a; // warning: assignment makes pointer from integer without a cast
6374/// pint = pfoo; // warning: assignment from incompatible pointer type
6375///
6376/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006377/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006378///
John McCall8cb679e2010-11-15 09:13:47 +00006379/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006380Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006381Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006382 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006383 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006384
Chris Lattnera52c2f22008-01-04 23:18:45 +00006385 // Get canonical types. We're not formatting these types, just comparing
6386 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006387 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6388 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006389
John McCalle5255932011-01-31 22:28:28 +00006390 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006391 if (lhsType == rhsType) {
6392 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006393 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006394 }
6395
Douglas Gregor6b754842008-10-28 00:22:11 +00006396 // If the left-hand side is a reference type, then we are in a
6397 // (rare!) case where we've allowed the use of references in C,
6398 // e.g., as a parameter type in a built-in function. In this case,
6399 // just make sure that the type referenced is compatible with the
6400 // right-hand side type. The caller is responsible for adjusting
6401 // lhsType so that the resulting expression does not have reference
6402 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006403 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006404 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6405 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006406 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006407 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006408 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006409 }
John McCalle5255932011-01-31 22:28:28 +00006410
Nate Begemanbd956c42009-06-28 02:36:38 +00006411 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6412 // to the same ExtVector type.
6413 if (lhsType->isExtVectorType()) {
6414 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006415 return Incompatible;
6416 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006417 // CK_VectorSplat does T -> vector T, so first cast to the
6418 // element type.
6419 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6420 if (elType != rhsType) {
6421 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006422 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006423 }
6424 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006425 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006426 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006427 }
Mike Stump11289f42009-09-09 15:08:12 +00006428
John McCalle5255932011-01-31 22:28:28 +00006429 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006430 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006431 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006432 // Allow assignments of an AltiVec vector type to an equivalent GCC
6433 // vector type and vice versa
6434 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6435 Kind = CK_BitCast;
6436 return Compatible;
6437 }
6438
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006439 // If we are allowing lax vector conversions, and LHS and RHS are both
6440 // vectors, the total size only needs to be the same. This is a bitcast;
6441 // no bits are changed but the result type is different.
6442 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006443 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006444 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006445 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006446 }
Chris Lattner881a2122008-01-04 23:32:24 +00006447 }
6448 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006449 }
Eli Friedman3360d892008-05-30 18:07:22 +00006450
John McCalle5255932011-01-31 22:28:28 +00006451 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006452 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006453 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006454 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006455 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006456 }
Eli Friedman3360d892008-05-30 18:07:22 +00006457
John McCalle5255932011-01-31 22:28:28 +00006458 // Conversions to normal pointers.
6459 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6460 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006461 if (isa<PointerType>(rhsType)) {
6462 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006463 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006464 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
John McCalle5255932011-01-31 22:28:28 +00006466 // int -> T*
6467 if (rhsType->isIntegerType()) {
6468 Kind = CK_IntegralToPointer; // FIXME: null?
6469 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006470 }
John McCalle5255932011-01-31 22:28:28 +00006471
6472 // C pointers are not compatible with ObjC object pointers,
6473 // with two exceptions:
6474 if (isa<ObjCObjectPointerType>(rhsType)) {
6475 // - conversions to void*
6476 if (lhsPointer->getPointeeType()->isVoidType()) {
6477 Kind = CK_AnyPointerToObjCPointerCast;
6478 return Compatible;
6479 }
6480
6481 // - conversions from 'Class' to the redefinition type
6482 if (rhsType->isObjCClassType() &&
6483 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006484 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006485 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006486 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006487
John McCalle5255932011-01-31 22:28:28 +00006488 Kind = CK_BitCast;
6489 return IncompatiblePointer;
6490 }
6491
6492 // U^ -> void*
6493 if (rhsType->getAs<BlockPointerType>()) {
6494 if (lhsPointer->getPointeeType()->isVoidType()) {
6495 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006496 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006497 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006498 }
John McCalle5255932011-01-31 22:28:28 +00006499
Steve Naroff081c7422008-09-04 15:10:53 +00006500 return Incompatible;
6501 }
6502
John McCalle5255932011-01-31 22:28:28 +00006503 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006504 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006505 // U^ -> T^
6506 if (rhsType->isBlockPointerType()) {
6507 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006508 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006509 }
6510
6511 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006512 if (rhsType->isIntegerType()) {
6513 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006514 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006515 }
6516
John McCalle5255932011-01-31 22:28:28 +00006517 // id -> T^
6518 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6519 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006520 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006521 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006522
John McCalle5255932011-01-31 22:28:28 +00006523 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006524 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006525 if (RHSPT->getPointeeType()->isVoidType()) {
6526 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006527 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006528 }
John McCall8cb679e2010-11-15 09:13:47 +00006529
Chris Lattnera52c2f22008-01-04 23:18:45 +00006530 return Incompatible;
6531 }
6532
John McCalle5255932011-01-31 22:28:28 +00006533 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006534 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006535 // A* -> B*
6536 if (rhsType->isObjCObjectPointerType()) {
6537 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006538 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006539 }
6540
6541 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006542 if (rhsType->isIntegerType()) {
6543 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006544 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006545 }
6546
John McCalle5255932011-01-31 22:28:28 +00006547 // In general, C pointers are not compatible with ObjC object pointers,
6548 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006549 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006550 // - conversions from 'void*'
6551 if (rhsType->isVoidPointerType()) {
6552 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006553 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006554 }
6555
6556 // - conversions to 'Class' from its redefinition type
6557 if (lhsType->isObjCClassType() &&
6558 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6559 Kind = CK_BitCast;
6560 return Compatible;
6561 }
6562
6563 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006564 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006565 }
John McCalle5255932011-01-31 22:28:28 +00006566
6567 // T^ -> A*
6568 if (rhsType->isBlockPointerType()) {
6569 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006570 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006571 }
6572
Steve Naroff7cae42b2009-07-10 23:34:53 +00006573 return Incompatible;
6574 }
John McCalle5255932011-01-31 22:28:28 +00006575
6576 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006577 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006578 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006579 if (lhsType == Context.BoolTy) {
6580 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006581 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006582 }
Eli Friedman3360d892008-05-30 18:07:22 +00006583
John McCalle5255932011-01-31 22:28:28 +00006584 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006585 if (lhsType->isIntegerType()) {
6586 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006587 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006588 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006589
Chris Lattnera52c2f22008-01-04 23:18:45 +00006590 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006591 }
John McCalle5255932011-01-31 22:28:28 +00006592
6593 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006594 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006595 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006596 if (lhsType == Context.BoolTy) {
6597 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006598 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006599 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006600
John McCalle5255932011-01-31 22:28:28 +00006601 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006602 if (lhsType->isIntegerType()) {
6603 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006604 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006605 }
6606
Steve Naroff7cae42b2009-07-10 23:34:53 +00006607 return Incompatible;
6608 }
Eli Friedman3360d892008-05-30 18:07:22 +00006609
John McCalle5255932011-01-31 22:28:28 +00006610 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006611 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006612 if (Context.typesAreCompatible(lhsType, rhsType)) {
6613 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006614 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006615 }
Bill Wendling216423b2007-05-30 06:30:29 +00006616 }
John McCalle5255932011-01-31 22:28:28 +00006617
Steve Naroff98cf3e92007-06-06 18:38:38 +00006618 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006619}
6620
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006621/// \brief Constructs a transparent union from an expression that is
6622/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006623static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006624 QualType UnionType, FieldDecl *Field) {
6625 // Build an initializer list that designates the appropriate member
6626 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006627 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006628 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006629 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006630 SourceLocation());
6631 Initializer->setType(UnionType);
6632 Initializer->setInitializedFieldInUnion(Field);
6633
6634 // Build a compound literal constructing a value of the transparent
6635 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006636 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006637 EResult = S.Owned(
6638 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6639 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006640}
6641
6642Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006643Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6644 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006645
Mike Stump11289f42009-09-09 15:08:12 +00006646 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006647 // transparent_union GCC extension.
6648 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006649 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006650 return Incompatible;
6651
6652 // The field to initialize within the transparent union.
6653 RecordDecl *UD = UT->getDecl();
6654 FieldDecl *InitField = 0;
6655 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006656 for (RecordDecl::field_iterator it = UD->field_begin(),
6657 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006658 it != itend; ++it) {
6659 if (it->getType()->isPointerType()) {
6660 // If the transparent union contains a pointer type, we allow:
6661 // 1) void pointer
6662 // 2) null pointer constant
6663 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006664 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006665 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006666 InitField = *it;
6667 break;
6668 }
Mike Stump11289f42009-09-09 15:08:12 +00006669
John Wiegley01296292011-04-08 18:41:53 +00006670 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006671 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006672 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006673 InitField = *it;
6674 break;
6675 }
6676 }
6677
John McCall8cb679e2010-11-15 09:13:47 +00006678 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006679 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006680 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006681 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006682 InitField = *it;
6683 break;
6684 }
6685 }
6686
6687 if (!InitField)
6688 return Incompatible;
6689
John Wiegley01296292011-04-08 18:41:53 +00006690 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006691 return Compatible;
6692}
6693
Chris Lattner9bad62c2008-01-04 18:04:52 +00006694Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006695Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006696 if (getLangOptions().CPlusPlus) {
6697 if (!lhsType->isRecordType()) {
6698 // C++ 5.17p3: If the left operand is not of class type, the
6699 // expression is implicitly converted (C++ 4) to the
6700 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006701 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6702 lhsType.getUnqualifiedType(),
6703 AA_Assigning);
6704 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006705 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006706 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006707 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006708 }
6709
6710 // FIXME: Currently, we fall through and treat C++ classes like C
6711 // structures.
John McCall34376a62010-12-04 03:47:34 +00006712 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006713
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006714 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6715 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006716 if ((lhsType->isPointerType() ||
6717 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006718 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006719 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006720 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006721 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006722 return Compatible;
6723 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006724
Chris Lattnere6dcd502007-10-16 02:55:40 +00006725 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006726 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006727 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006728 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006729 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006731 if (!lhsType->isReferenceType()) {
6732 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6733 if (rExpr.isInvalid())
6734 return Incompatible;
6735 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006736
John McCall8cb679e2010-11-15 09:13:47 +00006737 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006738 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006739 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006740
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006741 // C99 6.5.16.1p2: The value of the right operand is converted to the
6742 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006743 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6744 // so that we can use references in built-in functions even in C.
6745 // The getNonReferenceType() call makes sure that the resulting expression
6746 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006747 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6748 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006749 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006750}
6751
John Wiegley01296292011-04-08 18:41:53 +00006752QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006753 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006754 << lex.get()->getType() << rex.get()->getType()
6755 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006756 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006757}
6758
John Wiegley01296292011-04-08 18:41:53 +00006759QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006760 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006761 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006762 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006763 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006764 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006765 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006766
Nate Begeman191a6b12008-07-14 18:02:46 +00006767 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006768 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006769 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006770
Nate Begeman191a6b12008-07-14 18:02:46 +00006771 // Handle the case of a vector & extvector type of the same size and element
6772 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006773 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006774 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006775 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006776 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006777 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006778 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006779 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006780 return lhsType;
6781 }
6782
John Wiegley01296292011-04-08 18:41:53 +00006783 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006784 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006785 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6786 // If we are allowing lax vector conversions, and LHS and RHS are both
6787 // vectors, the total size only needs to be the same. This is a
6788 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006789 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006790 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006791 }
Eric Christophera613f562010-08-26 00:42:16 +00006792 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006793 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006794 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006795
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006796 // Handle the case of equivalent AltiVec and GCC vector types
6797 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6798 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006799 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006800 return rhsType;
6801 }
6802
Nate Begemanbd956c42009-06-28 02:36:38 +00006803 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6804 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6805 bool swapped = false;
6806 if (rhsType->isExtVectorType()) {
6807 swapped = true;
6808 std::swap(rex, lex);
6809 std::swap(rhsType, lhsType);
6810 }
Mike Stump11289f42009-09-09 15:08:12 +00006811
Nate Begeman886448d2009-06-28 19:12:57 +00006812 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006813 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006814 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006815 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006816 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6817 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006818 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006819 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006820 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006821 if (swapped) std::swap(rex, lex);
6822 return lhsType;
6823 }
6824 }
6825 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6826 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006827 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6828 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006829 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006830 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006831 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006832 if (swapped) std::swap(rex, lex);
6833 return lhsType;
6834 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006835 }
6836 }
Mike Stump11289f42009-09-09 15:08:12 +00006837
Nate Begeman886448d2009-06-28 19:12:57 +00006838 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006839 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006840 << lex.get()->getType() << rex.get()->getType()
6841 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006842 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006843}
6844
Chris Lattnerfaa54172010-01-12 21:23:57 +00006845QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006846 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6847 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006848 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006849
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006850 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006851 if (lex.isInvalid() || rex.isInvalid())
6852 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006853
John Wiegley01296292011-04-08 18:41:53 +00006854 if (!lex.get()->getType()->isArithmeticType() ||
6855 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006856 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006857
Chris Lattnerfaa54172010-01-12 21:23:57 +00006858 // Check for division by zero.
6859 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006860 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6861 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6862 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006863
Chris Lattnerfaa54172010-01-12 21:23:57 +00006864 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006865}
6866
Chris Lattnerfaa54172010-01-12 21:23:57 +00006867QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006868 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6869 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6870 if (lex.get()->getType()->hasIntegerRepresentation() &&
6871 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006872 return CheckVectorOperands(Loc, lex, rex);
6873 return InvalidOperands(Loc, lex, rex);
6874 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006875
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006876 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006877 if (lex.isInvalid() || rex.isInvalid())
6878 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006879
John Wiegley01296292011-04-08 18:41:53 +00006880 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006881 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006882
Chris Lattnerfaa54172010-01-12 21:23:57 +00006883 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006884 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6885 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6886 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006887
Chris Lattnerfaa54172010-01-12 21:23:57 +00006888 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006889}
6890
Chris Lattnerfaa54172010-01-12 21:23:57 +00006891QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006892 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6893 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006894 QualType compType = CheckVectorOperands(Loc, lex, rex);
6895 if (CompLHSTy) *CompLHSTy = compType;
6896 return compType;
6897 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006898
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006899 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006900 if (lex.isInvalid() || rex.isInvalid())
6901 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006902
Steve Naroffe4718892007-04-27 18:30:00 +00006903 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006904 if (lex.get()->getType()->isArithmeticType() &&
6905 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006906 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006907 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006908 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006909
Eli Friedman8e122982008-05-18 18:08:51 +00006910 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006911 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006912 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006913 std::swap(PExp, IExp);
6914
Steve Naroff6b712a72009-07-14 18:25:06 +00006915 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006916
Eli Friedman8e122982008-05-18 18:08:51 +00006917 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006918 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006919
Chris Lattner12bdebb2009-04-24 23:50:08 +00006920 // Check for arithmetic on pointers to incomplete types.
6921 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006922 if (getLangOptions().CPlusPlus) {
6923 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006924 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006925 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006926 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006927
6928 // GNU extension: arithmetic on pointer to void
6929 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006930 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006931 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006932 if (getLangOptions().CPlusPlus) {
6933 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006934 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006935 return QualType();
6936 }
6937
6938 // GNU extension: arithmetic on pointer to function
6939 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006940 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006941 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006942 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006943 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006944 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006945 PExp->getType()->isObjCObjectPointerType()) &&
6946 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006947 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6948 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006949 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006950 return QualType();
6951 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006952 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006953 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006954 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6955 << PointeeTy << PExp->getSourceRange();
6956 return QualType();
6957 }
Mike Stump11289f42009-09-09 15:08:12 +00006958
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006959 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006960 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006961 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006962 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006963 if (LHSTy->isPromotableIntegerType())
6964 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006965 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006966 *CompLHSTy = LHSTy;
6967 }
Eli Friedman8e122982008-05-18 18:08:51 +00006968 return PExp->getType();
6969 }
6970 }
6971
Chris Lattner326f7572008-11-18 01:30:42 +00006972 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006973}
6974
Chris Lattner2a3569b2008-04-07 05:30:13 +00006975// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006976QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006977 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006978 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006979 QualType compType = CheckVectorOperands(Loc, lex, rex);
6980 if (CompLHSTy) *CompLHSTy = compType;
6981 return compType;
6982 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006983
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006984 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006985 if (lex.isInvalid() || rex.isInvalid())
6986 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006987
Chris Lattner4d62f422007-12-09 21:53:25 +00006988 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006989
Chris Lattner4d62f422007-12-09 21:53:25 +00006990 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006991 if (lex.get()->getType()->isArithmeticType() &&
6992 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006993 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006994 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006995 }
Mike Stump11289f42009-09-09 15:08:12 +00006996
Chris Lattner4d62f422007-12-09 21:53:25 +00006997 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006998 if (lex.get()->getType()->isAnyPointerType()) {
6999 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007000
Douglas Gregorac1fb652009-03-24 19:52:54 +00007001 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007002
Douglas Gregorac1fb652009-03-24 19:52:54 +00007003 bool ComplainAboutVoid = false;
7004 Expr *ComplainAboutFunc = 0;
7005 if (lpointee->isVoidType()) {
7006 if (getLangOptions().CPlusPlus) {
7007 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007008 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007009 return QualType();
7010 }
7011
7012 // GNU C extension: arithmetic on pointer to void
7013 ComplainAboutVoid = true;
7014 } else if (lpointee->isFunctionType()) {
7015 if (getLangOptions().CPlusPlus) {
7016 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007017 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007018 return QualType();
7019 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007020
7021 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00007022 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007023 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007024 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007025 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007026 << lex.get()->getSourceRange()
7027 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007028 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007029
Chris Lattner12bdebb2009-04-24 23:50:08 +00007030 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007031 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007032 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00007033 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007034 return QualType();
7035 }
Mike Stump11289f42009-09-09 15:08:12 +00007036
Chris Lattner4d62f422007-12-09 21:53:25 +00007037 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00007038 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007039 if (ComplainAboutVoid)
7040 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007041 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007042 if (ComplainAboutFunc)
7043 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007044 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007045 << ComplainAboutFunc->getSourceRange();
7046
John Wiegley01296292011-04-08 18:41:53 +00007047 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7048 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007049 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007050
Chris Lattner4d62f422007-12-09 21:53:25 +00007051 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007052 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007053 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007054
Douglas Gregorac1fb652009-03-24 19:52:54 +00007055 // RHS must be a completely-type object type.
7056 // Handle the GNU void* extension.
7057 if (rpointee->isVoidType()) {
7058 if (getLangOptions().CPlusPlus) {
7059 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007060 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007061 return QualType();
7062 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007063
Douglas Gregorac1fb652009-03-24 19:52:54 +00007064 ComplainAboutVoid = true;
7065 } else if (rpointee->isFunctionType()) {
7066 if (getLangOptions().CPlusPlus) {
7067 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007068 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007069 return QualType();
7070 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007071
7072 // GNU extension: arithmetic on pointer to function
7073 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007074 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007075 } else if (!rpointee->isDependentType() &&
7076 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007077 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007078 << rex.get()->getSourceRange()
7079 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007080 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007081
Eli Friedman168fe152009-05-16 13:54:38 +00007082 if (getLangOptions().CPlusPlus) {
7083 // Pointee types must be the same: C++ [expr.add]
7084 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7085 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007086 << lex.get()->getType() << rex.get()->getType()
7087 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007088 return QualType();
7089 }
7090 } else {
7091 // Pointee types must be compatible C99 6.5.6p3
7092 if (!Context.typesAreCompatible(
7093 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7094 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7095 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007096 << lex.get()->getType() << rex.get()->getType()
7097 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007098 return QualType();
7099 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007100 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007101
Douglas Gregorac1fb652009-03-24 19:52:54 +00007102 if (ComplainAboutVoid)
7103 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007104 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007105 if (ComplainAboutFunc)
7106 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007107 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007108 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007109
John Wiegley01296292011-04-08 18:41:53 +00007110 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007111 return Context.getPointerDiffType();
7112 }
7113 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007114
Chris Lattner326f7572008-11-18 01:30:42 +00007115 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007116}
7117
Douglas Gregor0bf31402010-10-08 23:50:27 +00007118static bool isScopedEnumerationType(QualType T) {
7119 if (const EnumType *ET = dyn_cast<EnumType>(T))
7120 return ET->getDecl()->isScoped();
7121 return false;
7122}
7123
John Wiegley01296292011-04-08 18:41:53 +00007124static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007125 SourceLocation Loc, unsigned Opc,
7126 QualType LHSTy) {
7127 llvm::APSInt Right;
7128 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007129 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007130 return;
7131
7132 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007133 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007134 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007135 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007136 return;
7137 }
7138 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007139 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007140 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007141 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007142 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007143 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007144 return;
7145 }
7146 if (Opc != BO_Shl)
7147 return;
7148
7149 // When left shifting an ICE which is signed, we can check for overflow which
7150 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7151 // integers have defined behavior modulo one more than the maximum value
7152 // representable in the result type, so never warn for those.
7153 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007154 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007155 LHSTy->hasUnsignedIntegerRepresentation())
7156 return;
7157 llvm::APInt ResultBits =
7158 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7159 if (LeftBits.uge(ResultBits))
7160 return;
7161 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7162 Result = Result.shl(Right);
7163
7164 // If we are only missing a sign bit, this is less likely to result in actual
7165 // bugs -- if the result is cast back to an unsigned type, it will have the
7166 // expected value. Thus we place this behind a different warning that can be
7167 // turned off separately if needed.
7168 if (LeftBits == ResultBits - 1) {
7169 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7170 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007171 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007172 return;
7173 }
7174
7175 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7176 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007177 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007178}
7179
Chris Lattner2a3569b2008-04-07 05:30:13 +00007180// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007181QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007182 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007183 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007184 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7185 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007186 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007187
Douglas Gregor0bf31402010-10-08 23:50:27 +00007188 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7189 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007190 if (isScopedEnumerationType(lex.get()->getType()) ||
7191 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007192 return InvalidOperands(Loc, lex, rex);
7193 }
7194
Nate Begemane46ee9a2009-10-25 02:26:48 +00007195 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007196 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007197 return CheckVectorOperands(Loc, lex, rex);
7198
Chris Lattner5c11c412007-12-12 05:47:28 +00007199 // Shifts don't perform usual arithmetic conversions, they just do integer
7200 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007201
John McCall57cdd882010-12-16 19:28:59 +00007202 // For the LHS, do usual unary conversions, but then reset them away
7203 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007204 ExprResult old_lex = lex;
7205 lex = UsualUnaryConversions(lex.take());
7206 if (lex.isInvalid())
7207 return QualType();
7208 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007209 if (isCompAssign) lex = old_lex;
7210
7211 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007212 rex = UsualUnaryConversions(rex.take());
7213 if (rex.isInvalid())
7214 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007215
Ryan Flynnf53fab82009-08-07 16:20:20 +00007216 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007217 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007218
Chris Lattner5c11c412007-12-12 05:47:28 +00007219 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007220 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007221}
7222
Chandler Carruth17773fc2010-07-10 12:30:03 +00007223static bool IsWithinTemplateSpecialization(Decl *D) {
7224 if (DeclContext *DC = D->getDeclContext()) {
7225 if (isa<ClassTemplateSpecializationDecl>(DC))
7226 return true;
7227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7228 return FD->isFunctionTemplateSpecialization();
7229 }
7230 return false;
7231}
7232
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007233// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007234QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007235 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007236 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007237
Chris Lattner9a152e22009-12-05 05:40:13 +00007238 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007239 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007240 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007241
John Wiegley01296292011-04-08 18:41:53 +00007242 QualType lType = lex.get()->getType();
7243 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007244
John Wiegley01296292011-04-08 18:41:53 +00007245 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7246 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007247 QualType LHSStrippedType = LHSStripped->getType();
7248 QualType RHSStrippedType = RHSStripped->getType();
7249
Douglas Gregor1beec452011-03-12 01:48:56 +00007250
7251
Chandler Carruth712563b2011-02-17 08:37:06 +00007252 // Two different enums will raise a warning when compared.
7253 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7254 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7255 if (LHSEnumType->getDecl()->getIdentifier() &&
7256 RHSEnumType->getDecl()->getIdentifier() &&
7257 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7258 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7259 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007260 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007261 }
7262 }
7263 }
7264
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007265 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007266 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007267 !lex.get()->getLocStart().isMacroID() &&
7268 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007269 // For non-floating point types, check for self-comparisons of the form
7270 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7271 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007272 //
7273 // NOTE: Don't warn about comparison expressions resulting from macro
7274 // expansion. Also don't warn about comparisons which are only self
7275 // comparisons within a template specialization. The warnings should catch
7276 // obvious cases in the definition of the template anyways. The idea is to
7277 // warn when the typed comparison operator will always evaluate to the same
7278 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007279 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007280 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007281 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007282 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007283 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007284 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007285 << (Opc == BO_EQ
7286 || Opc == BO_LE
7287 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007288 } else if (lType->isArrayType() && rType->isArrayType() &&
7289 !DRL->getDecl()->getType()->isReferenceType() &&
7290 !DRR->getDecl()->getType()->isReferenceType()) {
7291 // what is it always going to eval to?
7292 char always_evals_to;
7293 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007294 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007295 always_evals_to = 0; // false
7296 break;
John McCalle3027922010-08-25 11:45:40 +00007297 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007298 always_evals_to = 1; // true
7299 break;
7300 default:
7301 // best we can say is 'a constant'
7302 always_evals_to = 2; // e.g. array1 <= array2
7303 break;
7304 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007305 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007306 << 1 // array
7307 << always_evals_to);
7308 }
7309 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007310 }
Mike Stump11289f42009-09-09 15:08:12 +00007311
Chris Lattner222b8bd2009-03-08 19:39:53 +00007312 if (isa<CastExpr>(LHSStripped))
7313 LHSStripped = LHSStripped->IgnoreParenCasts();
7314 if (isa<CastExpr>(RHSStripped))
7315 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007316
Chris Lattner222b8bd2009-03-08 19:39:53 +00007317 // Warn about comparisons against a string constant (unless the other
7318 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007319 Expr *literalString = 0;
7320 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007321 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007322 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007323 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007324 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007325 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007326 } else if ((isa<StringLiteral>(RHSStripped) ||
7327 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007328 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007329 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007330 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007331 literalStringStripped = RHSStripped;
7332 }
7333
7334 if (literalString) {
7335 std::string resultComparison;
7336 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007337 case BO_LT: resultComparison = ") < 0"; break;
7338 case BO_GT: resultComparison = ") > 0"; break;
7339 case BO_LE: resultComparison = ") <= 0"; break;
7340 case BO_GE: resultComparison = ") >= 0"; break;
7341 case BO_EQ: resultComparison = ") == 0"; break;
7342 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007343 default: assert(false && "Invalid comparison operator");
7344 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007345
Ted Kremenek3427fac2011-02-23 01:52:04 +00007346 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007347 PDiag(diag::warn_stringcompare)
7348 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007349 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007350 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007351 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007352
Douglas Gregorec170db2010-06-08 19:50:34 +00007353 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007354 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007355 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007356 if (lex.isInvalid() || rex.isInvalid())
7357 return QualType();
7358 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007359 else {
John Wiegley01296292011-04-08 18:41:53 +00007360 lex = UsualUnaryConversions(lex.take());
7361 if (lex.isInvalid())
7362 return QualType();
7363
7364 rex = UsualUnaryConversions(rex.take());
7365 if (rex.isInvalid())
7366 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007367 }
7368
John Wiegley01296292011-04-08 18:41:53 +00007369 lType = lex.get()->getType();
7370 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007371
Douglas Gregorca63811b2008-11-19 03:25:36 +00007372 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007373 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007374
Chris Lattnerb620c342007-08-26 01:18:55 +00007375 if (isRelational) {
7376 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007377 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007378 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007379 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007380 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007381 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007382
Chris Lattnerb620c342007-08-26 01:18:55 +00007383 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007384 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007385 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007386
John Wiegley01296292011-04-08 18:41:53 +00007387 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007388 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007389 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007390 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007391
Douglas Gregorf267edd2010-06-15 21:38:40 +00007392 // All of the following pointer-related warnings are GCC extensions, except
7393 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007394 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007395 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007396 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007397 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007398 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007399
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007400 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007401 if (LCanPointeeTy == RCanPointeeTy)
7402 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007403 if (!isRelational &&
7404 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7405 // Valid unless comparison between non-null pointer and function pointer
7406 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007407 // In a SFINAE context, we treat this as a hard error to maintain
7408 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007409 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7410 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007411 Diag(Loc,
7412 isSFINAEContext()?
7413 diag::err_typecheck_comparison_of_fptr_to_void
7414 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007415 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007416
7417 if (isSFINAEContext())
7418 return QualType();
7419
John Wiegley01296292011-04-08 18:41:53 +00007420 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007421 return ResultTy;
7422 }
7423 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007424
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007425 // C++ [expr.rel]p2:
7426 // [...] Pointer conversions (4.10) and qualification
7427 // conversions (4.4) are performed on pointer operands (or on
7428 // a pointer operand and a null pointer constant) to bring
7429 // them to their composite pointer type. [...]
7430 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007431 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007432 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007433 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007434 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007435 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007436 if (T.isNull()) {
7437 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007438 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007439 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007440 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007441 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007442 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007443 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007444 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007445 }
7446
John Wiegley01296292011-04-08 18:41:53 +00007447 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7448 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007449 return ResultTy;
7450 }
Eli Friedman16c209612009-08-23 00:27:47 +00007451 // C99 6.5.9p2 and C99 6.5.8p2
7452 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7453 RCanPointeeTy.getUnqualifiedType())) {
7454 // Valid unless a relational comparison of function pointers
7455 if (isRelational && LCanPointeeTy->isFunctionType()) {
7456 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007457 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007458 }
7459 } else if (!isRelational &&
7460 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7461 // Valid unless comparison between non-null pointer and function pointer
7462 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7463 && !LHSIsNull && !RHSIsNull) {
7464 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007465 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007466 }
7467 } else {
7468 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007469 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007470 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007471 }
John McCall7684dde2011-03-11 04:25:25 +00007472 if (LCanPointeeTy != RCanPointeeTy) {
7473 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007474 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007475 else
John Wiegley01296292011-04-08 18:41:53 +00007476 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007477 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007478 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007479 }
Mike Stump11289f42009-09-09 15:08:12 +00007480
Sebastian Redl576fd422009-05-10 18:38:11 +00007481 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007482 // Comparison of nullptr_t with itself.
7483 if (lType->isNullPtrType() && rType->isNullPtrType())
7484 return ResultTy;
7485
Mike Stump11289f42009-09-09 15:08:12 +00007486 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007487 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007488 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007489 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007490 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007491 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007492 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007493 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007494 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007495 return ResultTy;
7496 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007497 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007498 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007499 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007500 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007501 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007502 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007503 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007504 return ResultTy;
7505 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007506
7507 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007508 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007509 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7510 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007511 // In addition, pointers to members can be compared, or a pointer to
7512 // member and a null pointer constant. Pointer to member conversions
7513 // (4.11) and qualification conversions (4.4) are performed to bring
7514 // them to a common type. If one operand is a null pointer constant,
7515 // the common type is the type of the other operand. Otherwise, the
7516 // common type is a pointer to member type similar (4.4) to the type
7517 // of one of the operands, with a cv-qualification signature (4.4)
7518 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007519 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007520 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007521 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007522 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007523 if (T.isNull()) {
7524 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007525 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007526 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007527 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007528 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007529 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007530 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007531 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007532 }
Mike Stump11289f42009-09-09 15:08:12 +00007533
John Wiegley01296292011-04-08 18:41:53 +00007534 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7535 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007536 return ResultTy;
7537 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007538
7539 // Handle scoped enumeration types specifically, since they don't promote
7540 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007541 if (lex.get()->getType()->isEnumeralType() &&
7542 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007543 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007544 }
Mike Stump11289f42009-09-09 15:08:12 +00007545
Steve Naroff081c7422008-09-04 15:10:53 +00007546 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007547 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007548 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7549 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007550
Steve Naroff081c7422008-09-04 15:10:53 +00007551 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007552 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007553 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007554 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007555 }
John Wiegley01296292011-04-08 18:41:53 +00007556 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007557 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007558 }
John Wiegley01296292011-04-08 18:41:53 +00007559
Steve Naroffe18f94c2008-09-28 01:11:11 +00007560 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007561 if (!isRelational
7562 && ((lType->isBlockPointerType() && rType->isPointerType())
7563 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007564 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007565 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007566 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007567 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007568 ->getPointeeType()->isVoidType())))
7569 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007570 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007571 }
John McCall7684dde2011-03-11 04:25:25 +00007572 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007573 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007574 else
John Wiegley01296292011-04-08 18:41:53 +00007575 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007576 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007577 }
Steve Naroff081c7422008-09-04 15:10:53 +00007578
John McCall7684dde2011-03-11 04:25:25 +00007579 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7580 const PointerType *LPT = lType->getAs<PointerType>();
7581 const PointerType *RPT = rType->getAs<PointerType>();
7582 if (LPT || RPT) {
7583 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7584 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007585
Steve Naroff753567f2008-11-17 19:49:16 +00007586 if (!LPtrToVoid && !RPtrToVoid &&
7587 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007588 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007589 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007590 }
John McCall7684dde2011-03-11 04:25:25 +00007591 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007592 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007593 else
John Wiegley01296292011-04-08 18:41:53 +00007594 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007595 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007596 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007597 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007598 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007599 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007600 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007601 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007602 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007603 else
John Wiegley01296292011-04-08 18:41:53 +00007604 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007605 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007606 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007607 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007608 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7609 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007610 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007611 bool isError = false;
7612 if ((LHSIsNull && lType->isIntegerType()) ||
7613 (RHSIsNull && rType->isIntegerType())) {
7614 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007615 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007616 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007617 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007618 else if (getLangOptions().CPlusPlus) {
7619 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7620 isError = true;
7621 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007622 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007623
Chris Lattnerd99bd522009-08-23 00:03:44 +00007624 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007625 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007626 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007627 if (isError)
7628 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007629 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007630
7631 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007632 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007633 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007634 else
John Wiegley01296292011-04-08 18:41:53 +00007635 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007636 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007637 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007638 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007639
Steve Naroff4b191572008-09-04 16:56:14 +00007640 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007641 if (!isRelational && RHSIsNull
7642 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007643 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007644 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007645 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007646 if (!isRelational && LHSIsNull
7647 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007648 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007649 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007650 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007651
Chris Lattner326f7572008-11-18 01:30:42 +00007652 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007653}
7654
Nate Begeman191a6b12008-07-14 18:02:46 +00007655/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007656/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007657/// like a scalar comparison, a vector comparison produces a vector of integer
7658/// types.
John Wiegley01296292011-04-08 18:41:53 +00007659QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007660 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007661 bool isRelational) {
7662 // Check to make sure we're operating on vectors of the same type and width,
7663 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007664 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007665 if (vType.isNull())
7666 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007667
John Wiegley01296292011-04-08 18:41:53 +00007668 QualType lType = lex.get()->getType();
7669 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007670
Anton Yartsev530deb92011-03-27 15:36:07 +00007671 // If AltiVec, the comparison results in a numeric type, i.e.
7672 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007673 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007674 return Context.getLogicalOperationType();
7675
Nate Begeman191a6b12008-07-14 18:02:46 +00007676 // For non-floating point types, check for self-comparisons of the form
7677 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7678 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007679 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007680 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7681 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007682 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007683 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007684 PDiag(diag::warn_comparison_always)
7685 << 0 // self-
7686 << 2 // "a constant"
7687 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007688 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007689
Nate Begeman191a6b12008-07-14 18:02:46 +00007690 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007691 if (!isRelational && lType->hasFloatingRepresentation()) {
7692 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007693 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007694 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007695
Nate Begeman191a6b12008-07-14 18:02:46 +00007696 // Return the type for the comparison, which is the same as vector type for
7697 // integer vectors, or an integer type of identical size and number of
7698 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007699 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007700 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007701
John McCall9dd450b2009-09-21 23:43:11 +00007702 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007703 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007704 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007705 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007706 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007707 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7708
Mike Stump4e1f26a2009-02-19 03:04:26 +00007709 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007710 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007711 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7712}
7713
Steve Naroff218bc2b2007-05-04 21:54:46 +00007714inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007715 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7716 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7717 if (lex.get()->getType()->hasIntegerRepresentation() &&
7718 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007719 return CheckVectorOperands(Loc, lex, rex);
7720
7721 return InvalidOperands(Loc, lex, rex);
7722 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007723
John Wiegley01296292011-04-08 18:41:53 +00007724 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7725 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7726 if (lexResult.isInvalid() || rexResult.isInvalid())
7727 return QualType();
7728 lex = lexResult.take();
7729 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007730
John Wiegley01296292011-04-08 18:41:53 +00007731 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7732 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007733 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007734 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007735}
7736
Steve Naroff218bc2b2007-05-04 21:54:46 +00007737inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007738 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007739
7740 // Diagnose cases where the user write a logical and/or but probably meant a
7741 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7742 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007743 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7744 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007745 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007746 !Loc.isMacroID()) {
7747 // If the RHS can be constant folded, and if it constant folds to something
7748 // that isn't 0 or 1 (which indicate a potential logical operation that
7749 // happened to fold to true/false) then warn.
7750 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007751 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007752 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7753 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007754 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007755 << (Opc == BO_LAnd ? "&&" : "||")
7756 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007757 }
7758 }
Chris Lattner8406c512010-07-13 19:41:32 +00007759
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007760 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007761 lex = UsualUnaryConversions(lex.take());
7762 if (lex.isInvalid())
7763 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007764
John Wiegley01296292011-04-08 18:41:53 +00007765 rex = UsualUnaryConversions(rex.take());
7766 if (rex.isInvalid())
7767 return QualType();
7768
7769 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007770 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007771
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007772 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007773 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007774
John McCall4a2429a2010-06-04 00:29:51 +00007775 // The following is safe because we only use this method for
7776 // non-overloadable operands.
7777
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007778 // C++ [expr.log.and]p1
7779 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007780 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007781 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7782 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007783 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007784 lex = move(lexRes);
7785
7786 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7787 if (rexRes.isInvalid())
7788 return InvalidOperands(Loc, lex, rex);
7789 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007790
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007791 // C++ [expr.log.and]p2
7792 // C++ [expr.log.or]p2
7793 // The result is a bool.
7794 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007795}
7796
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007797/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7798/// is a read-only property; return true if so. A readonly property expression
7799/// depends on various declarations and thus must be treated specially.
7800///
Mike Stump11289f42009-09-09 15:08:12 +00007801static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007802 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7803 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007804 if (PropExpr->isImplicitProperty()) return false;
7805
7806 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7807 QualType BaseType = PropExpr->isSuperReceiver() ?
7808 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007809 PropExpr->getBase()->getType();
7810
John McCallb7bd14f2010-12-02 01:19:52 +00007811 if (const ObjCObjectPointerType *OPT =
7812 BaseType->getAsObjCInterfacePointerType())
7813 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7814 if (S.isPropertyReadonly(PDecl, IFace))
7815 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007816 }
7817 return false;
7818}
7819
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007820static bool IsConstProperty(Expr *E, Sema &S) {
7821 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7822 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7823 if (PropExpr->isImplicitProperty()) return false;
7824
7825 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7826 QualType T = PDecl->getType();
7827 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007828 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007829 CanQualType CT = S.Context.getCanonicalType(T);
7830 return CT.isConstQualified();
7831 }
7832 return false;
7833}
7834
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007835static bool IsReadonlyMessage(Expr *E, Sema &S) {
7836 if (E->getStmtClass() != Expr::MemberExprClass)
7837 return false;
7838 const MemberExpr *ME = cast<MemberExpr>(E);
7839 NamedDecl *Member = ME->getMemberDecl();
7840 if (isa<FieldDecl>(Member)) {
7841 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7842 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7843 return false;
7844 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7845 }
7846 return false;
7847}
7848
Chris Lattner30bd3272008-11-18 01:22:49 +00007849/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7850/// emit an error and return true. If so, return false.
7851static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007852 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007853 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007854 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007855 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7856 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007857 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7858 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007859 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7860 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007861 if (IsLV == Expr::MLV_Valid)
7862 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007863
Chris Lattner30bd3272008-11-18 01:22:49 +00007864 unsigned Diag = 0;
7865 bool NeedType = false;
7866 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007867 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007868 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007869 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7870 NeedType = true;
7871 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007872 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007873 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7874 NeedType = true;
7875 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007876 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007877 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7878 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007879 case Expr::MLV_Valid:
7880 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007881 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007882 case Expr::MLV_MemberFunction:
7883 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007884 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7885 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007886 case Expr::MLV_IncompleteType:
7887 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007888 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007889 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007890 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007891 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007892 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7893 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007894 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007895 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7896 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007897 case Expr::MLV_ReadonlyProperty:
7898 Diag = diag::error_readonly_property_assignment;
7899 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007900 case Expr::MLV_NoSetterProperty:
7901 Diag = diag::error_nosetter_property_assignment;
7902 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007903 case Expr::MLV_InvalidMessageExpression:
7904 Diag = diag::error_readonly_message_assignment;
7905 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007906 case Expr::MLV_SubObjCPropertySetting:
7907 Diag = diag::error_no_subobject_property_setting;
7908 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007909 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007910
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007911 SourceRange Assign;
7912 if (Loc != OrigLoc)
7913 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007914 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007915 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007916 else
Mike Stump11289f42009-09-09 15:08:12 +00007917 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007918 return true;
7919}
7920
7921
7922
7923// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007924QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007925 SourceLocation Loc,
7926 QualType CompoundType) {
7927 // Verify that LHS is a modifiable lvalue, and emit error if not.
7928 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007929 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007930
7931 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007932 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007933 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007934 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007935 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007936 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007937 if (LHS->getObjectKind() == OK_ObjCProperty) {
7938 ExprResult LHSResult = Owned(LHS);
7939 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7940 if (LHSResult.isInvalid())
7941 return QualType();
7942 LHS = LHSResult.take();
7943 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007944 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007945 if (RHS.isInvalid())
7946 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007947 // Special case of NSObject attributes on c-style pointer types.
7948 if (ConvTy == IncompatiblePointer &&
7949 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007950 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007951 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007952 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007953 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007954
John McCall7decc9e2010-11-18 06:31:45 +00007955 if (ConvTy == Compatible &&
7956 getLangOptions().ObjCNonFragileABI &&
7957 LHSType->isObjCObjectType())
7958 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7959 << LHSType;
7960
Chris Lattnerea714382008-08-21 18:04:13 +00007961 // If the RHS is a unary plus or minus, check to see if they = and + are
7962 // right next to each other. If so, the user may have typo'd "x =+ 4"
7963 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007964 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007965 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7966 RHSCheck = ICE->getSubExpr();
7967 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007968 if ((UO->getOpcode() == UO_Plus ||
7969 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007970 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007971 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007972 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7973 // And there is a space or other character before the subexpr of the
7974 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007975 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7976 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007977 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007978 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007979 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007980 }
Chris Lattnerea714382008-08-21 18:04:13 +00007981 }
7982 } else {
7983 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007984 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007985 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007986
Chris Lattner326f7572008-11-18 01:30:42 +00007987 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007988 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007989 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007990
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007991 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00007992 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007993 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007994
Steve Naroff98cf3e92007-06-06 18:38:38 +00007995 // C99 6.5.16p3: The type of an assignment expression is the type of the
7996 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007997 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007998 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7999 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008000 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008001 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00008002 return (getLangOptions().CPlusPlus
8003 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008004}
8005
Chris Lattner326f7572008-11-18 01:30:42 +00008006// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008007static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008008 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00008009 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00008010
John McCall3aef3d82011-04-10 19:13:55 +00008011 LHS = S.CheckPlaceholderExpr(LHS.take());
8012 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008013 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008014 return QualType();
8015
John McCall73d36182010-10-12 07:14:40 +00008016 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8017 // operands, but not unary promotions.
8018 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008019
John McCall34376a62010-12-04 03:47:34 +00008020 // So we treat the LHS as a ignored value, and in C++ we allow the
8021 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008022 LHS = S.IgnoredValueConversions(LHS.take());
8023 if (LHS.isInvalid())
8024 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008025
8026 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008027 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8028 if (RHS.isInvalid())
8029 return QualType();
8030 if (!RHS.get()->getType()->isVoidType())
8031 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008032 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008033
John Wiegley01296292011-04-08 18:41:53 +00008034 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008035}
8036
Steve Naroff7a5af782007-07-13 16:58:59 +00008037/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8038/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008039static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8040 ExprValueKind &VK,
8041 SourceLocation OpLoc,
8042 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008043 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008044 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008045
Chris Lattner6b0cf142008-11-21 07:05:48 +00008046 QualType ResType = Op->getType();
8047 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008048
John McCall4bc41ae2010-11-18 19:01:18 +00008049 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008050 // Decrement of bool is not allowed.
8051 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008052 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008053 return QualType();
8054 }
8055 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008056 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008057 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008058 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008059 } else if (ResType->isAnyPointerType()) {
8060 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008061
Chris Lattner6b0cf142008-11-21 07:05:48 +00008062 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008063 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008064 if (S.getLangOptions().CPlusPlus) {
8065 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008066 << Op->getSourceRange();
8067 return QualType();
8068 }
8069
8070 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008071 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008072 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008073 if (S.getLangOptions().CPlusPlus) {
8074 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008075 << Op->getType() << Op->getSourceRange();
8076 return QualType();
8077 }
8078
John McCall4bc41ae2010-11-18 19:01:18 +00008079 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008080 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008081 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8082 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008083 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008084 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008085 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008086 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008087 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8088 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008089 << PointeeTy << Op->getSourceRange();
8090 return QualType();
8091 }
Eli Friedman090addd2010-01-03 00:20:48 +00008092 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008093 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008094 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008095 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008096 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008097 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008098 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008099 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8100 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008101 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8102 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008103 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008104 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008105 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008106 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008107 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008108 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008109 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008110 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008111 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008112 // In C++, a prefix increment is the same type as the operand. Otherwise
8113 // (in C or with postfix), the increment is the unqualified type of the
8114 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008115 if (isPrefix && S.getLangOptions().CPlusPlus) {
8116 VK = VK_LValue;
8117 return ResType;
8118 } else {
8119 VK = VK_RValue;
8120 return ResType.getUnqualifiedType();
8121 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008122}
8123
John Wiegley01296292011-04-08 18:41:53 +00008124ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008125 assert(E->getValueKind() == VK_LValue &&
8126 E->getObjectKind() == OK_ObjCProperty);
8127 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8128
8129 ExprValueKind VK = VK_RValue;
8130 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008131 if (const ObjCMethodDecl *GetterMethod =
8132 PRE->getImplicitPropertyGetter()) {
8133 QualType Result = GetterMethod->getResultType();
8134 VK = Expr::getValueKindForType(Result);
8135 }
8136 else {
8137 Diag(PRE->getLocation(), diag::err_getter_not_found)
8138 << PRE->getBase()->getType();
8139 }
John McCall34376a62010-12-04 03:47:34 +00008140 }
8141
8142 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8143 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008144
8145 ExprResult Result = MaybeBindToTemporary(E);
8146 if (!Result.isInvalid())
8147 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008148
8149 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008150}
8151
John Wiegley01296292011-04-08 18:41:53 +00008152void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8153 assert(LHS.get()->getValueKind() == VK_LValue &&
8154 LHS.get()->getObjectKind() == OK_ObjCProperty);
8155 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008156
John Wiegley01296292011-04-08 18:41:53 +00008157 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008158 // If using property-dot syntax notation for assignment, and there is a
8159 // setter, RHS expression is being passed to the setter argument. So,
8160 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008161 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008162 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8163 LHSTy = (*P)->getType();
8164
8165 // Otherwise, if the getter returns an l-value, just call that.
8166 } else {
John Wiegley01296292011-04-08 18:41:53 +00008167 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008168 ExprValueKind VK = Expr::getValueKindForType(Result);
8169 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008170 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8171 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008172 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008173 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008174 }
John McCall34376a62010-12-04 03:47:34 +00008175 }
8176
8177 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008178 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008179 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008180 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008181 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008182 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008183 }
8184}
8185
8186
Anders Carlsson806700f2008-02-01 07:15:58 +00008187/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008188/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008189/// where the declaration is needed for type checking. We only need to
8190/// handle cases when the expression references a function designator
8191/// or is an lvalue. Here are some examples:
8192/// - &(x) => x
8193/// - &*****f => f for f a function designator.
8194/// - &s.xx => s
8195/// - &s.zz[1].yy -> s, if zz is an array
8196/// - *(x + 1) -> x, if x is an array
8197/// - &"123"[2] -> 0
8198/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008199static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008200 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008201 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008202 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008203 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008204 // If this is an arrow operator, the address is an offset from
8205 // the base's value, so the object the base refers to is
8206 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008207 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008208 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008209 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008210 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008211 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008212 // FIXME: This code shouldn't be necessary! We should catch the implicit
8213 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008214 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8215 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8216 if (ICE->getSubExpr()->getType()->isArrayType())
8217 return getPrimaryDecl(ICE->getSubExpr());
8218 }
8219 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008220 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008221 case Stmt::UnaryOperatorClass: {
8222 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008223
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008224 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008225 case UO_Real:
8226 case UO_Imag:
8227 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008228 return getPrimaryDecl(UO->getSubExpr());
8229 default:
8230 return 0;
8231 }
8232 }
Steve Naroff47500512007-04-19 23:00:49 +00008233 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008234 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008235 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008236 // If the result of an implicit cast is an l-value, we care about
8237 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008238 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008239 default:
8240 return 0;
8241 }
8242}
8243
8244/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008245/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008246/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008247/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008248/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008249/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008250/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008251static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8252 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008253 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008254 return S.Context.DependentTy;
8255 if (OrigOp->getType() == S.Context.OverloadTy)
8256 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008257 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8258 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008259 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8260 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8261 << OrigOp->getSourceRange();
8262 return QualType();
8263 }
John McCall8d08b9b2010-08-27 09:08:28 +00008264
John McCall2979fe02011-04-12 00:42:48 +00008265 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008266
John McCall8d08b9b2010-08-27 09:08:28 +00008267 // Make sure to ignore parentheses in subsequent checks
8268 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008269
John McCall4bc41ae2010-11-18 19:01:18 +00008270 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008271 // Implement C99-only parts of addressof rules.
8272 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008273 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008274 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8275 // (assuming the deref expression is valid).
8276 return uOp->getSubExpr()->getType();
8277 }
8278 // Technically, there should be a check for array subscript
8279 // expressions here, but the result of one is always an lvalue anyway.
8280 }
John McCallf3a88602011-02-03 08:15:49 +00008281 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008282 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008283
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008284 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008285 bool sfinae = S.isSFINAEContext();
8286 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8287 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008288 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008289 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008290 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008291 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008292 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008293 } else if (lval == Expr::LV_MemberFunction) {
8294 // If it's an instance method, make a member pointer.
8295 // The expression must have exactly the form &A::foo.
8296
8297 // If the underlying expression isn't a decl ref, give up.
8298 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008299 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008300 << OrigOp->getSourceRange();
8301 return QualType();
8302 }
8303 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8304 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8305
8306 // The id-expression was parenthesized.
8307 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008308 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008309 << OrigOp->getSourceRange();
8310
8311 // The method was named without a qualifier.
8312 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008313 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008314 << op->getSourceRange();
8315 }
8316
John McCall4bc41ae2010-11-18 19:01:18 +00008317 return S.Context.getMemberPointerType(op->getType(),
8318 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008319 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008320 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008321 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008322 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008323 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008324 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008325 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008326 return QualType();
8327 }
John McCall086a4642010-11-24 05:12:34 +00008328 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008329 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008330 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008331 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008332 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008333 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008334 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008335 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008336 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008337 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008338 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008339 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008340 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008341 << "property expression" << op->getSourceRange();
8342 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008343 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008344 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008345 // with the register storage-class specifier.
8346 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008347 // in C++ it is not error to take address of a register
8348 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008349 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008350 !S.getLangOptions().CPlusPlus) {
8351 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008352 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008353 return QualType();
8354 }
John McCalld14a8642009-11-21 08:51:07 +00008355 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008356 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008357 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008358 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008359 // Could be a pointer to member, though, if there is an explicit
8360 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008361 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008362 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008363 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008364 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008365 S.Diag(OpLoc,
8366 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008367 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008368 return QualType();
8369 }
Mike Stump11289f42009-09-09 15:08:12 +00008370
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008371 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8372 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008373 return S.Context.getMemberPointerType(op->getType(),
8374 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008375 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008376 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008377 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008378 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008379 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008380
Eli Friedmance7f9002009-05-16 23:27:50 +00008381 if (lval == Expr::LV_IncompleteVoidType) {
8382 // Taking the address of a void variable is technically illegal, but we
8383 // allow it in cases which are otherwise valid.
8384 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008385 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008386 }
8387
Steve Naroff47500512007-04-19 23:00:49 +00008388 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008389 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008390 return S.Context.getObjCObjectPointerType(op->getType());
8391 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008392}
8393
Chris Lattner9156f1b2010-07-05 19:17:26 +00008394/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008395static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8396 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008397 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008398 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008399
John Wiegley01296292011-04-08 18:41:53 +00008400 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8401 if (ConvResult.isInvalid())
8402 return QualType();
8403 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008404 QualType OpTy = Op->getType();
8405 QualType Result;
8406
8407 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8408 // is an incomplete type or void. It would be possible to warn about
8409 // dereferencing a void pointer, but it's completely well-defined, and such a
8410 // warning is unlikely to catch any mistakes.
8411 if (const PointerType *PT = OpTy->getAs<PointerType>())
8412 Result = PT->getPointeeType();
8413 else if (const ObjCObjectPointerType *OPT =
8414 OpTy->getAs<ObjCObjectPointerType>())
8415 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008416 else {
John McCall3aef3d82011-04-10 19:13:55 +00008417 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008418 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008419 if (PR.take() != Op)
8420 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008421 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008422
Chris Lattner9156f1b2010-07-05 19:17:26 +00008423 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008424 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008425 << OpTy << Op->getSourceRange();
8426 return QualType();
8427 }
John McCall4bc41ae2010-11-18 19:01:18 +00008428
8429 // Dereferences are usually l-values...
8430 VK = VK_LValue;
8431
8432 // ...except that certain expressions are never l-values in C.
8433 if (!S.getLangOptions().CPlusPlus &&
8434 IsCForbiddenLValueType(S.Context, Result))
8435 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008436
8437 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008438}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008439
John McCalle3027922010-08-25 11:45:40 +00008440static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008441 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008442 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008443 switch (Kind) {
8444 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008445 case tok::periodstar: Opc = BO_PtrMemD; break;
8446 case tok::arrowstar: Opc = BO_PtrMemI; break;
8447 case tok::star: Opc = BO_Mul; break;
8448 case tok::slash: Opc = BO_Div; break;
8449 case tok::percent: Opc = BO_Rem; break;
8450 case tok::plus: Opc = BO_Add; break;
8451 case tok::minus: Opc = BO_Sub; break;
8452 case tok::lessless: Opc = BO_Shl; break;
8453 case tok::greatergreater: Opc = BO_Shr; break;
8454 case tok::lessequal: Opc = BO_LE; break;
8455 case tok::less: Opc = BO_LT; break;
8456 case tok::greaterequal: Opc = BO_GE; break;
8457 case tok::greater: Opc = BO_GT; break;
8458 case tok::exclaimequal: Opc = BO_NE; break;
8459 case tok::equalequal: Opc = BO_EQ; break;
8460 case tok::amp: Opc = BO_And; break;
8461 case tok::caret: Opc = BO_Xor; break;
8462 case tok::pipe: Opc = BO_Or; break;
8463 case tok::ampamp: Opc = BO_LAnd; break;
8464 case tok::pipepipe: Opc = BO_LOr; break;
8465 case tok::equal: Opc = BO_Assign; break;
8466 case tok::starequal: Opc = BO_MulAssign; break;
8467 case tok::slashequal: Opc = BO_DivAssign; break;
8468 case tok::percentequal: Opc = BO_RemAssign; break;
8469 case tok::plusequal: Opc = BO_AddAssign; break;
8470 case tok::minusequal: Opc = BO_SubAssign; break;
8471 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8472 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8473 case tok::ampequal: Opc = BO_AndAssign; break;
8474 case tok::caretequal: Opc = BO_XorAssign; break;
8475 case tok::pipeequal: Opc = BO_OrAssign; break;
8476 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008477 }
8478 return Opc;
8479}
8480
John McCalle3027922010-08-25 11:45:40 +00008481static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008482 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008483 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008484 switch (Kind) {
8485 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008486 case tok::plusplus: Opc = UO_PreInc; break;
8487 case tok::minusminus: Opc = UO_PreDec; break;
8488 case tok::amp: Opc = UO_AddrOf; break;
8489 case tok::star: Opc = UO_Deref; break;
8490 case tok::plus: Opc = UO_Plus; break;
8491 case tok::minus: Opc = UO_Minus; break;
8492 case tok::tilde: Opc = UO_Not; break;
8493 case tok::exclaim: Opc = UO_LNot; break;
8494 case tok::kw___real: Opc = UO_Real; break;
8495 case tok::kw___imag: Opc = UO_Imag; break;
8496 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008497 }
8498 return Opc;
8499}
8500
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008501/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8502/// This warning is only emitted for builtin assignment operations. It is also
8503/// suppressed in the event of macro expansions.
8504static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8505 SourceLocation OpLoc) {
8506 if (!S.ActiveTemplateInstantiations.empty())
8507 return;
8508 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8509 return;
8510 lhs = lhs->IgnoreParenImpCasts();
8511 rhs = rhs->IgnoreParenImpCasts();
8512 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8513 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8514 if (!LeftDeclRef || !RightDeclRef ||
8515 LeftDeclRef->getLocation().isMacroID() ||
8516 RightDeclRef->getLocation().isMacroID())
8517 return;
8518 const ValueDecl *LeftDecl =
8519 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8520 const ValueDecl *RightDecl =
8521 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8522 if (LeftDecl != RightDecl)
8523 return;
8524 if (LeftDecl->getType().isVolatileQualified())
8525 return;
8526 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8527 if (RefTy->getPointeeType().isVolatileQualified())
8528 return;
8529
8530 S.Diag(OpLoc, diag::warn_self_assignment)
8531 << LeftDeclRef->getType()
8532 << lhs->getSourceRange() << rhs->getSourceRange();
8533}
8534
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008535/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8536/// operator @p Opc at location @c TokLoc. This routine only supports
8537/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008538ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008539 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008540 Expr *lhsExpr, Expr *rhsExpr) {
8541 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008542 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008543 // The following two variables are used for compound assignment operators
8544 QualType CompLHSTy; // Type of LHS after promotions for computation
8545 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008546 ExprValueKind VK = VK_RValue;
8547 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008548
Douglas Gregor1beec452011-03-12 01:48:56 +00008549 // Check if a 'foo<int>' involved in a binary op, identifies a single
8550 // function unambiguously (i.e. an lvalue ala 13.4)
8551 // But since an assignment can trigger target based overload, exclude it in
8552 // our blind search. i.e:
8553 // template<class T> void f(); template<class T, class U> void f(U);
8554 // f<int> == 0; // resolve f<int> blindly
8555 // void (*p)(int); p = f<int>; // resolve f<int> using target
8556 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008557 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008558 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008559 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008560
John McCall3aef3d82011-04-10 19:13:55 +00008561 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008562 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008563 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008564 }
8565
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008566 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008567 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008568 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008569 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008570 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8571 VK = lhs.get()->getValueKind();
8572 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008573 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008574 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008575 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008576 break;
John McCalle3027922010-08-25 11:45:40 +00008577 case BO_PtrMemD:
8578 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008579 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008580 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008581 break;
John McCalle3027922010-08-25 11:45:40 +00008582 case BO_Mul:
8583 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008584 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008585 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008586 break;
John McCalle3027922010-08-25 11:45:40 +00008587 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008588 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8589 break;
John McCalle3027922010-08-25 11:45:40 +00008590 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008591 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8592 break;
John McCalle3027922010-08-25 11:45:40 +00008593 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008594 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8595 break;
John McCalle3027922010-08-25 11:45:40 +00008596 case BO_Shl:
8597 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008598 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008599 break;
John McCalle3027922010-08-25 11:45:40 +00008600 case BO_LE:
8601 case BO_LT:
8602 case BO_GE:
8603 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008604 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008605 break;
John McCalle3027922010-08-25 11:45:40 +00008606 case BO_EQ:
8607 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008608 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008609 break;
John McCalle3027922010-08-25 11:45:40 +00008610 case BO_And:
8611 case BO_Xor:
8612 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008613 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8614 break;
John McCalle3027922010-08-25 11:45:40 +00008615 case BO_LAnd:
8616 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008617 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008618 break;
John McCalle3027922010-08-25 11:45:40 +00008619 case BO_MulAssign:
8620 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008621 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008622 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008623 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008624 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8625 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008626 break;
John McCalle3027922010-08-25 11:45:40 +00008627 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008628 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8629 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008630 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8631 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008632 break;
John McCalle3027922010-08-25 11:45:40 +00008633 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008634 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008635 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8636 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008637 break;
John McCalle3027922010-08-25 11:45:40 +00008638 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008639 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008640 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8641 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008642 break;
John McCalle3027922010-08-25 11:45:40 +00008643 case BO_ShlAssign:
8644 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008645 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008646 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008647 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8648 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008649 break;
John McCalle3027922010-08-25 11:45:40 +00008650 case BO_AndAssign:
8651 case BO_XorAssign:
8652 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008653 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8654 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008655 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8656 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008657 break;
John McCalle3027922010-08-25 11:45:40 +00008658 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008659 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008660 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8661 VK = rhs.get()->getValueKind();
8662 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008663 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008664 break;
8665 }
John Wiegley01296292011-04-08 18:41:53 +00008666 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008667 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008668 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008669 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8670 ResultTy, VK, OK, OpLoc));
8671 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008672 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008673 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008674 }
John Wiegley01296292011-04-08 18:41:53 +00008675 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8676 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008677 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008678}
8679
Sebastian Redl44615072009-10-27 12:10:02 +00008680/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8681/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008682static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8683 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008684 const PartialDiagnostic &FirstNote,
8685 SourceRange FirstParenRange,
8686 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008687 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008688 Self.Diag(Loc, PD);
8689
8690 if (!FirstNote.getDiagID())
8691 return;
8692
8693 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8694 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8695 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008696 return;
8697 }
8698
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008699 Self.Diag(Loc, FirstNote)
8700 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008701 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008702
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008703 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008704 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008705
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008706 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8707 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8708 // We can't display the parentheses, so just dig the
8709 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008710 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008711 return;
8712 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008713
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008714 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008715 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8716 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008717}
8718
Sebastian Redl44615072009-10-27 12:10:02 +00008719/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8720/// operators are mixed in a way that suggests that the programmer forgot that
8721/// comparison operators have higher precedence. The most typical example of
8722/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008723static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008724 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008725 typedef BinaryOperator BinOp;
8726 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8727 rhsopc = static_cast<BinOp::Opcode>(-1);
8728 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008729 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008730 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008731 rhsopc = BO->getOpcode();
8732
8733 // Subs are not binary operators.
8734 if (lhsopc == -1 && rhsopc == -1)
8735 return;
8736
8737 // Bitwise operations are sometimes used as eager logical ops.
8738 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008739 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8740 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008741 return;
8742
Sebastian Redl44615072009-10-27 12:10:02 +00008743 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008744 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008745 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008746 << SourceRange(lhs->getLocStart(), OpLoc)
8747 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008748 Self.PDiag(diag::note_precedence_bitwise_silence)
8749 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008750 lhs->getSourceRange(),
8751 Self.PDiag(diag::note_precedence_bitwise_first)
8752 << BinOp::getOpcodeStr(Opc),
8753 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redl44615072009-10-27 12:10:02 +00008754 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008755 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008756 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008757 << SourceRange(OpLoc, rhs->getLocEnd())
8758 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008759 Self.PDiag(diag::note_precedence_bitwise_silence)
8760 << BinOp::getOpcodeStr(rhsopc),
8761 rhs->getSourceRange(),
Douglas Gregor89336232010-03-29 23:34:08 +00008762 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008763 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008764 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00008765}
8766
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008767/// \brief It accepts a '&&' expr that is inside a '||' one.
8768/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8769/// in parentheses.
8770static void
8771EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008772 BinaryOperator *Bop) {
8773 assert(Bop->getOpcode() == BO_LAnd);
8774 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008775 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008776 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008777 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008778 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008779 Self.PDiag(0), SourceRange());
8780}
8781
8782/// \brief Returns true if the given expression can be evaluated as a constant
8783/// 'true'.
8784static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8785 bool Res;
8786 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8787}
8788
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008789/// \brief Returns true if the given expression can be evaluated as a constant
8790/// 'false'.
8791static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8792 bool Res;
8793 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8794}
8795
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008796/// \brief Look for '&&' in the left hand of a '||' expr.
8797static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008798 Expr *OrLHS, Expr *OrRHS) {
8799 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008800 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008801 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8802 if (EvaluatesAsFalse(S, OrRHS))
8803 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008804 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8805 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8806 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8807 } else if (Bop->getOpcode() == BO_LOr) {
8808 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8809 // If it's "a || b && 1 || c" we didn't warn earlier for
8810 // "a || b && 1", but warn now.
8811 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8812 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8813 }
8814 }
8815 }
8816}
8817
8818/// \brief Look for '&&' in the right hand of a '||' expr.
8819static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008820 Expr *OrLHS, Expr *OrRHS) {
8821 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008822 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008823 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8824 if (EvaluatesAsFalse(S, OrLHS))
8825 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008826 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8827 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8828 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008829 }
8830 }
8831}
8832
Sebastian Redl43028242009-10-26 15:24:15 +00008833/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008834/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008835static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008836 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008837 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008838 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008839 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8840
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008841 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8842 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008843 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008844 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8845 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008846 }
Sebastian Redl43028242009-10-26 15:24:15 +00008847}
8848
Steve Naroff218bc2b2007-05-04 21:54:46 +00008849// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008850ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008851 tok::TokenKind Kind,
8852 Expr *lhs, Expr *rhs) {
8853 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008854 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8855 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008856
Sebastian Redl43028242009-10-26 15:24:15 +00008857 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8858 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8859
Douglas Gregor5287f092009-11-05 00:51:44 +00008860 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8861}
8862
John McCalldadc5752010-08-24 06:29:42 +00008863ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008864 BinaryOperatorKind Opc,
8865 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008866 if (getLangOptions().CPlusPlus) {
8867 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008868
John McCall622114c2010-12-06 05:26:58 +00008869 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8870 UseBuiltinOperator = false;
8871 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8872 UseBuiltinOperator = true;
8873 } else {
8874 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8875 !rhs->getType()->isOverloadableType();
8876 }
8877
8878 if (!UseBuiltinOperator) {
8879 // Find all of the overloaded operators visible from this
8880 // point. We perform both an operator-name lookup from the local
8881 // scope and an argument-dependent lookup based on the types of
8882 // the arguments.
8883 UnresolvedSet<16> Functions;
8884 OverloadedOperatorKind OverOp
8885 = BinaryOperator::getOverloadedOperator(Opc);
8886 if (S && OverOp != OO_None)
8887 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8888 Functions);
8889
8890 // Build the (potentially-overloaded, potentially-dependent)
8891 // binary operation.
8892 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8893 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008894 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008895
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008896 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008897 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008898}
8899
John McCalldadc5752010-08-24 06:29:42 +00008900ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008901 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008902 Expr *InputExpr) {
8903 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008904 ExprValueKind VK = VK_RValue;
8905 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008906 QualType resultType;
8907 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008908 case UO_PreInc:
8909 case UO_PreDec:
8910 case UO_PostInc:
8911 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008912 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008913 Opc == UO_PreInc ||
8914 Opc == UO_PostInc,
8915 Opc == UO_PreInc ||
8916 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008917 break;
John McCalle3027922010-08-25 11:45:40 +00008918 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008919 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008920 break;
John McCall31996342011-04-07 08:22:57 +00008921 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008922 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008923 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008924 Input = move(resolved);
8925 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8926 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008927 break;
John McCall31996342011-04-07 08:22:57 +00008928 }
John McCalle3027922010-08-25 11:45:40 +00008929 case UO_Plus:
8930 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008931 Input = UsualUnaryConversions(Input.take());
8932 if (Input.isInvalid()) return ExprError();
8933 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008934 if (resultType->isDependentType())
8935 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008936 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8937 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008938 break;
8939 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8940 resultType->isEnumeralType())
8941 break;
8942 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008943 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008944 resultType->isPointerType())
8945 break;
John McCall36226622010-10-12 02:09:17 +00008946 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008947 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008948 if (Input.isInvalid()) return ExprError();
8949 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008950 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008951
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008953 << resultType << Input.get()->getSourceRange());
8954
John McCalle3027922010-08-25 11:45:40 +00008955 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008956 Input = UsualUnaryConversions(Input.take());
8957 if (Input.isInvalid()) return ExprError();
8958 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008959 if (resultType->isDependentType())
8960 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008961 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8962 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8963 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008964 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008965 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008966 else if (resultType->hasIntegerRepresentation())
8967 break;
8968 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008969 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008970 if (Input.isInvalid()) return ExprError();
8971 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008972 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008973 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008974 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008975 }
Steve Naroff35d85152007-05-07 00:24:15 +00008976 break;
John Wiegley01296292011-04-08 18:41:53 +00008977
John McCalle3027922010-08-25 11:45:40 +00008978 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008979 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008980 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8981 if (Input.isInvalid()) return ExprError();
8982 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008983 if (resultType->isDependentType())
8984 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008985 if (resultType->isScalarType()) {
8986 // C99 6.5.3.3p1: ok, fallthrough;
8987 if (Context.getLangOptions().CPlusPlus) {
8988 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8989 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008990 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8991 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008992 }
John McCall36226622010-10-12 02:09:17 +00008993 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008994 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008995 if (Input.isInvalid()) return ExprError();
8996 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008997 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008998 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008999 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009000 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009001
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009002 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009003 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009004 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009005 break;
John McCalle3027922010-08-25 11:45:40 +00009006 case UO_Real:
9007 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009008 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00009009 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00009010 if (Input.isInvalid()) return ExprError();
9011 if (Input.get()->getValueKind() != VK_RValue &&
9012 Input.get()->getObjectKind() == OK_Ordinary)
9013 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00009014 break;
John McCalle3027922010-08-25 11:45:40 +00009015 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009016 resultType = Input.get()->getType();
9017 VK = Input.get()->getValueKind();
9018 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009019 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009020 }
John Wiegley01296292011-04-08 18:41:53 +00009021 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009022 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009023
John Wiegley01296292011-04-08 18:41:53 +00009024 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009025 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009026}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009027
John McCalldadc5752010-08-24 06:29:42 +00009028ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009029 UnaryOperatorKind Opc,
9030 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00009031 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00009032 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009033 // Find all of the overloaded operators visible from this
9034 // point. We perform both an operator-name lookup from the local
9035 // scope and an argument-dependent lookup based on the types of
9036 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009037 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009038 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009039 if (S && OverOp != OO_None)
9040 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9041 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009042
John McCallb268a282010-08-23 23:25:46 +00009043 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009044 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009045
John McCallb268a282010-08-23 23:25:46 +00009046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009047}
9048
Douglas Gregor5287f092009-11-05 00:51:44 +00009049// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009050ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009051 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009052 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009053}
9054
Steve Naroff66356bd2007-09-16 14:56:35 +00009055/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009056ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009057 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009058 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009059 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009060 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009061 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009062}
9063
John McCalldadc5752010-08-24 06:29:42 +00009064ExprResult
John McCallb268a282010-08-23 23:25:46 +00009065Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009066 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009067 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9068 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9069
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009070 bool isFileScope
9071 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009072 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009073 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009074
Chris Lattner366727f2007-07-24 16:58:17 +00009075 // FIXME: there are a variety of strange constraints to enforce here, for
9076 // example, it is not possible to goto into a stmt expression apparently.
9077 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009078
Chris Lattner366727f2007-07-24 16:58:17 +00009079 // If there are sub stmts in the compound stmt, take the type of the last one
9080 // as the type of the stmtexpr.
9081 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009082 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009083 if (!Compound->body_empty()) {
9084 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009085 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009086 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009087 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9088 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009089 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009090 }
John Wiegley01296292011-04-08 18:41:53 +00009091 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009092 // Do function/array conversion on the last expression, but not
9093 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009094 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9095 if (LastExpr.isInvalid())
9096 return ExprError();
9097 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009098
John Wiegley01296292011-04-08 18:41:53 +00009099 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9100 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009101 InitializedEntity::InitializeResult(LPLoc,
9102 Ty,
9103 false),
9104 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00009105 LastExpr);
9106 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009107 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009108 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009109 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009110 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009111 else
John Wiegley01296292011-04-08 18:41:53 +00009112 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009113 StmtExprMayBindToTemp = true;
9114 }
9115 }
9116 }
Chris Lattner944d3062008-07-26 19:51:01 +00009117 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009118
Eli Friedmanba961a92009-03-23 00:24:07 +00009119 // FIXME: Check that expression type is complete/non-abstract; statement
9120 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009121 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9122 if (StmtExprMayBindToTemp)
9123 return MaybeBindToTemporary(ResStmtExpr);
9124 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009125}
Steve Naroff78864672007-08-01 22:05:33 +00009126
John McCalldadc5752010-08-24 06:29:42 +00009127ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009128 TypeSourceInfo *TInfo,
9129 OffsetOfComponent *CompPtr,
9130 unsigned NumComponents,
9131 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009132 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009133 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009134 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009135
Chris Lattnerf17bd422007-08-30 17:45:32 +00009136 // We must have at least one component that refers to the type, and the first
9137 // one is known to be a field designator. Verify that the ArgTy represents
9138 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009139 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009140 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9141 << ArgTy << TypeRange);
9142
9143 // Type must be complete per C99 7.17p3 because a declaring a variable
9144 // with an incomplete type would be ill-formed.
9145 if (!Dependent
9146 && RequireCompleteType(BuiltinLoc, ArgTy,
9147 PDiag(diag::err_offsetof_incomplete_type)
9148 << TypeRange))
9149 return ExprError();
9150
Chris Lattner78502cf2007-08-31 21:49:13 +00009151 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9152 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009153 // FIXME: This diagnostic isn't actually visible because the location is in
9154 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009155 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009156 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9157 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009158
9159 bool DidWarnAboutNonPOD = false;
9160 QualType CurrentType = ArgTy;
9161 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9162 llvm::SmallVector<OffsetOfNode, 4> Comps;
9163 llvm::SmallVector<Expr*, 4> Exprs;
9164 for (unsigned i = 0; i != NumComponents; ++i) {
9165 const OffsetOfComponent &OC = CompPtr[i];
9166 if (OC.isBrackets) {
9167 // Offset of an array sub-field. TODO: Should we allow vector elements?
9168 if (!CurrentType->isDependentType()) {
9169 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9170 if(!AT)
9171 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9172 << CurrentType);
9173 CurrentType = AT->getElementType();
9174 } else
9175 CurrentType = Context.DependentTy;
9176
9177 // The expression must be an integral expression.
9178 // FIXME: An integral constant expression?
9179 Expr *Idx = static_cast<Expr*>(OC.U.E);
9180 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9181 !Idx->getType()->isIntegerType())
9182 return ExprError(Diag(Idx->getLocStart(),
9183 diag::err_typecheck_subscript_not_integer)
9184 << Idx->getSourceRange());
9185
9186 // Record this array index.
9187 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9188 Exprs.push_back(Idx);
9189 continue;
9190 }
9191
9192 // Offset of a field.
9193 if (CurrentType->isDependentType()) {
9194 // We have the offset of a field, but we can't look into the dependent
9195 // type. Just record the identifier of the field.
9196 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9197 CurrentType = Context.DependentTy;
9198 continue;
9199 }
9200
9201 // We need to have a complete type to look into.
9202 if (RequireCompleteType(OC.LocStart, CurrentType,
9203 diag::err_offsetof_incomplete_type))
9204 return ExprError();
9205
9206 // Look for the designated field.
9207 const RecordType *RC = CurrentType->getAs<RecordType>();
9208 if (!RC)
9209 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9210 << CurrentType);
9211 RecordDecl *RD = RC->getDecl();
9212
9213 // C++ [lib.support.types]p5:
9214 // The macro offsetof accepts a restricted set of type arguments in this
9215 // International Standard. type shall be a POD structure or a POD union
9216 // (clause 9).
9217 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9218 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009219 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009220 PDiag(diag::warn_offsetof_non_pod_type)
9221 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9222 << CurrentType))
9223 DidWarnAboutNonPOD = true;
9224 }
9225
9226 // Look for the field.
9227 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9228 LookupQualifiedName(R, RD);
9229 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009230 IndirectFieldDecl *IndirectMemberDecl = 0;
9231 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009232 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009233 MemberDecl = IndirectMemberDecl->getAnonField();
9234 }
9235
Douglas Gregor882211c2010-04-28 22:16:22 +00009236 if (!MemberDecl)
9237 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9238 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9239 OC.LocEnd));
9240
Douglas Gregor10982ea2010-04-28 22:36:06 +00009241 // C99 7.17p3:
9242 // (If the specified member is a bit-field, the behavior is undefined.)
9243 //
9244 // We diagnose this as an error.
9245 if (MemberDecl->getBitWidth()) {
9246 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9247 << MemberDecl->getDeclName()
9248 << SourceRange(BuiltinLoc, RParenLoc);
9249 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9250 return ExprError();
9251 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009252
9253 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009254 if (IndirectMemberDecl)
9255 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009256
Douglas Gregord1702062010-04-29 00:18:15 +00009257 // If the member was found in a base class, introduce OffsetOfNodes for
9258 // the base class indirections.
9259 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9260 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009261 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009262 CXXBasePath &Path = Paths.front();
9263 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9264 B != BEnd; ++B)
9265 Comps.push_back(OffsetOfNode(B->Base));
9266 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009267
Francois Pichet783dd6e2010-11-21 06:08:52 +00009268 if (IndirectMemberDecl) {
9269 for (IndirectFieldDecl::chain_iterator FI =
9270 IndirectMemberDecl->chain_begin(),
9271 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9272 assert(isa<FieldDecl>(*FI));
9273 Comps.push_back(OffsetOfNode(OC.LocStart,
9274 cast<FieldDecl>(*FI), OC.LocEnd));
9275 }
9276 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009277 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009278
Douglas Gregor882211c2010-04-28 22:16:22 +00009279 CurrentType = MemberDecl->getType().getNonReferenceType();
9280 }
9281
9282 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9283 TInfo, Comps.data(), Comps.size(),
9284 Exprs.data(), Exprs.size(), RParenLoc));
9285}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009286
John McCalldadc5752010-08-24 06:29:42 +00009287ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009288 SourceLocation BuiltinLoc,
9289 SourceLocation TypeLoc,
9290 ParsedType argty,
9291 OffsetOfComponent *CompPtr,
9292 unsigned NumComponents,
9293 SourceLocation RPLoc) {
9294
Douglas Gregor882211c2010-04-28 22:16:22 +00009295 TypeSourceInfo *ArgTInfo;
9296 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9297 if (ArgTy.isNull())
9298 return ExprError();
9299
Eli Friedman06dcfd92010-08-05 10:15:45 +00009300 if (!ArgTInfo)
9301 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9302
9303 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9304 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009305}
9306
9307
John McCalldadc5752010-08-24 06:29:42 +00009308ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009309 Expr *CondExpr,
9310 Expr *LHSExpr, Expr *RHSExpr,
9311 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009312 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9313
John McCall7decc9e2010-11-18 06:31:45 +00009314 ExprValueKind VK = VK_RValue;
9315 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009316 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009317 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009318 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009319 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009320 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009321 } else {
9322 // The conditional expression is required to be a constant expression.
9323 llvm::APSInt condEval(32);
9324 SourceLocation ExpLoc;
9325 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009326 return ExprError(Diag(ExpLoc,
9327 diag::err_typecheck_choose_expr_requires_constant)
9328 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009329
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009330 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009331 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9332
9333 resType = ActiveExpr->getType();
9334 ValueDependent = ActiveExpr->isValueDependent();
9335 VK = ActiveExpr->getValueKind();
9336 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009337 }
9338
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009339 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009340 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009341 resType->isDependentType(),
9342 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009343}
9344
Steve Naroffc540d662008-09-03 18:15:37 +00009345//===----------------------------------------------------------------------===//
9346// Clang Extensions.
9347//===----------------------------------------------------------------------===//
9348
9349/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009350void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009351 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9352 PushBlockScope(BlockScope, Block);
9353 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009354 if (BlockScope)
9355 PushDeclContext(BlockScope, Block);
9356 else
9357 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009358}
9359
Mike Stump82f071f2009-02-04 22:31:32 +00009360void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009361 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009362 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009363 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009364
John McCall8cb7bdf2010-06-04 23:28:52 +00009365 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009366 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009367
John McCall3882ace2011-01-05 12:14:39 +00009368 // GetTypeForDeclarator always produces a function type for a block
9369 // literal signature. Furthermore, it is always a FunctionProtoType
9370 // unless the function was written with a typedef.
9371 assert(T->isFunctionType() &&
9372 "GetTypeForDeclarator made a non-function block signature");
9373
9374 // Look for an explicit signature in that function type.
9375 FunctionProtoTypeLoc ExplicitSignature;
9376
9377 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9378 if (isa<FunctionProtoTypeLoc>(tmp)) {
9379 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9380
9381 // Check whether that explicit signature was synthesized by
9382 // GetTypeForDeclarator. If so, don't save that as part of the
9383 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009384 if (ExplicitSignature.getLocalRangeBegin() ==
9385 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009386 // This would be much cheaper if we stored TypeLocs instead of
9387 // TypeSourceInfos.
9388 TypeLoc Result = ExplicitSignature.getResultLoc();
9389 unsigned Size = Result.getFullDataSize();
9390 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9391 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9392
9393 ExplicitSignature = FunctionProtoTypeLoc();
9394 }
John McCalla3ccba02010-06-04 11:21:44 +00009395 }
Mike Stump11289f42009-09-09 15:08:12 +00009396
John McCall3882ace2011-01-05 12:14:39 +00009397 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9398 CurBlock->FunctionType = T;
9399
9400 const FunctionType *Fn = T->getAs<FunctionType>();
9401 QualType RetTy = Fn->getResultType();
9402 bool isVariadic =
9403 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9404
John McCall8e346702010-06-04 19:02:56 +00009405 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009406
John McCalla3ccba02010-06-04 11:21:44 +00009407 // Don't allow returning a objc interface by value.
9408 if (RetTy->isObjCObjectType()) {
9409 Diag(ParamInfo.getSourceRange().getBegin(),
9410 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9411 return;
9412 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009413
John McCalla3ccba02010-06-04 11:21:44 +00009414 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009415 // return type. TODO: what should we do with declarators like:
9416 // ^ * { ... }
9417 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009418 if (RetTy != Context.DependentTy)
9419 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009420
John McCalla3ccba02010-06-04 11:21:44 +00009421 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009422 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009423 if (ExplicitSignature) {
9424 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9425 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009426 if (Param->getIdentifier() == 0 &&
9427 !Param->isImplicit() &&
9428 !Param->isInvalidDecl() &&
9429 !getLangOptions().CPlusPlus)
9430 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009431 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009432 }
John McCalla3ccba02010-06-04 11:21:44 +00009433
9434 // Fake up parameter variables if we have a typedef, like
9435 // ^ fntype { ... }
9436 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9437 for (FunctionProtoType::arg_type_iterator
9438 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9439 ParmVarDecl *Param =
9440 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9441 ParamInfo.getSourceRange().getBegin(),
9442 *I);
John McCall8e346702010-06-04 19:02:56 +00009443 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009444 }
Steve Naroffc540d662008-09-03 18:15:37 +00009445 }
John McCalla3ccba02010-06-04 11:21:44 +00009446
John McCall8e346702010-06-04 19:02:56 +00009447 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009448 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009449 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009450 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9451 CurBlock->TheDecl->param_end(),
9452 /*CheckParameterNames=*/false);
9453 }
9454
John McCalla3ccba02010-06-04 11:21:44 +00009455 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009456 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009457
John McCall8e346702010-06-04 19:02:56 +00009458 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009459 Diag(ParamInfo.getAttributes()->getLoc(),
9460 diag::warn_attribute_sentinel_not_variadic) << 1;
9461 // FIXME: remove the attribute.
9462 }
9463
9464 // Put the parameter variables in scope. We can bail out immediately
9465 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009466 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009467 return;
9468
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009469 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009470 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9471 (*AI)->setOwningFunction(CurBlock->TheDecl);
9472
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009473 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009474 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009475 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009476
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009477 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009478 }
John McCallf7b2fb52010-01-22 00:28:27 +00009479 }
Steve Naroffc540d662008-09-03 18:15:37 +00009480}
9481
9482/// ActOnBlockError - If there is an error parsing a block, this callback
9483/// is invoked to pop the information about the block from the action impl.
9484void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009485 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009486 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009487 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009488}
9489
9490/// ActOnBlockStmtExpr - This is called when the body of a block statement
9491/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009492ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009493 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009494 // If blocks are disabled, emit an error.
9495 if (!LangOpts.Blocks)
9496 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009497
Douglas Gregor9a28e842010-03-01 23:15:13 +00009498 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009499
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009500 PopDeclContext();
9501
Steve Naroffc540d662008-09-03 18:15:37 +00009502 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009503 if (!BSI->ReturnType.isNull())
9504 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009505
Mike Stump3bf1ab42009-07-28 22:04:01 +00009506 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009507 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009508
John McCallc63de662011-02-02 13:00:07 +00009509 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009510 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9511 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009512
John McCall8e346702010-06-04 19:02:56 +00009513 // If the user wrote a function type in some form, try to use that.
9514 if (!BSI->FunctionType.isNull()) {
9515 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9516
9517 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9518 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9519
9520 // Turn protoless block types into nullary block types.
9521 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009522 FunctionProtoType::ExtProtoInfo EPI;
9523 EPI.ExtInfo = Ext;
9524 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009525
9526 // Otherwise, if we don't need to change anything about the function type,
9527 // preserve its sugar structure.
9528 } else if (FTy->getResultType() == RetTy &&
9529 (!NoReturn || FTy->getNoReturnAttr())) {
9530 BlockTy = BSI->FunctionType;
9531
9532 // Otherwise, make the minimal modifications to the function type.
9533 } else {
9534 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009535 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9536 EPI.TypeQuals = 0; // FIXME: silently?
9537 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009538 BlockTy = Context.getFunctionType(RetTy,
9539 FPT->arg_type_begin(),
9540 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009541 EPI);
John McCall8e346702010-06-04 19:02:56 +00009542 }
9543
9544 // If we don't have a function type, just build one from nothing.
9545 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009546 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009547 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009548 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009549 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009550
John McCall8e346702010-06-04 19:02:56 +00009551 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9552 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009553 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009554
Chris Lattner45542ea2009-04-19 05:28:12 +00009555 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009556 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009557 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009558
Chris Lattner60f84492011-02-17 23:58:47 +00009559 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009560
John McCallc63de662011-02-02 13:00:07 +00009561 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009562
Ted Kremenek1767a272011-02-23 01:51:48 +00009563 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9564 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009565 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009566}
9567
John McCalldadc5752010-08-24 06:29:42 +00009568ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009569 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009570 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009571 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009572 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009573 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009574}
9575
John McCalldadc5752010-08-24 06:29:42 +00009576ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009577 Expr *E, TypeSourceInfo *TInfo,
9578 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009579 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009580
Eli Friedman121ba0c2008-08-09 23:32:40 +00009581 // Get the va_list type
9582 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009583 if (VaListType->isArrayType()) {
9584 // Deal with implicit array decay; for example, on x86-64,
9585 // va_list is an array, but it's supposed to decay to
9586 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009587 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009588 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009589 ExprResult Result = UsualUnaryConversions(E);
9590 if (Result.isInvalid())
9591 return ExprError();
9592 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009593 } else {
9594 // Otherwise, the va_list argument must be an l-value because
9595 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009596 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009597 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009598 return ExprError();
9599 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009600
Douglas Gregorad3150c2009-05-19 23:10:31 +00009601 if (!E->isTypeDependent() &&
9602 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009603 return ExprError(Diag(E->getLocStart(),
9604 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009605 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009606 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009607
Eli Friedmanba961a92009-03-23 00:24:07 +00009608 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009609 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009610
Abramo Bagnara27db2392010-08-10 10:06:15 +00009611 QualType T = TInfo->getType().getNonLValueExprType(Context);
9612 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009613}
9614
John McCalldadc5752010-08-24 06:29:42 +00009615ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009616 // The type of __null will be int or long, depending on the size of
9617 // pointers on the target.
9618 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009619 unsigned pw = Context.Target.getPointerWidth(0);
9620 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009621 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009622 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009623 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009624 else if (pw == Context.Target.getLongLongWidth())
9625 Ty = Context.LongLongTy;
9626 else {
9627 assert(!"I don't know size of pointer!");
9628 Ty = Context.IntTy;
9629 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009630
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009631 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009632}
9633
Alexis Huntc46382e2010-04-28 23:02:27 +00009634static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009635 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009636 if (!SemaRef.getLangOptions().ObjC1)
9637 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009638
Anders Carlssonace5d072009-11-10 04:46:30 +00009639 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9640 if (!PT)
9641 return;
9642
9643 // Check if the destination is of type 'id'.
9644 if (!PT->isObjCIdType()) {
9645 // Check if the destination is the 'NSString' interface.
9646 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9647 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9648 return;
9649 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009650
Anders Carlssonace5d072009-11-10 04:46:30 +00009651 // Strip off any parens and casts.
9652 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9653 if (!SL || SL->isWide())
9654 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009655
Douglas Gregora771f462010-03-31 17:46:05 +00009656 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009657}
9658
Chris Lattner9bad62c2008-01-04 18:04:52 +00009659bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9660 SourceLocation Loc,
9661 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009662 Expr *SrcExpr, AssignmentAction Action,
9663 bool *Complained) {
9664 if (Complained)
9665 *Complained = false;
9666
Chris Lattner9bad62c2008-01-04 18:04:52 +00009667 // Decode the result (notice that AST's are still created for extensions).
9668 bool isInvalid = false;
9669 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009670 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009671
Chris Lattner9bad62c2008-01-04 18:04:52 +00009672 switch (ConvTy) {
9673 default: assert(0 && "Unknown conversion type");
9674 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009675 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009676 DiagKind = diag::ext_typecheck_convert_pointer_int;
9677 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009678 case IntToPointer:
9679 DiagKind = diag::ext_typecheck_convert_int_pointer;
9680 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009681 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009682 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009683 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9684 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009685 case IncompatiblePointerSign:
9686 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9687 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009688 case FunctionVoidPointer:
9689 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9690 break;
John McCall4fff8f62011-02-01 00:10:29 +00009691 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009692 // Perform array-to-pointer decay if necessary.
9693 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9694
John McCall4fff8f62011-02-01 00:10:29 +00009695 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9696 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9697 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9698 DiagKind = diag::err_typecheck_incompatible_address_space;
9699 break;
9700 }
9701
9702 llvm_unreachable("unknown error case for discarding qualifiers!");
9703 // fallthrough
9704 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009705 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009706 // If the qualifiers lost were because we were applying the
9707 // (deprecated) C++ conversion from a string literal to a char*
9708 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9709 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009710 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009711 // bit of refactoring (so that the second argument is an
9712 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009713 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009714 // C++ semantics.
9715 if (getLangOptions().CPlusPlus &&
9716 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9717 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009718 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9719 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009720 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009721 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009722 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009723 case IntToBlockPointer:
9724 DiagKind = diag::err_int_to_block_pointer;
9725 break;
9726 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009727 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009728 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009729 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009730 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009731 // it can give a more specific diagnostic.
9732 DiagKind = diag::warn_incompatible_qualified_id;
9733 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009734 case IncompatibleVectors:
9735 DiagKind = diag::warn_incompatible_vectors;
9736 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009737 case Incompatible:
9738 DiagKind = diag::err_typecheck_convert_incompatible;
9739 isInvalid = true;
9740 break;
9741 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009742
Douglas Gregorc68e1402010-04-09 00:35:39 +00009743 QualType FirstType, SecondType;
9744 switch (Action) {
9745 case AA_Assigning:
9746 case AA_Initializing:
9747 // The destination type comes first.
9748 FirstType = DstType;
9749 SecondType = SrcType;
9750 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009751
Douglas Gregorc68e1402010-04-09 00:35:39 +00009752 case AA_Returning:
9753 case AA_Passing:
9754 case AA_Converting:
9755 case AA_Sending:
9756 case AA_Casting:
9757 // The source type comes first.
9758 FirstType = SrcType;
9759 SecondType = DstType;
9760 break;
9761 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009762
Douglas Gregorc68e1402010-04-09 00:35:39 +00009763 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009764 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009765 if (Complained)
9766 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009767 return isInvalid;
9768}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009769
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009770bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009771 llvm::APSInt ICEResult;
9772 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9773 if (Result)
9774 *Result = ICEResult;
9775 return false;
9776 }
9777
Anders Carlssone54e8a12008-11-30 19:50:32 +00009778 Expr::EvalResult EvalResult;
9779
Mike Stump4e1f26a2009-02-19 03:04:26 +00009780 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009781 EvalResult.HasSideEffects) {
9782 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9783
9784 if (EvalResult.Diag) {
9785 // We only show the note if it's not the usual "invalid subexpression"
9786 // or if it's actually in a subexpression.
9787 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9788 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9789 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9790 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009791
Anders Carlssone54e8a12008-11-30 19:50:32 +00009792 return true;
9793 }
9794
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009795 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9796 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009797
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009798 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009799 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9800 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009801 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009802
Anders Carlssone54e8a12008-11-30 19:50:32 +00009803 if (Result)
9804 *Result = EvalResult.Val.getInt();
9805 return false;
9806}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009807
Douglas Gregorff790f12009-11-26 00:44:06 +00009808void
Mike Stump11289f42009-09-09 15:08:12 +00009809Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009810 ExprEvalContexts.push_back(
9811 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009812}
9813
Mike Stump11289f42009-09-09 15:08:12 +00009814void
Douglas Gregorff790f12009-11-26 00:44:06 +00009815Sema::PopExpressionEvaluationContext() {
9816 // Pop the current expression evaluation context off the stack.
9817 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9818 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009819
Douglas Gregorfab31f42009-12-12 07:57:52 +00009820 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9821 if (Rec.PotentiallyReferenced) {
9822 // Mark any remaining declarations in the current position of the stack
9823 // as "referenced". If they were not meant to be referenced, semantic
9824 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009825 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009826 I = Rec.PotentiallyReferenced->begin(),
9827 IEnd = Rec.PotentiallyReferenced->end();
9828 I != IEnd; ++I)
9829 MarkDeclarationReferenced(I->first, I->second);
9830 }
9831
9832 if (Rec.PotentiallyDiagnosed) {
9833 // Emit any pending diagnostics.
9834 for (PotentiallyEmittedDiagnostics::iterator
9835 I = Rec.PotentiallyDiagnosed->begin(),
9836 IEnd = Rec.PotentiallyDiagnosed->end();
9837 I != IEnd; ++I)
9838 Diag(I->first, I->second);
9839 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009840 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009841
9842 // When are coming out of an unevaluated context, clear out any
9843 // temporaries that we may have created as part of the evaluation of
9844 // the expression in that context: they aren't relevant because they
9845 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009846 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009847 ExprTemporaries.size() > Rec.NumTemporaries)
9848 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9849 ExprTemporaries.end());
9850
9851 // Destroy the popped expression evaluation record.
9852 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009853}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009854
9855/// \brief Note that the given declaration was referenced in the source code.
9856///
9857/// This routine should be invoke whenever a given declaration is referenced
9858/// in the source code, and where that reference occurred. If this declaration
9859/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9860/// C99 6.9p3), then the declaration will be marked as used.
9861///
9862/// \param Loc the location where the declaration was referenced.
9863///
9864/// \param D the declaration that has been referenced by the source code.
9865void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9866 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009867
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009868 D->setReferenced();
9869
Douglas Gregorebada0772010-06-17 23:14:26 +00009870 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009871 return;
Mike Stump11289f42009-09-09 15:08:12 +00009872
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009873 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9874 // template or not. The reason for this is that unevaluated expressions
9875 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9876 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009877 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009878 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009879 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009880 return;
9881 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009882
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009883 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9884 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009885
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009886 // Do not mark anything as "used" within a dependent context; wait for
9887 // an instantiation.
9888 if (CurContext->isDependentContext())
9889 return;
Mike Stump11289f42009-09-09 15:08:12 +00009890
Douglas Gregorff790f12009-11-26 00:44:06 +00009891 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009892 case Unevaluated:
9893 // We are in an expression that is not potentially evaluated; do nothing.
9894 return;
Mike Stump11289f42009-09-09 15:08:12 +00009895
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009896 case PotentiallyEvaluated:
9897 // We are in a potentially-evaluated expression, so this declaration is
9898 // "used"; handle this below.
9899 break;
Mike Stump11289f42009-09-09 15:08:12 +00009900
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009901 case PotentiallyPotentiallyEvaluated:
9902 // We are in an expression that may be potentially evaluated; queue this
9903 // declaration reference until we know whether the expression is
9904 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009905 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009906 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009907
9908 case PotentiallyEvaluatedIfUsed:
9909 // Referenced declarations will only be used if the construct in the
9910 // containing expression is used.
9911 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009912 }
Mike Stump11289f42009-09-09 15:08:12 +00009913
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009914 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009915 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009916 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009917 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009918 if (Constructor->getParent()->hasTrivialConstructor())
9919 return;
9920 if (!Constructor->isUsed(false))
9921 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009922 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009923 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009924 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009925 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9926 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009927
Douglas Gregor88d292c2010-05-13 16:44:06 +00009928 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009929 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009930 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009931 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009932 if (Destructor->isVirtual())
9933 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009934 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9935 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9936 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009937 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009938 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009939 } else if (MethodDecl->isVirtual())
9940 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009941 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009942 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009943 // Recursive functions should be marked when used from another function.
9944 if (CurContext == Function) return;
9945
Mike Stump11289f42009-09-09 15:08:12 +00009946 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009947 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009948 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009949 bool AlreadyInstantiated = false;
9950 if (FunctionTemplateSpecializationInfo *SpecInfo
9951 = Function->getTemplateSpecializationInfo()) {
9952 if (SpecInfo->getPointOfInstantiation().isInvalid())
9953 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009954 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009955 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009956 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009957 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009958 = Function->getMemberSpecializationInfo()) {
9959 if (MSInfo->getPointOfInstantiation().isInvalid())
9960 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009961 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009962 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009963 AlreadyInstantiated = true;
9964 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009965
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009966 if (!AlreadyInstantiated) {
9967 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9968 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9969 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9970 Loc));
9971 else
Chandler Carruth54080172010-08-25 08:44:16 +00009972 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009973 }
John McCall83779672011-02-19 02:53:41 +00009974 } else {
9975 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009976 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9977 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009978 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009979 MarkDeclarationReferenced(Loc, *i);
9980 }
John McCall83779672011-02-19 02:53:41 +00009981 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009982
John McCall83779672011-02-19 02:53:41 +00009983 // Keep track of used but undefined functions.
9984 if (!Function->isPure() && !Function->hasBody() &&
9985 Function->getLinkage() != ExternalLinkage) {
9986 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9987 if (old.isInvalid()) old = Loc;
9988 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009989
John McCall83779672011-02-19 02:53:41 +00009990 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009991 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009992 }
Mike Stump11289f42009-09-09 15:08:12 +00009993
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009994 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009995 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009996 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009997 Var->getInstantiatedFromStaticDataMember()) {
9998 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9999 assert(MSInfo && "Missing member specialization information?");
10000 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10001 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10002 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +000010003 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +000010004 }
10005 }
Mike Stump11289f42009-09-09 15:08:12 +000010006
John McCall15dd4042011-02-21 19:25:48 +000010007 // Keep track of used but undefined variables. We make a hole in
10008 // the warning for static const data members with in-line
10009 // initializers.
John McCall83779672011-02-19 02:53:41 +000010010 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +000010011 && Var->getLinkage() != ExternalLinkage
10012 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +000010013 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10014 if (old.isInvalid()) old = Loc;
10015 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010016
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010017 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010018 return;
Sam Weinigbae69142009-09-11 03:29:30 +000010019 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010020}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010021
Douglas Gregor5597ab42010-05-07 23:12:07 +000010022namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010023 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010024 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010025 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010026 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10027 Sema &S;
10028 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010029
Douglas Gregor5597ab42010-05-07 23:12:07 +000010030 public:
10031 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010032
Douglas Gregor5597ab42010-05-07 23:12:07 +000010033 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010034
10035 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10036 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010037 };
10038}
10039
Chandler Carruthaf80f662010-06-09 08:17:30 +000010040bool MarkReferencedDecls::TraverseTemplateArgument(
10041 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010042 if (Arg.getKind() == TemplateArgument::Declaration) {
10043 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10044 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010045
10046 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010047}
10048
Chandler Carruthaf80f662010-06-09 08:17:30 +000010049bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010050 if (ClassTemplateSpecializationDecl *Spec
10051 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10052 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010053 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010054 }
10055
Chandler Carruthc65667c2010-06-10 10:31:57 +000010056 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010057}
10058
10059void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10060 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010061 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010062}
10063
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010064namespace {
10065 /// \brief Helper class that marks all of the declarations referenced by
10066 /// potentially-evaluated subexpressions as "referenced".
10067 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10068 Sema &S;
10069
10070 public:
10071 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10072
10073 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10074
10075 void VisitDeclRefExpr(DeclRefExpr *E) {
10076 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10077 }
10078
10079 void VisitMemberExpr(MemberExpr *E) {
10080 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010081 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010082 }
10083
10084 void VisitCXXNewExpr(CXXNewExpr *E) {
10085 if (E->getConstructor())
10086 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10087 if (E->getOperatorNew())
10088 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10089 if (E->getOperatorDelete())
10090 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010091 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010092 }
10093
10094 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10095 if (E->getOperatorDelete())
10096 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010097 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10098 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10099 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10100 S.MarkDeclarationReferenced(E->getLocStart(),
10101 S.LookupDestructor(Record));
10102 }
10103
Douglas Gregor32b3de52010-09-11 23:32:50 +000010104 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010105 }
10106
10107 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10108 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010109 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010110 }
10111
10112 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10113 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10114 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010115
10116 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10117 Visit(E->getExpr());
10118 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010119 };
10120}
10121
10122/// \brief Mark any declarations that appear within this expression or any
10123/// potentially-evaluated subexpressions as "referenced".
10124void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10125 EvaluatedExprMarker(*this).Visit(E);
10126}
10127
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010128/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10129/// of the program being compiled.
10130///
10131/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010132/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010133/// possibility that the code will actually be executable. Code in sizeof()
10134/// expressions, code used only during overload resolution, etc., are not
10135/// potentially evaluated. This routine will suppress such diagnostics or,
10136/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010137/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010138/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010139///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010140/// This routine should be used for all diagnostics that describe the run-time
10141/// behavior of a program, such as passing a non-POD value through an ellipsis.
10142/// Failure to do so will likely result in spurious diagnostics or failures
10143/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010144bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010145 const PartialDiagnostic &PD) {
10146 switch (ExprEvalContexts.back().Context ) {
10147 case Unevaluated:
10148 // The argument will never be evaluated, so don't complain.
10149 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010150
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010151 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010152 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010153 if (stmt && getCurFunctionOrMethodDecl()) {
10154 FunctionScopes.back()->PossiblyUnreachableDiags.
10155 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10156 }
10157 else
10158 Diag(Loc, PD);
10159
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010160 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010161
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010162 case PotentiallyPotentiallyEvaluated:
10163 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10164 break;
10165 }
10166
10167 return false;
10168}
10169
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010170bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10171 CallExpr *CE, FunctionDecl *FD) {
10172 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10173 return false;
10174
10175 PartialDiagnostic Note =
10176 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10177 << FD->getDeclName() : PDiag();
10178 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010179
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010180 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010181 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010182 PDiag(diag::err_call_function_incomplete_return)
10183 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010184 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010185 << CE->getSourceRange(),
10186 std::make_pair(NoteLoc, Note)))
10187 return true;
10188
10189 return false;
10190}
10191
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010192// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010193// will prevent this condition from triggering, which is what we want.
10194void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10195 SourceLocation Loc;
10196
John McCall0506e4a2009-11-11 02:41:58 +000010197 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010198 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010199
John McCalld5707ab2009-10-12 21:59:07 +000010200 if (isa<BinaryOperator>(E)) {
10201 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010202 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010203 return;
10204
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010205 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10206
John McCallb0e419e2009-11-12 00:06:05 +000010207 // Greylist some idioms by putting them into a warning subcategory.
10208 if (ObjCMessageExpr *ME
10209 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10210 Selector Sel = ME->getSelector();
10211
John McCallb0e419e2009-11-12 00:06:05 +000010212 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010213 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010214 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10215
10216 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010217 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010218 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10219 }
John McCall0506e4a2009-11-11 02:41:58 +000010220
John McCalld5707ab2009-10-12 21:59:07 +000010221 Loc = Op->getOperatorLoc();
10222 } else if (isa<CXXOperatorCallExpr>(E)) {
10223 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010224 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010225 return;
10226
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010227 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010228 Loc = Op->getOperatorLoc();
10229 } else {
10230 // Not an assignment.
10231 return;
10232 }
10233
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010234 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010235
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010236 SourceLocation Open = E->getSourceRange().getBegin();
10237 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10238 Diag(Loc, diag::note_condition_assign_silence)
10239 << FixItHint::CreateInsertion(Open, "(")
10240 << FixItHint::CreateInsertion(Close, ")");
10241
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010242 if (IsOrAssign)
10243 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10244 << FixItHint::CreateReplacement(Loc, "!=");
10245 else
10246 Diag(Loc, diag::note_condition_assign_to_comparison)
10247 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010248}
10249
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010250/// \brief Redundant parentheses over an equality comparison can indicate
10251/// that the user intended an assignment used as condition.
10252void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010253 // Don't warn if the parens came from a macro.
10254 SourceLocation parenLoc = parenE->getLocStart();
10255 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10256 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010257 // Don't warn for dependent expressions.
10258 if (parenE->isTypeDependent())
10259 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010260
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010261 Expr *E = parenE->IgnoreParens();
10262
10263 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010264 if (opE->getOpcode() == BO_EQ &&
10265 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10266 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010267 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010268
Ted Kremenekae022092011-02-02 02:20:30 +000010269 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010270 Diag(Loc, diag::note_equality_comparison_silence)
10271 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10272 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010273 Diag(Loc, diag::note_equality_comparison_to_assign)
10274 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010275 }
10276}
10277
John Wiegley01296292011-04-08 18:41:53 +000010278ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010279 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010280 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10281 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010282
John McCall0009fcc2011-04-26 20:42:42 +000010283 ExprResult result = CheckPlaceholderExpr(E);
10284 if (result.isInvalid()) return ExprError();
10285 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010286
John McCall0009fcc2011-04-26 20:42:42 +000010287 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010288 if (getLangOptions().CPlusPlus)
10289 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10290
John Wiegley01296292011-04-08 18:41:53 +000010291 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10292 if (ERes.isInvalid())
10293 return ExprError();
10294 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010295
10296 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010297 if (!T->isScalarType()) { // C99 6.8.4.1p1
10298 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10299 << T << E->getSourceRange();
10300 return ExprError();
10301 }
John McCalld5707ab2009-10-12 21:59:07 +000010302 }
10303
John Wiegley01296292011-04-08 18:41:53 +000010304 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010305}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010306
John McCalldadc5752010-08-24 06:29:42 +000010307ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10308 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010309 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010310 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010311
10312 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010313}
John McCall36e7fe32010-10-12 00:20:44 +000010314
John McCall31996342011-04-07 08:22:57 +000010315namespace {
John McCall2979fe02011-04-12 00:42:48 +000010316 /// A visitor for rebuilding a call to an __unknown_any expression
10317 /// to have an appropriate type.
10318 struct RebuildUnknownAnyFunction
10319 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10320
10321 Sema &S;
10322
10323 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10324
10325 ExprResult VisitStmt(Stmt *S) {
10326 llvm_unreachable("unexpected statement!");
10327 return ExprError();
10328 }
10329
10330 ExprResult VisitExpr(Expr *expr) {
10331 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10332 << expr->getSourceRange();
10333 return ExprError();
10334 }
10335
10336 /// Rebuild an expression which simply semantically wraps another
10337 /// expression which it shares the type and value kind of.
10338 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10339 ExprResult subResult = Visit(expr->getSubExpr());
10340 if (subResult.isInvalid()) return ExprError();
10341
10342 Expr *subExpr = subResult.take();
10343 expr->setSubExpr(subExpr);
10344 expr->setType(subExpr->getType());
10345 expr->setValueKind(subExpr->getValueKind());
10346 assert(expr->getObjectKind() == OK_Ordinary);
10347 return expr;
10348 }
10349
10350 ExprResult VisitParenExpr(ParenExpr *paren) {
10351 return rebuildSugarExpr(paren);
10352 }
10353
10354 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10355 return rebuildSugarExpr(op);
10356 }
10357
10358 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10359 ExprResult subResult = Visit(op->getSubExpr());
10360 if (subResult.isInvalid()) return ExprError();
10361
10362 Expr *subExpr = subResult.take();
10363 op->setSubExpr(subExpr);
10364 op->setType(S.Context.getPointerType(subExpr->getType()));
10365 assert(op->getValueKind() == VK_RValue);
10366 assert(op->getObjectKind() == OK_Ordinary);
10367 return op;
10368 }
10369
10370 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10371 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10372
10373 expr->setType(decl->getType());
10374
10375 assert(expr->getValueKind() == VK_RValue);
10376 if (S.getLangOptions().CPlusPlus &&
10377 !(isa<CXXMethodDecl>(decl) &&
10378 cast<CXXMethodDecl>(decl)->isInstance()))
10379 expr->setValueKind(VK_LValue);
10380
10381 return expr;
10382 }
10383
10384 ExprResult VisitMemberExpr(MemberExpr *mem) {
10385 return resolveDecl(mem, mem->getMemberDecl());
10386 }
10387
10388 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10389 return resolveDecl(ref, ref->getDecl());
10390 }
10391 };
10392}
10393
10394/// Given a function expression of unknown-any type, try to rebuild it
10395/// to have a function type.
10396static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10397 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10398 if (result.isInvalid()) return ExprError();
10399 return S.DefaultFunctionArrayConversion(result.take());
10400}
10401
10402namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010403 /// A visitor for rebuilding an expression of type __unknown_anytype
10404 /// into one which resolves the type directly on the referring
10405 /// expression. Strict preservation of the original source
10406 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010407 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010408 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010409
10410 Sema &S;
10411
10412 /// The current destination type.
10413 QualType DestType;
10414
10415 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10416 : S(S), DestType(castType) {}
10417
John McCall39439732011-04-09 22:50:59 +000010418 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010419 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010420 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010421 }
10422
John McCall2d2e8702011-04-11 07:02:50 +000010423 ExprResult VisitExpr(Expr *expr) {
10424 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10425 << expr->getSourceRange();
10426 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010427 }
10428
John McCall2d2e8702011-04-11 07:02:50 +000010429 ExprResult VisitCallExpr(CallExpr *call);
10430 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10431
John McCall39439732011-04-09 22:50:59 +000010432 /// Rebuild an expression which simply semantically wraps another
10433 /// expression which it shares the type and value kind of.
10434 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10435 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010436 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010437 Expr *subExpr = subResult.take();
10438 expr->setSubExpr(subExpr);
10439 expr->setType(subExpr->getType());
10440 expr->setValueKind(subExpr->getValueKind());
10441 assert(expr->getObjectKind() == OK_Ordinary);
10442 return expr;
10443 }
John McCall31996342011-04-07 08:22:57 +000010444
John McCall39439732011-04-09 22:50:59 +000010445 ExprResult VisitParenExpr(ParenExpr *paren) {
10446 return rebuildSugarExpr(paren);
10447 }
10448
10449 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10450 return rebuildSugarExpr(op);
10451 }
10452
John McCall2979fe02011-04-12 00:42:48 +000010453 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10454 const PointerType *ptr = DestType->getAs<PointerType>();
10455 if (!ptr) {
10456 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10457 << op->getSourceRange();
10458 return ExprError();
10459 }
10460 assert(op->getValueKind() == VK_RValue);
10461 assert(op->getObjectKind() == OK_Ordinary);
10462 op->setType(DestType);
10463
10464 // Build the sub-expression as if it were an object of the pointee type.
10465 DestType = ptr->getPointeeType();
10466 ExprResult subResult = Visit(op->getSubExpr());
10467 if (subResult.isInvalid()) return ExprError();
10468 op->setSubExpr(subResult.take());
10469 return op;
10470 }
10471
John McCall2d2e8702011-04-11 07:02:50 +000010472 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010473
John McCall2979fe02011-04-12 00:42:48 +000010474 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010475
John McCall2979fe02011-04-12 00:42:48 +000010476 ExprResult VisitMemberExpr(MemberExpr *mem) {
10477 return resolveDecl(mem, mem->getMemberDecl());
10478 }
John McCall39439732011-04-09 22:50:59 +000010479
10480 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010481 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010482 }
10483 };
10484}
10485
John McCall2d2e8702011-04-11 07:02:50 +000010486/// Rebuilds a call expression which yielded __unknown_anytype.
10487ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10488 Expr *callee = call->getCallee();
10489
10490 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010491 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010492 FK_FunctionPointer,
10493 FK_BlockPointer
10494 };
10495
10496 FnKind kind;
10497 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010498 if (type == S.Context.BoundMemberTy) {
10499 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10500 kind = FK_MemberFunction;
10501 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010502 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10503 type = ptr->getPointeeType();
10504 kind = FK_FunctionPointer;
10505 } else {
10506 type = type->castAs<BlockPointerType>()->getPointeeType();
10507 kind = FK_BlockPointer;
10508 }
10509 const FunctionType *fnType = type->castAs<FunctionType>();
10510
10511 // Verify that this is a legal result type of a function.
10512 if (DestType->isArrayType() || DestType->isFunctionType()) {
10513 unsigned diagID = diag::err_func_returning_array_function;
10514 if (kind == FK_BlockPointer)
10515 diagID = diag::err_block_returning_array_function;
10516
10517 S.Diag(call->getExprLoc(), diagID)
10518 << DestType->isFunctionType() << DestType;
10519 return ExprError();
10520 }
10521
10522 // Otherwise, go ahead and set DestType as the call's result.
10523 call->setType(DestType.getNonLValueExprType(S.Context));
10524 call->setValueKind(Expr::getValueKindForType(DestType));
10525 assert(call->getObjectKind() == OK_Ordinary);
10526
10527 // Rebuild the function type, replacing the result type with DestType.
10528 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10529 DestType = S.Context.getFunctionType(DestType,
10530 proto->arg_type_begin(),
10531 proto->getNumArgs(),
10532 proto->getExtProtoInfo());
10533 else
10534 DestType = S.Context.getFunctionNoProtoType(DestType,
10535 fnType->getExtInfo());
10536
10537 // Rebuild the appropriate pointer-to-function type.
10538 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010539 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010540 // Nothing to do.
10541 break;
10542
10543 case FK_FunctionPointer:
10544 DestType = S.Context.getPointerType(DestType);
10545 break;
10546
10547 case FK_BlockPointer:
10548 DestType = S.Context.getBlockPointerType(DestType);
10549 break;
10550 }
10551
10552 // Finally, we can recurse.
10553 ExprResult calleeResult = Visit(callee);
10554 if (!calleeResult.isUsable()) return ExprError();
10555 call->setCallee(calleeResult.take());
10556
10557 // Bind a temporary if necessary.
10558 return S.MaybeBindToTemporary(call);
10559}
10560
10561ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010562 ObjCMethodDecl *method = msg->getMethodDecl();
10563 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010564
John McCall2979fe02011-04-12 00:42:48 +000010565 // Verify that this is a legal result type of a call.
10566 if (DestType->isArrayType() || DestType->isFunctionType()) {
10567 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10568 << DestType->isFunctionType() << DestType;
10569 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010570 }
10571
John McCall2979fe02011-04-12 00:42:48 +000010572 assert(method->getResultType() == S.Context.UnknownAnyTy);
10573 method->setResultType(DestType);
10574
John McCall2d2e8702011-04-11 07:02:50 +000010575 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010576 msg->setType(DestType.getNonReferenceType());
10577 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010578
John McCall2979fe02011-04-12 00:42:48 +000010579 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000010580}
10581
10582ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000010583 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000010584 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000010585 assert(ice->getValueKind() == VK_RValue);
10586 assert(ice->getObjectKind() == OK_Ordinary);
10587
John McCall2979fe02011-04-12 00:42:48 +000010588 ice->setType(DestType);
10589
John McCall2d2e8702011-04-11 07:02:50 +000010590 // Rebuild the sub-expression as the pointee (function) type.
10591 DestType = DestType->castAs<PointerType>()->getPointeeType();
10592
10593 ExprResult result = Visit(ice->getSubExpr());
10594 if (!result.isUsable()) return ExprError();
10595
10596 ice->setSubExpr(result.take());
10597 return S.Owned(ice);
10598}
10599
John McCall2979fe02011-04-12 00:42:48 +000010600ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000010601 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000010602 QualType type = DestType;
10603
10604 // We know how to make this work for certain kinds of decls:
10605
10606 // - functions
John McCall2979fe02011-04-12 00:42:48 +000010607 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000010608 // This is true because FunctionDecls must always have function
10609 // type, so we can't be resolving the entire thing at once.
10610 assert(type->isFunctionType());
10611
John McCall4adb38c2011-04-27 00:36:17 +000010612 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10613 if (method->isInstance()) {
10614 valueKind = VK_RValue;
10615 type = S.Context.BoundMemberTy;
10616 }
10617
John McCall2d2e8702011-04-11 07:02:50 +000010618 // Function references aren't l-values in C.
10619 if (!S.getLangOptions().CPlusPlus)
10620 valueKind = VK_RValue;
10621
10622 // - variables
10623 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000010624 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10625 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000010626 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000010627 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10628 << decl << expr->getSourceRange();
10629 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010630 }
10631
10632 // - nothing else
10633 } else {
10634 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10635 << decl << expr->getSourceRange();
10636 return ExprError();
10637 }
10638
John McCall2979fe02011-04-12 00:42:48 +000010639 decl->setType(DestType);
10640 expr->setType(type);
10641 expr->setValueKind(valueKind);
10642 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000010643}
10644
John McCall31996342011-04-07 08:22:57 +000010645/// Check a cast of an unknown-any type. We intentionally only
10646/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010647ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10648 Expr *castExpr, CastKind &castKind,
10649 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010650 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010651 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10652 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010653
John McCall39439732011-04-09 22:50:59 +000010654 castExpr = result.take();
10655 VK = castExpr->getValueKind();
10656 castKind = CK_NoOp;
10657
10658 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010659}
10660
10661static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10662 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000010663 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010664 while (true) {
10665 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000010666 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000010667 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010668 diagID = diag::err_uncasted_call_of_unknown_any;
10669 } else {
John McCall31996342011-04-07 08:22:57 +000010670 break;
John McCall2d2e8702011-04-11 07:02:50 +000010671 }
John McCall31996342011-04-07 08:22:57 +000010672 }
10673
John McCall2d2e8702011-04-11 07:02:50 +000010674 SourceLocation loc;
10675 NamedDecl *d;
10676 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10677 loc = ref->getLocation();
10678 d = ref->getDecl();
10679 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10680 loc = mem->getMemberLoc();
10681 d = mem->getMemberDecl();
10682 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10683 diagID = diag::err_uncasted_call_of_unknown_any;
10684 loc = msg->getSelectorLoc();
10685 d = msg->getMethodDecl();
10686 assert(d && "unknown method returning __unknown_any?");
10687 } else {
10688 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10689 << e->getSourceRange();
10690 return ExprError();
10691 }
10692
10693 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010694
10695 // Never recoverable.
10696 return ExprError();
10697}
10698
John McCall36e7fe32010-10-12 00:20:44 +000010699/// Check for operands with placeholder types and complain if found.
10700/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010701ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010702 // Placeholder types are always *exactly* the appropriate builtin type.
10703 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010704
John McCall31996342011-04-07 08:22:57 +000010705 // Overloaded expressions.
10706 if (type == Context.OverloadTy)
10707 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010708 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010709 QualType(),
10710 diag::err_ovl_unresolvable);
10711
John McCall0009fcc2011-04-26 20:42:42 +000010712 // Bound member functions.
10713 if (type == Context.BoundMemberTy) {
10714 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10715 << E->getSourceRange();
10716 return ExprError();
10717 }
10718
John McCall31996342011-04-07 08:22:57 +000010719 // Expressions of unknown type.
10720 if (type == Context.UnknownAnyTy)
10721 return diagnoseUnknownAnyExpr(*this, E);
10722
10723 assert(!type->isPlaceholderType());
10724 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010725}
Richard Trieu2c850c02011-04-21 21:44:26 +000010726
10727bool Sema::CheckCaseExpression(Expr *expr) {
10728 if (expr->isTypeDependent())
10729 return true;
10730 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10731 return expr->getType()->isIntegralOrEnumerationType();
10732 return false;
10733}