blob: 6327ee71db13576f5201acea22faca2497e47924 [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"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000161
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000246 SourceLocation MissingNilLoc
247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
248 std::string NullValue;
249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition())
250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
253 else if (Context.getTypeSize(Context.IntTy)
254 == Context.getTypeSize(Context.getSizeType()))
255 NullValue = "0";
256 else
257 NullValue = "0L";
258
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << isMethod
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall7ddbcf42010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000263}
264
Douglas Gregor87f95b02009-02-26 21:00:50 +0000265SourceRange Sema::getExprRange(ExprTy *E) const {
266 Expr *Ex = (Expr *)E;
267 return Ex? Ex->getSourceRange() : SourceRange();
268}
269
Chris Lattner513165e2008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattner513165e2008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattner513165e2008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000282 else if (Ty->isArrayType()) {
283 // In C90 mode, arrays only promote to pointers if the array expression is
284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
285 // type 'array of type' is converted to an expression that has type 'pointer
286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
287 // that has type 'array of type' ...". The relevant change is "an lvalue"
288 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000289 //
290 // C++ 4.2p1:
291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
292 // T" can be converted to an rvalue of type "pointer to T".
293 //
John McCall086a4642010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000297 }
John Wiegley01296292011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000301static void CheckForNullPointerDereference(Sema &S, Expr *E) {
302 // Check to see if we are dereferencing a null pointer. If so,
303 // and if not volatile-qualified, this is undefined behavior that the
304 // optimizer will delete, so warn about it. People sometimes try to use this
305 // to get a deterministic trap and are surprised by clang's behavior. This
306 // only handles the pattern "*null", which is a very syntactic check.
307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
308 if (UO->getOpcode() == UO_Deref &&
309 UO->getSubExpr()->IgnoreParenCasts()->
310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
311 !UO->getType().isVolatileQualified()) {
312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
313 S.PDiag(diag::warn_indirection_through_null)
314 << UO->getSubExpr()->getSourceRange());
315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
316 S.PDiag(diag::note_indirection_through_null));
317 }
318}
319
John Wiegley01296292011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000321 // C++ [conv.lval]p1:
322 // A glvalue of a non-function, non-array type T can be
323 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000325
John McCall27584242010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000328
John McCall27584242010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000337 }
John McCall27584242010-12-06 20:48:59 +0000338
339 // We don't want to throw lvalue-to-rvalue casts on top of
340 // expressions of certain types in C++.
341 if (getLangOptions().CPlusPlus &&
342 (E->getType() == Context.OverloadTy ||
343 T->isDependentType() ||
344 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000345 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000346
347 // The C standard is actually really unclear on this point, and
348 // DR106 tells us what the result should be but not why. It's
349 // generally best to say that void types just doesn't undergo
350 // lvalue-to-rvalue at all. Note that expressions of unqualified
351 // 'void' type are never l-values, but qualified void can be.
352 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000353 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000354
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall27584242010-12-06 20:48:59 +0000357 // C++ [conv.lval]p1:
358 // [...] If T is a non-class type, the type of the prvalue is the
359 // cv-unqualified version of T. Otherwise, the type of the
360 // rvalue is T.
361 //
362 // C99 6.3.2.1p2:
363 // If the lvalue has qualified type, the value has the unqualified
364 // version of the type of the lvalue; otherwise, the value has the
365 // type of the lvalue.
366 if (T.hasQualifiers())
367 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000368
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000371}
372
John Wiegley01296292011-04-08 18:41:53 +0000373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
374 ExprResult Res = DefaultFunctionArrayConversion(E);
375 if (Res.isInvalid())
376 return ExprError();
377 Res = DefaultLvalueConversion(Res.take());
378 if (Res.isInvalid())
379 return ExprError();
380 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000381}
382
383
Chris Lattner513165e2008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000387/// apply if the array is an argument to the sizeof or address (&) operators.
388/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000398
399 // Try to perform integral promotions if the object has a theoretically
400 // promotable type.
401 if (Ty->isIntegralOrUnscopedEnumerationType()) {
402 // C99 6.3.1.1p2:
403 //
404 // The following may be used in an expression wherever an int or
405 // unsigned int may be used:
406 // - an object or expression with an integer type whose integer
407 // conversion rank is less than or equal to the rank of int
408 // and unsigned int.
409 // - A bit-field of type _Bool, int, signed int, or unsigned int.
410 //
411 // If an int can represent all values of the original type, the
412 // value is converted to an int; otherwise, it is converted to an
413 // unsigned int. These are called the integer promotions. All
414 // other types are unchanged by the integer promotions.
415
416 QualType PTy = Context.isPromotableBitField(E);
417 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000425 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000426 }
John Wiegley01296292011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000428}
429
Chris Lattner2ce500f2008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000436
John Wiegley01296292011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000441
Chris Lattner2ce500f2008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
John McCall4bb057d2011-08-27 22:06:17 +0000446 // C++ performs lvalue-to-rvalue conversion as a default argument
447 // promotion. If we still have a gl-value after usual unary
448 // conversion, we must have an l-value of class type, so we need to
449 // initialize a temporary. For compatibility reasons, however, we
450 // don't want to do this in unevaluated contexts; otherwise we
451 // reject metaprograms which work by passing uncopyable l-values to
452 // variadic functions.
453 if (getLangOptions().CPlusPlus && E->isGLValue() &&
454 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000455 ExprResult Temp = PerformCopyInitialization(
456 InitializedEntity::InitializeTemporary(E->getType()),
457 E->getExprLoc(),
458 Owned(E));
459 if (Temp.isInvalid())
460 return ExprError();
461 E = Temp.get();
462 }
463
John Wiegley01296292011-04-08 18:41:53 +0000464 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000465}
466
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000467/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
468/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000469/// interfaces passed by value.
470ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000471 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000472 ExprResult ExprRes = CheckPlaceholderExpr(E);
473 if (ExprRes.isInvalid())
474 return ExprError();
475
476 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000477 if (ExprRes.isInvalid())
478 return ExprError();
479 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Douglas Gregor347e0f22011-05-21 19:26:31 +0000481 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000482 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000483 DiagRuntimeBehavior(E->getLocStart(), 0,
484 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
485 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000486 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000487
John McCall31168b02011-06-15 23:02:42 +0000488 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000489 // C++0x [expr.call]p7:
490 // Passing a potentially-evaluated argument of class type (Clause 9)
491 // having a non-trivial copy constructor, a non-trivial move constructor,
492 // or a non-trivial destructor, with no corresponding parameter,
493 // is conditionally-supported with implementation-defined semantics.
494 bool TrivialEnough = false;
495 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
496 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
497 if (Record->hasTrivialCopyConstructor() &&
498 Record->hasTrivialMoveConstructor() &&
499 Record->hasTrivialDestructor())
500 TrivialEnough = true;
501 }
502 }
John McCall31168b02011-06-15 23:02:42 +0000503
504 if (!TrivialEnough &&
505 getLangOptions().ObjCAutoRefCount &&
506 E->getType()->isObjCLifetimeType())
507 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000508
509 if (TrivialEnough) {
510 // Nothing to diagnose. This is okay.
511 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000512 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000513 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000514 << CT)) {
515 // Turn this into a trap.
516 CXXScopeSpec SS;
517 UnqualifiedId Name;
518 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
519 E->getLocStart());
520 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
521 if (TrapFn.isInvalid())
522 return ExprError();
523
524 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
525 MultiExprArg(), E->getLocEnd());
526 if (Call.isInvalid())
527 return ExprError();
528
529 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
530 Call.get(), E);
531 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000532 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000533 E = Comma.get();
534 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000535 }
536
John Wiegley01296292011-04-08 18:41:53 +0000537 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000538}
539
Chris Lattner513165e2008-07-25 21:10:04 +0000540/// UsualArithmeticConversions - Performs various conversions that are common to
541/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000542/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000543/// responsible for emitting appropriate error diagnostics.
544/// FIXME: verify the conversion rules for "complex int" are consistent with
545/// GCC.
Richard Trieucfc491d2011-08-02 04:35:43 +0000546QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
547 ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000548 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000549 if (!isCompAssign) {
550 lhsExpr = UsualUnaryConversions(lhsExpr.take());
551 if (lhsExpr.isInvalid())
552 return QualType();
553 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000554
John Wiegley01296292011-04-08 18:41:53 +0000555 rhsExpr = UsualUnaryConversions(rhsExpr.take());
556 if (rhsExpr.isInvalid())
557 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000558
Mike Stump11289f42009-09-09 15:08:12 +0000559 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000560 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000561 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000562 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000563 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000564 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000565
566 // If both types are identical, no conversion is needed.
567 if (lhs == rhs)
568 return lhs;
569
570 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
571 // The caller can deal with this (e.g. pointer + int).
572 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
573 return lhs;
574
John McCalld005ac92010-11-13 08:17:45 +0000575 // Apply unary and bitfield promotions to the LHS's type.
576 QualType lhs_unpromoted = lhs;
577 if (lhs->isPromotableIntegerType())
578 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000579 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000580 if (!LHSBitfieldPromoteTy.isNull())
581 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000582 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000583 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000584
John McCalld005ac92010-11-13 08:17:45 +0000585 // If both types are identical, no conversion is needed.
586 if (lhs == rhs)
587 return lhs;
588
589 // At this point, we have two different arithmetic types.
590
591 // Handle complex types first (C99 6.3.1.8p1).
592 bool LHSComplexFloat = lhs->isComplexType();
593 bool RHSComplexFloat = rhs->isComplexType();
594 if (LHSComplexFloat || RHSComplexFloat) {
595 // if we have an integer operand, the result is the complex type.
596
John McCallc5e62b42010-11-13 09:02:35 +0000597 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
598 if (rhs->isIntegerType()) {
599 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000600 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieucfc491d2011-08-02 04:35:43 +0000601 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
602 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000603 } else {
604 assert(rhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000605 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
606 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000607 }
John McCalld005ac92010-11-13 08:17:45 +0000608 return lhs;
609 }
610
John McCallc5e62b42010-11-13 09:02:35 +0000611 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
612 if (!isCompAssign) {
613 // int -> float -> _Complex float
614 if (lhs->isIntegerType()) {
615 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieucfc491d2011-08-02 04:35:43 +0000616 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
617 CK_IntegralToFloating);
618 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
619 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000620 } else {
621 assert(lhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000622 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
623 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000624 }
625 }
John McCalld005ac92010-11-13 08:17:45 +0000626 return rhs;
627 }
628
629 // This handles complex/complex, complex/float, or float/complex.
630 // When both operands are complex, the shorter operand is converted to the
631 // type of the longer, and that is the type of the result. This corresponds
632 // to what is done when combining two real floating-point operands.
633 // The fun begins when size promotion occur across type domains.
634 // From H&S 6.3.4: When one operand is complex and the other is a real
635 // floating-point type, the less precise type is converted, within it's
636 // real or complex domain, to the precision of the other type. For example,
637 // when combining a "long double" with a "double _Complex", the
638 // "double _Complex" is promoted to "long double _Complex".
639 int order = Context.getFloatingTypeOrder(lhs, rhs);
640
641 // If both are complex, just cast to the more precise type.
642 if (LHSComplexFloat && RHSComplexFloat) {
643 if (order > 0) {
644 // _Complex float -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
646 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000647 return lhs;
648
649 } else if (order < 0) {
650 // _Complex float -> _Complex double
651 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000652 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
653 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000654 return rhs;
655 }
656 return lhs;
657 }
658
659 // If just the LHS is complex, the RHS needs to be converted,
660 // and the LHS might need to be promoted.
661 if (LHSComplexFloat) {
662 if (order > 0) { // LHS is wider
663 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000664 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000665 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000666 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
667 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000668 return lhs;
669 }
670
671 // RHS is at least as wide. Find its corresponding complex type.
672 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
673
674 // double -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000675 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
676 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000677
678 // _Complex float -> _Complex double
679 if (!isCompAssign && order < 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000680 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
681 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000682
683 return result;
684 }
685
686 // Just the RHS is complex, so the LHS needs to be converted
687 // and the RHS might need to be promoted.
688 assert(RHSComplexFloat);
689
690 if (order < 0) { // RHS is wider
691 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000692 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000693 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000694 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000695 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
696 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000697 }
John McCalld005ac92010-11-13 08:17:45 +0000698 return rhs;
699 }
700
701 // LHS is at least as wide. Find its corresponding complex type.
702 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
703
704 // double -> _Complex double
705 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000706 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
707 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000708
709 // _Complex float -> _Complex double
710 if (order > 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000711 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
712 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000713
714 return result;
715 }
716
717 // Now handle "real" floating types (i.e. float, double, long double).
718 bool LHSFloat = lhs->isRealFloatingType();
719 bool RHSFloat = rhs->isRealFloatingType();
720 if (LHSFloat || RHSFloat) {
721 // If we have two real floating types, convert the smaller operand
722 // to the bigger result.
723 if (LHSFloat && RHSFloat) {
724 int order = Context.getFloatingTypeOrder(lhs, rhs);
725 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000726 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000727 return lhs;
728 }
729
730 assert(order < 0 && "illegal float comparison");
731 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000732 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000733 return rhs;
734 }
735
736 // If we have an integer operand, the result is the real floating type.
737 if (LHSFloat) {
738 if (rhs->isIntegerType()) {
739 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000740 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000741 return lhs;
742 }
743
744 // Convert both sides to the appropriate complex float.
745 assert(rhs->isComplexIntegerType());
746 QualType result = Context.getComplexType(lhs);
747
748 // _Complex int -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000749 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
750 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000751
752 // float -> _Complex float
753 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000754 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
755 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000756
757 return result;
758 }
759
760 assert(RHSFloat);
761 if (lhs->isIntegerType()) {
762 // Convert lhs to the rhs floating point type.
763 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000764 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000765 return rhs;
766 }
767
768 // Convert both sides to the appropriate complex float.
769 assert(lhs->isComplexIntegerType());
770 QualType result = Context.getComplexType(rhs);
771
772 // _Complex int -> _Complex float
773 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000774 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
775 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000776
777 // float -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000778 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
779 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000780
781 return result;
782 }
783
784 // Handle GCC complex int extension.
785 // FIXME: if the operands are (int, _Complex long), we currently
786 // don't promote the complex. Also, signedness?
787 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
788 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
789 if (lhsComplexInt && rhsComplexInt) {
790 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
791 rhsComplexInt->getElementType());
792 assert(order && "inequal types with equal element ordering");
793 if (order > 0) {
794 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000795 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000796 return lhs;
797 }
798
799 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000800 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000801 return rhs;
802 } else if (lhsComplexInt) {
803 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000804 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000805 return lhs;
806 } else if (rhsComplexInt) {
807 // int -> _Complex int
808 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000809 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
810 CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000811 return rhs;
812 }
813
814 // Finally, we have two differing integer types.
815 // The rules for this case are in C99 6.3.1.8
816 int compare = Context.getIntegerTypeOrder(lhs, rhs);
817 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
818 rhsSigned = rhs->hasSignedIntegerRepresentation();
819 if (lhsSigned == rhsSigned) {
820 // Same signedness; use the higher-ranked type
821 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000822 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000823 return lhs;
824 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000825 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000826 return rhs;
827 } else if (compare != (lhsSigned ? 1 : -1)) {
828 // The unsigned type has greater than or equal rank to the
829 // signed type, so use the unsigned type
830 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000831 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000832 return lhs;
833 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000834 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000835 return rhs;
836 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
837 // The two types are different widths; if we are here, that
838 // means the signed type is larger than the unsigned type, so
839 // use the signed type.
840 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000841 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000842 return lhs;
843 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000844 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000845 return rhs;
846 } else {
847 // The signed type is higher-ranked than the unsigned type,
848 // but isn't actually any bigger (like unsigned int and long
849 // on most 32-bit systems). Use the unsigned type corresponding
850 // to the signed type.
851 QualType result =
852 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000853 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000854 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000855 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000856 return result;
857 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000858}
859
Chris Lattner513165e2008-07-25 21:10:04 +0000860//===----------------------------------------------------------------------===//
861// Semantic Analysis for various Expression Types
862//===----------------------------------------------------------------------===//
863
864
Peter Collingbourne91147592011-04-15 00:35:48 +0000865ExprResult
866Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
867 SourceLocation DefaultLoc,
868 SourceLocation RParenLoc,
869 Expr *ControllingExpr,
870 MultiTypeArg types,
871 MultiExprArg exprs) {
872 unsigned NumAssocs = types.size();
873 assert(NumAssocs == exprs.size());
874
875 ParsedType *ParsedTypes = types.release();
876 Expr **Exprs = exprs.release();
877
878 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
879 for (unsigned i = 0; i < NumAssocs; ++i) {
880 if (ParsedTypes[i])
881 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
882 else
883 Types[i] = 0;
884 }
885
886 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
887 ControllingExpr, Types, Exprs,
888 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000889 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000890 return ER;
891}
892
893ExprResult
894Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
895 SourceLocation DefaultLoc,
896 SourceLocation RParenLoc,
897 Expr *ControllingExpr,
898 TypeSourceInfo **Types,
899 Expr **Exprs,
900 unsigned NumAssocs) {
901 bool TypeErrorFound = false,
902 IsResultDependent = ControllingExpr->isTypeDependent(),
903 ContainsUnexpandedParameterPack
904 = ControllingExpr->containsUnexpandedParameterPack();
905
906 for (unsigned i = 0; i < NumAssocs; ++i) {
907 if (Exprs[i]->containsUnexpandedParameterPack())
908 ContainsUnexpandedParameterPack = true;
909
910 if (Types[i]) {
911 if (Types[i]->getType()->containsUnexpandedParameterPack())
912 ContainsUnexpandedParameterPack = true;
913
914 if (Types[i]->getType()->isDependentType()) {
915 IsResultDependent = true;
916 } else {
917 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
918 // complete object type other than a variably modified type."
919 unsigned D = 0;
920 if (Types[i]->getType()->isIncompleteType())
921 D = diag::err_assoc_type_incomplete;
922 else if (!Types[i]->getType()->isObjectType())
923 D = diag::err_assoc_type_nonobject;
924 else if (Types[i]->getType()->isVariablyModifiedType())
925 D = diag::err_assoc_type_variably_modified;
926
927 if (D != 0) {
928 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
929 << Types[i]->getTypeLoc().getSourceRange()
930 << Types[i]->getType();
931 TypeErrorFound = true;
932 }
933
934 // C1X 6.5.1.1p2 "No two generic associations in the same generic
935 // selection shall specify compatible types."
936 for (unsigned j = i+1; j < NumAssocs; ++j)
937 if (Types[j] && !Types[j]->getType()->isDependentType() &&
938 Context.typesAreCompatible(Types[i]->getType(),
939 Types[j]->getType())) {
940 Diag(Types[j]->getTypeLoc().getBeginLoc(),
941 diag::err_assoc_compatible_types)
942 << Types[j]->getTypeLoc().getSourceRange()
943 << Types[j]->getType()
944 << Types[i]->getType();
945 Diag(Types[i]->getTypeLoc().getBeginLoc(),
946 diag::note_compat_assoc)
947 << Types[i]->getTypeLoc().getSourceRange()
948 << Types[i]->getType();
949 TypeErrorFound = true;
950 }
951 }
952 }
953 }
954 if (TypeErrorFound)
955 return ExprError();
956
957 // If we determined that the generic selection is result-dependent, don't
958 // try to compute the result expression.
959 if (IsResultDependent)
960 return Owned(new (Context) GenericSelectionExpr(
961 Context, KeyLoc, ControllingExpr,
962 Types, Exprs, NumAssocs, DefaultLoc,
963 RParenLoc, ContainsUnexpandedParameterPack));
964
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000965 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000966 unsigned DefaultIndex = -1U;
967 for (unsigned i = 0; i < NumAssocs; ++i) {
968 if (!Types[i])
969 DefaultIndex = i;
970 else if (Context.typesAreCompatible(ControllingExpr->getType(),
971 Types[i]->getType()))
972 CompatIndices.push_back(i);
973 }
974
975 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
976 // type compatible with at most one of the types named in its generic
977 // association list."
978 if (CompatIndices.size() > 1) {
979 // We strip parens here because the controlling expression is typically
980 // parenthesized in macro definitions.
981 ControllingExpr = ControllingExpr->IgnoreParens();
982 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
983 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
984 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000985 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000986 E = CompatIndices.end(); I != E; ++I) {
987 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
988 diag::note_compat_assoc)
989 << Types[*I]->getTypeLoc().getSourceRange()
990 << Types[*I]->getType();
991 }
992 return ExprError();
993 }
994
995 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
996 // its controlling expression shall have type compatible with exactly one of
997 // the types named in its generic association list."
998 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
999 // We strip parens here because the controlling expression is typically
1000 // parenthesized in macro definitions.
1001 ControllingExpr = ControllingExpr->IgnoreParens();
1002 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1003 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1004 return ExprError();
1005 }
1006
1007 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1008 // type name that is compatible with the type of the controlling expression,
1009 // then the result expression of the generic selection is the expression
1010 // in that generic association. Otherwise, the result expression of the
1011 // generic selection is the expression in the default generic association."
1012 unsigned ResultIndex =
1013 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1014
1015 return Owned(new (Context) GenericSelectionExpr(
1016 Context, KeyLoc, ControllingExpr,
1017 Types, Exprs, NumAssocs, DefaultLoc,
1018 RParenLoc, ContainsUnexpandedParameterPack,
1019 ResultIndex));
1020}
1021
Steve Naroff83895f72007-09-16 03:34:24 +00001022/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001023/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1024/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1025/// multiple tokens. However, the common case is that StringToks points to one
1026/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001027///
John McCalldadc5752010-08-24 06:29:42 +00001028ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001029Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001030 assert(NumStringToks && "Must have at least one string!");
1031
Chris Lattner8a24e582009-01-16 18:51:42 +00001032 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001033 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001034 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001035
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001036 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001037 for (unsigned i = 0; i != NumStringToks; ++i)
1038 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001039
Chris Lattner36fc8792008-02-11 00:02:17 +00001040 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001041 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001042 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001043 else if (Literal.isUTF16())
1044 StrTy = Context.Char16Ty;
1045 else if (Literal.isUTF32())
1046 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001047 else if (Literal.Pascal)
1048 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001049
Douglas Gregorfb65e592011-07-27 05:40:30 +00001050 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1051 if (Literal.isWide())
1052 Kind = StringLiteral::Wide;
1053 else if (Literal.isUTF8())
1054 Kind = StringLiteral::UTF8;
1055 else if (Literal.isUTF16())
1056 Kind = StringLiteral::UTF16;
1057 else if (Literal.isUTF32())
1058 Kind = StringLiteral::UTF32;
1059
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001060 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001061 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001062 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001063
Chris Lattner36fc8792008-02-11 00:02:17 +00001064 // Get an array type for the string, according to C99 6.4.5. This includes
1065 // the nul terminator character as well as the string length for pascal
1066 // strings.
1067 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001068 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001069 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattner5b183d82006-11-10 05:03:26 +00001071 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001072 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001073 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001074 &StringTokLocs[0],
1075 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001076}
1077
John McCallc63de662011-02-02 13:00:07 +00001078enum CaptureResult {
1079 /// No capture is required.
1080 CR_NoCapture,
1081
1082 /// A capture is required.
1083 CR_Capture,
1084
John McCall351762c2011-02-07 10:33:21 +00001085 /// A by-ref capture is required.
1086 CR_CaptureByRef,
1087
John McCallc63de662011-02-02 13:00:07 +00001088 /// An error occurred when trying to capture the given variable.
1089 CR_Error
1090};
1091
1092/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001093///
John McCallc63de662011-02-02 13:00:07 +00001094/// \param var - the variable referenced
1095/// \param DC - the context which we couldn't capture through
1096static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001097diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001098 VarDecl *var, DeclContext *DC) {
1099 switch (S.ExprEvalContexts.back().Context) {
1100 case Sema::Unevaluated:
1101 // The argument will never be evaluated, so don't complain.
1102 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001103
John McCallc63de662011-02-02 13:00:07 +00001104 case Sema::PotentiallyEvaluated:
1105 case Sema::PotentiallyEvaluatedIfUsed:
1106 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001107
John McCallc63de662011-02-02 13:00:07 +00001108 case Sema::PotentiallyPotentiallyEvaluated:
1109 // FIXME: delay these!
1110 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001111 }
Mike Stump11289f42009-09-09 15:08:12 +00001112
John McCallc63de662011-02-02 13:00:07 +00001113 // Don't diagnose about capture if we're not actually in code right
1114 // now; in general, there are more appropriate places that will
1115 // diagnose this.
1116 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1117
John McCall92d627e2011-03-22 23:15:50 +00001118 // Certain madnesses can happen with parameter declarations, which
1119 // we want to ignore.
1120 if (isa<ParmVarDecl>(var)) {
1121 // - If the parameter still belongs to the translation unit, then
1122 // we're actually just using one parameter in the declaration of
1123 // the next. This is useful in e.g. VLAs.
1124 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1125 return CR_NoCapture;
1126
1127 // - This particular madness can happen in ill-formed default
1128 // arguments; claim it's okay and let downstream code handle it.
1129 if (S.CurContext == var->getDeclContext()->getParent())
1130 return CR_NoCapture;
1131 }
John McCallc63de662011-02-02 13:00:07 +00001132
1133 DeclarationName functionName;
1134 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1135 functionName = fn->getDeclName();
1136 // FIXME: variable from enclosing block that we couldn't capture from!
1137
1138 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1139 << var->getIdentifier() << functionName;
1140 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1141 << var->getIdentifier();
1142
1143 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001144}
1145
John McCall351762c2011-02-07 10:33:21 +00001146/// There is a well-formed capture at a particular scope level;
1147/// propagate it through all the nested blocks.
1148static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1149 const BlockDecl::Capture &capture) {
1150 VarDecl *var = capture.getVariable();
1151
1152 // Update all the inner blocks with the capture information.
1153 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1154 i != e; ++i) {
1155 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1156 innerBlock->Captures.push_back(
1157 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1158 /*nested*/ true, capture.getCopyExpr()));
1159 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1160 }
1161
1162 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1163}
1164
1165/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001166/// given value in the current context requires a variable capture.
1167///
1168/// This also keeps the captures set in the BlockScopeInfo records
1169/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001170static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001171 ValueDecl *value) {
1172 // Only variables ever require capture.
1173 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001174 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001175
1176 // Fast path: variables from the current context never require capture.
1177 DeclContext *DC = S.CurContext;
1178 if (var->getDeclContext() == DC) return CR_NoCapture;
1179
1180 // Only variables with local storage require capture.
1181 // FIXME: What about 'const' variables in C++?
1182 if (!var->hasLocalStorage()) return CR_NoCapture;
1183
1184 // Otherwise, we need to capture.
1185
1186 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001187 do {
1188 // Only blocks (and eventually C++0x closures) can capture; other
1189 // scopes don't work.
1190 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001191 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001192
1193 BlockScopeInfo *blockScope =
1194 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1195 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1196
John McCall351762c2011-02-07 10:33:21 +00001197 // Check whether we've already captured it in this block. If so,
1198 // we're done.
1199 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1200 return propagateCapture(S, functionScopesIndex,
1201 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001202
1203 functionScopesIndex--;
1204 DC = cast<BlockDecl>(DC)->getDeclContext();
1205 } while (var->getDeclContext() != DC);
1206
John McCall351762c2011-02-07 10:33:21 +00001207 // Okay, we descended all the way to the block that defines the variable.
1208 // Actually try to capture it.
1209 QualType type = var->getType();
1210
1211 // Prohibit variably-modified types.
1212 if (type->isVariablyModifiedType()) {
1213 S.Diag(loc, diag::err_ref_vm_type);
1214 S.Diag(var->getLocation(), diag::note_declared_at);
1215 return CR_Error;
1216 }
1217
1218 // Prohibit arrays, even in __block variables, but not references to
1219 // them.
1220 if (type->isArrayType()) {
1221 S.Diag(loc, diag::err_ref_array_type);
1222 S.Diag(var->getLocation(), diag::note_declared_at);
1223 return CR_Error;
1224 }
1225
1226 S.MarkDeclarationReferenced(loc, var);
1227
1228 // The BlocksAttr indicates the variable is bound by-reference.
1229 bool byRef = var->hasAttr<BlocksAttr>();
1230
1231 // Build a copy expression.
1232 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001233 const RecordType *rtype;
1234 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1235 (rtype = type->getAs<RecordType>())) {
1236
1237 // The capture logic needs the destructor, so make sure we mark it.
1238 // Usually this is unnecessary because most local variables have
1239 // their destructors marked at declaration time, but parameters are
1240 // an exception because it's technically only the call site that
1241 // actually requires the destructor.
1242 if (isa<ParmVarDecl>(var))
1243 S.FinalizeVarWithDestructor(var, rtype);
1244
John McCall351762c2011-02-07 10:33:21 +00001245 // According to the blocks spec, the capture of a variable from
1246 // the stack requires a const copy constructor. This is not true
1247 // of the copy/move done to move a __block variable to the heap.
1248 type.addConst();
1249
1250 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1251 ExprResult result =
1252 S.PerformCopyInitialization(
1253 InitializedEntity::InitializeBlock(var->getLocation(),
1254 type, false),
1255 loc, S.Owned(declRef));
1256
1257 // Build a full-expression copy expression if initialization
1258 // succeeded and used a non-trivial constructor. Recover from
1259 // errors by pretending that the copy isn't necessary.
1260 if (!result.isInvalid() &&
1261 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1262 result = S.MaybeCreateExprWithCleanups(result);
1263 copyExpr = result.take();
1264 }
1265 }
1266
1267 // We're currently at the declarer; go back to the closure.
1268 functionScopesIndex++;
1269 BlockScopeInfo *blockScope =
1270 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1271
1272 // Build a valid capture in this scope.
1273 blockScope->Captures.push_back(
1274 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1275 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1276
1277 // Propagate that to inner captures if necessary.
1278 return propagateCapture(S, functionScopesIndex,
1279 blockScope->Captures.back());
1280}
1281
1282static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1283 const DeclarationNameInfo &NameInfo,
1284 bool byRef) {
1285 assert(isa<VarDecl>(vd) && "capturing non-variable");
1286
1287 VarDecl *var = cast<VarDecl>(vd);
1288 assert(var->hasLocalStorage() && "capturing non-local");
1289 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1290
1291 QualType exprType = var->getType().getNonReferenceType();
1292
1293 BlockDeclRefExpr *BDRE;
1294 if (!byRef) {
1295 // The variable will be bound by copy; make it const within the
1296 // closure, but record that this was done in the expression.
1297 bool constAdded = !exprType.isConstQualified();
1298 exprType.addConst();
1299
1300 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1301 NameInfo.getLoc(), false,
1302 constAdded);
1303 } else {
1304 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1305 NameInfo.getLoc(), true);
1306 }
1307
1308 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001309}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001310
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001312Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001313 SourceLocation Loc,
1314 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001315 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001316 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001317}
1318
John McCallf4cd4f92011-02-09 01:13:10 +00001319/// BuildDeclRefExpr - Build an expression that references a
1320/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001321ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001322Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001323 const DeclarationNameInfo &NameInfo,
1324 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001325 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001326
John McCall086a4642010-11-24 05:12:34 +00001327 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001328 SS? SS->getWithLocInContext(Context)
1329 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001330 D, NameInfo, Ty, VK);
1331
1332 // Just in case we're building an illegal pointer-to-member.
1333 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1334 E->setObjectKind(OK_BitField);
1335
1336 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001337}
1338
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001339/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001340/// possibly a list of template arguments.
1341///
1342/// If this produces template arguments, it is permitted to call
1343/// DecomposeTemplateName.
1344///
1345/// This actually loses a lot of source location information for
1346/// non-standard name kinds; we should consider preserving that in
1347/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001348void
1349Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1350 TemplateArgumentListInfo &Buffer,
1351 DeclarationNameInfo &NameInfo,
1352 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001353 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1354 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1355 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1356
Douglas Gregor5476205b2011-06-23 00:49:38 +00001357 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001358 Id.TemplateId->getTemplateArgs(),
1359 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001360 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001361 TemplateArgsPtr.release();
1362
John McCall3e56fd42010-08-23 07:28:44 +00001363 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001365 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001366 TemplateArgs = &Buffer;
1367 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001368 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001369 TemplateArgs = 0;
1370 }
1371}
1372
John McCalld681c392009-12-16 08:11:27 +00001373/// Diagnose an empty lookup.
1374///
1375/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001376bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001377 CorrectTypoContext CTC,
1378 TemplateArgumentListInfo *ExplicitTemplateArgs,
1379 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001380 DeclarationName Name = R.getLookupName();
1381
John McCalld681c392009-12-16 08:11:27 +00001382 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001383 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001384 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1385 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001386 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001387 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001388 diagnostic_suggest = diag::err_undeclared_use_suggest;
1389 }
John McCalld681c392009-12-16 08:11:27 +00001390
Douglas Gregor598b08f2009-12-31 05:20:13 +00001391 // If the original lookup was an unqualified lookup, fake an
1392 // unqualified lookup. This is useful when (for example) the
1393 // original lookup would not have found something because it was a
1394 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001395 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001396 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001397 if (isa<CXXRecordDecl>(DC)) {
1398 LookupQualifiedName(R, DC);
1399
1400 if (!R.empty()) {
1401 // Don't give errors about ambiguities in this lookup.
1402 R.suppressDiagnostics();
1403
1404 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1405 bool isInstance = CurMethod &&
1406 CurMethod->isInstance() &&
1407 DC == CurMethod->getParent();
1408
1409 // Give a code modification hint to insert 'this->'.
1410 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1411 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001412 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001413 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1414 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001415 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001416 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001417 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001418 Diag(R.getNameLoc(), diagnostic) << Name
1419 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1420 QualType DepThisType = DepMethod->getThisType(Context);
1421 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1422 R.getNameLoc(), DepThisType, false);
1423 TemplateArgumentListInfo TList;
1424 if (ULE->hasExplicitTemplateArgs())
1425 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001426
Douglas Gregore16af532011-02-28 18:50:33 +00001427 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001428 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001429 CXXDependentScopeMemberExpr *DepExpr =
1430 CXXDependentScopeMemberExpr::Create(
1431 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001432 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001433 R.getLookupNameInfo(), &TList);
1434 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001435 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001436 // FIXME: we should be able to handle this case too. It is correct
1437 // to add this-> here. This is a workaround for PR7947.
1438 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001439 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001440 } else {
John McCalld681c392009-12-16 08:11:27 +00001441 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001442 }
John McCalld681c392009-12-16 08:11:27 +00001443
1444 // Do we really want to note all of these?
1445 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1446 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1447
1448 // Tell the callee to try to recover.
1449 return false;
1450 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001451
1452 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001453 }
1454 }
1455
Douglas Gregor598b08f2009-12-31 05:20:13 +00001456 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001457 TypoCorrection Corrected;
1458 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1459 S, &SS, NULL, false, CTC))) {
1460 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1461 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1462 R.setLookupName(Corrected.getCorrection());
1463
Hans Wennborg38198de2011-07-12 08:45:31 +00001464 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001465 if (Corrected.isOverloaded()) {
1466 OverloadCandidateSet OCS(R.getNameLoc());
1467 OverloadCandidateSet::iterator Best;
1468 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1469 CDEnd = Corrected.end();
1470 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001471 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001472 dyn_cast<FunctionTemplateDecl>(*CD))
1473 AddTemplateOverloadCandidate(
1474 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1475 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001476 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1477 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1478 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1479 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001480 }
1481 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1482 case OR_Success:
1483 ND = Best->Function;
1484 break;
1485 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001486 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001487 }
1488 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001489 R.addDecl(ND);
1490 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001491 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001492 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1493 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001494 else
1495 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001496 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001497 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001498 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1499 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001500 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001501 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001502
1503 // Tell the callee to try to recover.
1504 return false;
1505 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001506
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001507 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001508 // FIXME: If we ended up with a typo for a type name or
1509 // Objective-C class name, we're in trouble because the parser
1510 // is in the wrong place to recover. Suggest the typo
1511 // correction, but don't make it a fix-it since we're not going
1512 // to recover well anyway.
1513 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001514 Diag(R.getNameLoc(), diagnostic_suggest)
1515 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001516 else
1517 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001518 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001519 << SS.getRange();
1520
1521 // Don't try to recover; it won't work.
1522 return true;
1523 }
1524 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001525 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001526 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001527 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001528 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001529 else
Douglas Gregor25363982010-01-01 00:15:04 +00001530 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001531 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001532 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001533 return true;
1534 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001535 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001536 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001537
1538 // Emit a special diagnostic for failed member lookups.
1539 // FIXME: computing the declaration context might fail here (?)
1540 if (!SS.isEmpty()) {
1541 Diag(R.getNameLoc(), diag::err_no_member)
1542 << Name << computeDeclContext(SS, false)
1543 << SS.getRange();
1544 return true;
1545 }
1546
John McCalld681c392009-12-16 08:11:27 +00001547 // Give up, we can't recover.
1548 Diag(R.getNameLoc(), diagnostic) << Name;
1549 return true;
1550}
1551
Douglas Gregor05fcf842010-11-02 20:36:02 +00001552ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1553 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001554 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1555 if (!IDecl)
1556 return 0;
1557 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1558 if (!ClassImpDecl)
1559 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001560 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001561 if (!property)
1562 return 0;
1563 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001564 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1565 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001566 return 0;
1567 return property;
1568}
1569
Douglas Gregor05fcf842010-11-02 20:36:02 +00001570bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1571 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1572 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1573 if (!IDecl)
1574 return false;
1575 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1576 if (!ClassImpDecl)
1577 return false;
1578 if (ObjCPropertyImplDecl *PIDecl
1579 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1580 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1581 PIDecl->getPropertyIvarDecl())
1582 return false;
1583
1584 return true;
1585}
1586
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001587ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1588 IdentifierInfo *II,
1589 SourceLocation NameLoc) {
1590 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001591 bool LookForIvars;
1592 if (Lookup.empty())
1593 LookForIvars = true;
1594 else if (CurMeth->isClassMethod())
1595 LookForIvars = false;
1596 else
1597 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001598 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1599 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001600 if (!LookForIvars)
1601 return 0;
1602
Fariborz Jahanian18722982010-07-17 00:59:30 +00001603 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1604 if (!IDecl)
1605 return 0;
1606 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001607 if (!ClassImpDecl)
1608 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001609 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001610 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001611 if (!property)
1612 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001613 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001614 DynamicImplSeen =
1615 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001616 // property implementation has a designated ivar. No need to assume a new
1617 // one.
1618 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1619 return 0;
1620 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001621 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001622 QualType PropType = Context.getCanonicalType(property->getType());
1623 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001624 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001625 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001626 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001627 (Expr *)0, true);
1628 ClassImpDecl->addDecl(Ivar);
1629 IDecl->makeDeclVisibleInContext(Ivar, false);
1630 property->setPropertyIvarDecl(Ivar);
1631 return Ivar;
1632 }
1633 return 0;
1634}
1635
John McCalldadc5752010-08-24 06:29:42 +00001636ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001637 CXXScopeSpec &SS,
1638 UnqualifiedId &Id,
1639 bool HasTrailingLParen,
1640 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001641 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1642 "cannot be direct & operand and have a trailing lparen");
1643
1644 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001645 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001646
John McCall10eae182009-11-30 22:42:35 +00001647 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001648
1649 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001650 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001651 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001652 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001653
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001654 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001655 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001656 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001657
John McCalle66edc12009-11-24 19:00:30 +00001658 // C++ [temp.dep.expr]p3:
1659 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001660 // -- an identifier that was declared with a dependent type,
1661 // (note: handled after lookup)
1662 // -- a template-id that is dependent,
1663 // (note: handled in BuildTemplateIdExpr)
1664 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001665 // -- a nested-name-specifier that contains a class-name that
1666 // names a dependent type.
1667 // Determine whether this is a member of an unknown specialization;
1668 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001669 bool DependentID = false;
1670 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1671 Name.getCXXNameType()->isDependentType()) {
1672 DependentID = true;
1673 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001674 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001675 if (RequireCompleteDeclContext(SS, DC))
1676 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001677 } else {
1678 DependentID = true;
1679 }
1680 }
1681
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001682 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001683 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001684 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001685
Fariborz Jahanian86151342010-07-22 23:33:21 +00001686 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001687 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001688 LookupResult R(*this, NameInfo,
1689 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1690 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001691 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001692 // Lookup the template name again to correctly establish the context in
1693 // which it was found. This is really unfortunate as we already did the
1694 // lookup to determine that it was a template name in the first place. If
1695 // this becomes a performance hit, we can work harder to preserve those
1696 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001697 bool MemberOfUnknownSpecialization;
1698 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1699 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001700
1701 if (MemberOfUnknownSpecialization ||
1702 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1703 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1704 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001705 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001706 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001707 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregora5226932011-02-04 13:35:07 +00001709 // If the result might be in a dependent base class, this is a dependent
1710 // id-expression.
1711 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1712 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1713 TemplateArgs);
1714
John McCalle66edc12009-11-24 19:00:30 +00001715 // If this reference is in an Objective-C method, then we need to do
1716 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001717 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001718 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001719 if (E.isInvalid())
1720 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001721
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001722 if (Expr *Ex = E.takeAs<Expr>())
1723 return Owned(Ex);
1724
1725 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001726 if (getLangOptions().ObjCDefaultSynthProperties &&
1727 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001728 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001729 if (const ObjCPropertyDecl *Property =
1730 canSynthesizeProvisionalIvar(II)) {
1731 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1732 Diag(Property->getLocation(), diag::note_property_declare);
1733 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001734 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1735 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001736 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001737 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001738 // for further use, this must be set to false if in class method.
1739 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001740 }
Chris Lattner59a25942008-03-31 00:36:02 +00001741 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001742
John McCalle66edc12009-11-24 19:00:30 +00001743 if (R.isAmbiguous())
1744 return ExprError();
1745
Douglas Gregor171c45a2009-02-18 21:56:37 +00001746 // Determine whether this name might be a candidate for
1747 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001748 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001749
John McCalle66edc12009-11-24 19:00:30 +00001750 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001751 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001752 // in C90, extension in C99, forbidden in C++).
1753 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1754 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1755 if (D) R.addDecl(D);
1756 }
1757
1758 // If this name wasn't predeclared and if this is not a function
1759 // call, diagnose the problem.
1760 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001761 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001762 return ExprError();
1763
1764 assert(!R.empty() &&
1765 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001766
1767 // If we found an Objective-C instance variable, let
1768 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001769 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001770 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1771 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001772 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001773 assert(E.isInvalid() || E.get());
1774 return move(E);
1775 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001776 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
John McCalle66edc12009-11-24 19:00:30 +00001779 // This is guaranteed from this point on.
1780 assert(!R.empty() || ADL);
1781
John McCall2d74de92009-12-01 22:10:20 +00001782 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001783 // C++ [class.mfct.non-static]p3:
1784 // When an id-expression that is not part of a class member access
1785 // syntax and not used to form a pointer to member is used in the
1786 // body of a non-static member function of class X, if name lookup
1787 // resolves the name in the id-expression to a non-static non-type
1788 // member of some class C, the id-expression is transformed into a
1789 // class member access expression using (*this) as the
1790 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001791 //
1792 // But we don't actually need to do this for '&' operands if R
1793 // resolved to a function or overloaded function set, because the
1794 // expression is ill-formed if it actually works out to be a
1795 // non-static member function:
1796 //
1797 // C++ [expr.ref]p4:
1798 // Otherwise, if E1.E2 refers to a non-static member function. . .
1799 // [t]he expression can be used only as the left-hand operand of a
1800 // member function call.
1801 //
1802 // There are other safeguards against such uses, but it's important
1803 // to get this right here so that we don't end up making a
1804 // spuriously dependent expression if we're inside a dependent
1805 // instance method.
John McCall57500772009-12-16 12:17:52 +00001806 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001807 bool MightBeImplicitMember;
1808 if (!isAddressOfOperand)
1809 MightBeImplicitMember = true;
1810 else if (!SS.isEmpty())
1811 MightBeImplicitMember = false;
1812 else if (R.isOverloadedResult())
1813 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001814 else if (R.isUnresolvableResult())
1815 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001816 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001817 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1818 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001819
1820 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001821 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001822 }
1823
John McCalle66edc12009-11-24 19:00:30 +00001824 if (TemplateArgs)
1825 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001826
John McCalle66edc12009-11-24 19:00:30 +00001827 return BuildDeclarationNameExpr(SS, R, ADL);
1828}
1829
John McCall10eae182009-11-30 22:42:35 +00001830/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1831/// declaration name, generally during template instantiation.
1832/// There's a large number of things which don't need to be done along
1833/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001834ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001835Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001836 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001837 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001838 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001839 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001840
John McCall0b66eb32010-05-01 00:40:08 +00001841 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001842 return ExprError();
1843
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001844 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001845 LookupQualifiedName(R, DC);
1846
1847 if (R.isAmbiguous())
1848 return ExprError();
1849
1850 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001851 Diag(NameInfo.getLoc(), diag::err_no_member)
1852 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001853 return ExprError();
1854 }
1855
1856 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1857}
1858
1859/// LookupInObjCMethod - The parser has read a name in, and Sema has
1860/// detected that we're currently inside an ObjC method. Perform some
1861/// additional lookup.
1862///
1863/// Ideally, most of this would be done by lookup, but there's
1864/// actually quite a lot of extra work involved.
1865///
1866/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001867ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001868Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001869 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001870 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001871 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001872
John McCalle66edc12009-11-24 19:00:30 +00001873 // There are two cases to handle here. 1) scoped lookup could have failed,
1874 // in which case we should look for an ivar. 2) scoped lookup could have
1875 // found a decl, but that decl is outside the current instance method (i.e.
1876 // a global variable). In these two cases, we do a lookup for an ivar with
1877 // this name, if the lookup sucedes, we replace it our current decl.
1878
1879 // If we're in a class method, we don't normally want to look for
1880 // ivars. But if we don't find anything else, and there's an
1881 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001882 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001883
1884 bool LookForIvars;
1885 if (Lookup.empty())
1886 LookForIvars = true;
1887 else if (IsClassMethod)
1888 LookForIvars = false;
1889 else
1890 LookForIvars = (Lookup.isSingleResult() &&
1891 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001892 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001893 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001894 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001895 ObjCInterfaceDecl *ClassDeclared;
1896 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1897 // Diagnose using an ivar in a class method.
1898 if (IsClassMethod)
1899 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1900 << IV->getDeclName());
1901
1902 // If we're referencing an invalid decl, just return this as a silent
1903 // error node. The error diagnostic was already emitted on the decl.
1904 if (IV->isInvalidDecl())
1905 return ExprError();
1906
1907 // Check if referencing a field with __attribute__((deprecated)).
1908 if (DiagnoseUseOfDecl(IV, Loc))
1909 return ExprError();
1910
1911 // Diagnose the use of an ivar outside of the declaring class.
1912 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1913 ClassDeclared != IFace)
1914 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1915
1916 // FIXME: This should use a new expr for a direct reference, don't
1917 // turn this into Self->ivar, just return a BareIVarExpr or something.
1918 IdentifierInfo &II = Context.Idents.get("self");
1919 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001920 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001921 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001922 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001923 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001924 SelfName, false, false);
1925 if (SelfExpr.isInvalid())
1926 return ExprError();
1927
John Wiegley01296292011-04-08 18:41:53 +00001928 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1929 if (SelfExpr.isInvalid())
1930 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001931
John McCalle66edc12009-11-24 19:00:30 +00001932 MarkDeclarationReferenced(Loc, IV);
1933 return Owned(new (Context)
1934 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001935 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001936 }
Chris Lattner87313662010-04-12 05:10:17 +00001937 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001938 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001939 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001940 ObjCInterfaceDecl *ClassDeclared;
1941 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1942 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1943 IFace == ClassDeclared)
1944 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1945 }
1946 }
1947
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001948 if (Lookup.empty() && II && AllowBuiltinCreation) {
1949 // FIXME. Consolidate this with similar code in LookupName.
1950 if (unsigned BuiltinID = II->getBuiltinID()) {
1951 if (!(getLangOptions().CPlusPlus &&
1952 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1953 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1954 S, Lookup.isForRedeclaration(),
1955 Lookup.getNameLoc());
1956 if (D) Lookup.addDecl(D);
1957 }
1958 }
1959 }
John McCalle66edc12009-11-24 19:00:30 +00001960 // Sentinel value saying that we didn't do anything special.
1961 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001962}
John McCalld14a8642009-11-21 08:51:07 +00001963
John McCall16df1e52010-03-30 21:47:33 +00001964/// \brief Cast a base object to a member's actual type.
1965///
1966/// Logically this happens in three phases:
1967///
1968/// * First we cast from the base type to the naming class.
1969/// The naming class is the class into which we were looking
1970/// when we found the member; it's the qualifier type if a
1971/// qualifier was provided, and otherwise it's the base type.
1972///
1973/// * Next we cast from the naming class to the declaring class.
1974/// If the member we found was brought into a class's scope by
1975/// a using declaration, this is that class; otherwise it's
1976/// the class declaring the member.
1977///
1978/// * Finally we cast from the declaring class to the "true"
1979/// declaring class of the member. This conversion does not
1980/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001981ExprResult
1982Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001984 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001985 NamedDecl *Member) {
1986 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1987 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001988 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001989
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 QualType DestRecordType;
1991 QualType DestType;
1992 QualType FromRecordType;
1993 QualType FromType = From->getType();
1994 bool PointerConversions = false;
1995 if (isa<FieldDecl>(Member)) {
1996 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001997
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 if (FromType->getAs<PointerType>()) {
1999 DestType = Context.getPointerType(DestRecordType);
2000 FromRecordType = FromType->getPointeeType();
2001 PointerConversions = true;
2002 } else {
2003 DestType = DestRecordType;
2004 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002005 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002006 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2007 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002008 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002009
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002010 DestType = Method->getThisType(Context);
2011 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002012
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013 if (FromType->getAs<PointerType>()) {
2014 FromRecordType = FromType->getPointeeType();
2015 PointerConversions = true;
2016 } else {
2017 FromRecordType = FromType;
2018 DestType = DestRecordType;
2019 }
2020 } else {
2021 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002022 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002023 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002024
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002025 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002026 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002027
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002028 // If the unqualified types are the same, no conversion is necessary.
2029 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002030 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002031
John McCall16df1e52010-03-30 21:47:33 +00002032 SourceRange FromRange = From->getSourceRange();
2033 SourceLocation FromLoc = FromRange.getBegin();
2034
John McCall2536c6d2010-08-25 10:28:54 +00002035 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002036
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002037 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002038 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002039 // class name.
2040 //
2041 // If the member was a qualified name and the qualified referred to a
2042 // specific base subobject type, we'll cast to that intermediate type
2043 // first and then to the object in which the member is declared. That allows
2044 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2045 //
2046 // class Base { public: int x; };
2047 // class Derived1 : public Base { };
2048 // class Derived2 : public Base { };
2049 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2050 //
2051 // void VeryDerived::f() {
2052 // x = 17; // error: ambiguous base subobjects
2053 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2054 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002055 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002056 QualType QType = QualType(Qualifier->getAsType(), 0);
2057 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2058 assert(QType->isRecordType() && "lookup done with non-record type");
2059
2060 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2061
2062 // In C++98, the qualifier type doesn't actually have to be a base
2063 // type of the object type, in which case we just ignore it.
2064 // Otherwise build the appropriate casts.
2065 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002066 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002067 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002068 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002069 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002070
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002071 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002072 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002073 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2074 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002075
2076 FromType = QType;
2077 FromRecordType = QRecordType;
2078
2079 // If the qualifier type was the same as the destination type,
2080 // we're done.
2081 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002082 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002083 }
2084 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002085
John McCall16df1e52010-03-30 21:47:33 +00002086 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002087
John McCall16df1e52010-03-30 21:47:33 +00002088 // If we actually found the member through a using declaration, cast
2089 // down to the using declaration's type.
2090 //
2091 // Pointer equality is fine here because only one declaration of a
2092 // class ever has member declarations.
2093 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2094 assert(isa<UsingShadowDecl>(FoundDecl));
2095 QualType URecordType = Context.getTypeDeclType(
2096 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2097
2098 // We only need to do this if the naming-class to declaring-class
2099 // conversion is non-trivial.
2100 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2101 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002102 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002103 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002104 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002105 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002106
John McCall16df1e52010-03-30 21:47:33 +00002107 QualType UType = URecordType;
2108 if (PointerConversions)
2109 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002110 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2111 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002112 FromType = UType;
2113 FromRecordType = URecordType;
2114 }
2115
2116 // We don't do access control for the conversion from the
2117 // declaring class to the true declaring class.
2118 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002119 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002120
John McCallcf142162010-08-07 06:22:56 +00002121 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002122 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2123 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002124 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002125 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002126
John Wiegley01296292011-04-08 18:41:53 +00002127 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2128 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002129}
Douglas Gregor3256d042009-06-30 15:47:41 +00002130
John McCalle66edc12009-11-24 19:00:30 +00002131bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002132 const LookupResult &R,
2133 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002134 // Only when used directly as the postfix-expression of a call.
2135 if (!HasTrailingLParen)
2136 return false;
2137
2138 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002139 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002140 return false;
2141
2142 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002143 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002144 return false;
2145
2146 // Turn off ADL when we find certain kinds of declarations during
2147 // normal lookup:
2148 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2149 NamedDecl *D = *I;
2150
2151 // C++0x [basic.lookup.argdep]p3:
2152 // -- a declaration of a class member
2153 // Since using decls preserve this property, we check this on the
2154 // original decl.
John McCall57500772009-12-16 12:17:52 +00002155 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002156 return false;
2157
2158 // C++0x [basic.lookup.argdep]p3:
2159 // -- a block-scope function declaration that is not a
2160 // using-declaration
2161 // NOTE: we also trigger this for function templates (in fact, we
2162 // don't check the decl type at all, since all other decl types
2163 // turn off ADL anyway).
2164 if (isa<UsingShadowDecl>(D))
2165 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2166 else if (D->getDeclContext()->isFunctionOrMethod())
2167 return false;
2168
2169 // C++0x [basic.lookup.argdep]p3:
2170 // -- a declaration that is neither a function or a function
2171 // template
2172 // And also for builtin functions.
2173 if (isa<FunctionDecl>(D)) {
2174 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2175
2176 // But also builtin functions.
2177 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2178 return false;
2179 } else if (!isa<FunctionTemplateDecl>(D))
2180 return false;
2181 }
2182
2183 return true;
2184}
2185
2186
John McCalld14a8642009-11-21 08:51:07 +00002187/// Diagnoses obvious problems with the use of the given declaration
2188/// as an expression. This is only actually called for lookups that
2189/// were not overloaded, and it doesn't promise that the declaration
2190/// will in fact be used.
2191static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002192 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002193 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2194 return true;
2195 }
2196
2197 if (isa<ObjCInterfaceDecl>(D)) {
2198 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2199 return true;
2200 }
2201
2202 if (isa<NamespaceDecl>(D)) {
2203 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2204 return true;
2205 }
2206
2207 return false;
2208}
2209
John McCalldadc5752010-08-24 06:29:42 +00002210ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002211Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002212 LookupResult &R,
2213 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002214 // If this is a single, fully-resolved result and we don't need ADL,
2215 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002216 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002217 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2218 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002219
2220 // We only need to check the declaration if there's exactly one
2221 // result, because in the overloaded case the results can only be
2222 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002223 if (R.isSingleResult() &&
2224 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002225 return ExprError();
2226
John McCall58cc69d2010-01-27 01:50:18 +00002227 // Otherwise, just build an unresolved lookup expression. Suppress
2228 // any lookup-related diagnostics; we'll hash these out later, when
2229 // we've picked a target.
2230 R.suppressDiagnostics();
2231
John McCalld14a8642009-11-21 08:51:07 +00002232 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002233 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002234 SS.getWithLocInContext(Context),
2235 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002236 NeedsADL, R.isOverloadedResult(),
2237 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002238
2239 return Owned(ULE);
2240}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002241
John McCalld14a8642009-11-21 08:51:07 +00002242/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002243ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002244Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002245 const DeclarationNameInfo &NameInfo,
2246 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002247 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002248 assert(!isa<FunctionTemplateDecl>(D) &&
2249 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002250
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002251 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002252 if (CheckDeclInExpr(*this, Loc, D))
2253 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002254
Douglas Gregore7488b92009-12-01 16:58:18 +00002255 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2256 // Specifically diagnose references to class templates that are missing
2257 // a template argument list.
2258 Diag(Loc, diag::err_template_decl_ref)
2259 << Template << SS.getRange();
2260 Diag(Template->getLocation(), diag::note_template_decl_here);
2261 return ExprError();
2262 }
2263
2264 // Make sure that we're referring to a value.
2265 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2266 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002267 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002268 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002269 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002270 return ExprError();
2271 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002272
Douglas Gregor171c45a2009-02-18 21:56:37 +00002273 // Check whether this declaration can be used. Note that we suppress
2274 // this check when we're going to perform argument-dependent lookup
2275 // on this function name, because this might not be the function
2276 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002277 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002278 return ExprError();
2279
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002280 // Only create DeclRefExpr's for valid Decl's.
2281 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002282 return ExprError();
2283
John McCallf3a88602011-02-03 08:15:49 +00002284 // Handle members of anonymous structs and unions. If we got here,
2285 // and the reference is to a class member indirect field, then this
2286 // must be the subject of a pointer-to-member expression.
2287 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2288 if (!indirectField->isCXXClassMember())
2289 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2290 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002291
Chris Lattner2a9d9892008-10-20 05:16:36 +00002292 // If the identifier reference is inside a block, and it refers to a value
2293 // that is outside the block, create a BlockDeclRefExpr instead of a
2294 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2295 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002296 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002297 // We do not do this for things like enum constants, global variables, etc,
2298 // as they do not get snapshotted.
2299 //
John McCall351762c2011-02-07 10:33:21 +00002300 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002301 case CR_Error:
2302 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002303
John McCallc63de662011-02-02 13:00:07 +00002304 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002305 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2306 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2307
2308 case CR_CaptureByRef:
2309 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2310 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002311
2312 case CR_NoCapture: {
2313 // If this reference is not in a block or if the referenced
2314 // variable is within the block, create a normal DeclRefExpr.
2315
2316 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002317 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002318
2319 switch (D->getKind()) {
2320 // Ignore all the non-ValueDecl kinds.
2321#define ABSTRACT_DECL(kind)
2322#define VALUE(type, base)
2323#define DECL(type, base) \
2324 case Decl::type:
2325#include "clang/AST/DeclNodes.inc"
2326 llvm_unreachable("invalid value decl kind");
2327 return ExprError();
2328
2329 // These shouldn't make it here.
2330 case Decl::ObjCAtDefsField:
2331 case Decl::ObjCIvar:
2332 llvm_unreachable("forming non-member reference to ivar?");
2333 return ExprError();
2334
2335 // Enum constants are always r-values and never references.
2336 // Unresolved using declarations are dependent.
2337 case Decl::EnumConstant:
2338 case Decl::UnresolvedUsingValue:
2339 valueKind = VK_RValue;
2340 break;
2341
2342 // Fields and indirect fields that got here must be for
2343 // pointer-to-member expressions; we just call them l-values for
2344 // internal consistency, because this subexpression doesn't really
2345 // exist in the high-level semantics.
2346 case Decl::Field:
2347 case Decl::IndirectField:
2348 assert(getLangOptions().CPlusPlus &&
2349 "building reference to field in C?");
2350
2351 // These can't have reference type in well-formed programs, but
2352 // for internal consistency we do this anyway.
2353 type = type.getNonReferenceType();
2354 valueKind = VK_LValue;
2355 break;
2356
2357 // Non-type template parameters are either l-values or r-values
2358 // depending on the type.
2359 case Decl::NonTypeTemplateParm: {
2360 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2361 type = reftype->getPointeeType();
2362 valueKind = VK_LValue; // even if the parameter is an r-value reference
2363 break;
2364 }
2365
2366 // For non-references, we need to strip qualifiers just in case
2367 // the template parameter was declared as 'const int' or whatever.
2368 valueKind = VK_RValue;
2369 type = type.getUnqualifiedType();
2370 break;
2371 }
2372
2373 case Decl::Var:
2374 // In C, "extern void blah;" is valid and is an r-value.
2375 if (!getLangOptions().CPlusPlus &&
2376 !type.hasQualifiers() &&
2377 type->isVoidType()) {
2378 valueKind = VK_RValue;
2379 break;
2380 }
2381 // fallthrough
2382
2383 case Decl::ImplicitParam:
2384 case Decl::ParmVar:
2385 // These are always l-values.
2386 valueKind = VK_LValue;
2387 type = type.getNonReferenceType();
2388 break;
2389
2390 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002391 const FunctionType *fty = type->castAs<FunctionType>();
2392
2393 // If we're referring to a function with an __unknown_anytype
2394 // result type, make the entire expression __unknown_anytype.
2395 if (fty->getResultType() == Context.UnknownAnyTy) {
2396 type = Context.UnknownAnyTy;
2397 valueKind = VK_RValue;
2398 break;
2399 }
2400
John McCallf4cd4f92011-02-09 01:13:10 +00002401 // Functions are l-values in C++.
2402 if (getLangOptions().CPlusPlus) {
2403 valueKind = VK_LValue;
2404 break;
2405 }
2406
2407 // C99 DR 316 says that, if a function type comes from a
2408 // function definition (without a prototype), that type is only
2409 // used for checking compatibility. Therefore, when referencing
2410 // the function, we pretend that we don't have the full function
2411 // type.
John McCall2979fe02011-04-12 00:42:48 +00002412 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2413 isa<FunctionProtoType>(fty))
2414 type = Context.getFunctionNoProtoType(fty->getResultType(),
2415 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002416
2417 // Functions are r-values in C.
2418 valueKind = VK_RValue;
2419 break;
2420 }
2421
2422 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002423 // If we're referring to a method with an __unknown_anytype
2424 // result type, make the entire expression __unknown_anytype.
2425 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002426 if (const FunctionProtoType *proto
2427 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002428 if (proto->getResultType() == Context.UnknownAnyTy) {
2429 type = Context.UnknownAnyTy;
2430 valueKind = VK_RValue;
2431 break;
2432 }
2433
John McCallf4cd4f92011-02-09 01:13:10 +00002434 // C++ methods are l-values if static, r-values if non-static.
2435 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2436 valueKind = VK_LValue;
2437 break;
2438 }
2439 // fallthrough
2440
2441 case Decl::CXXConversion:
2442 case Decl::CXXDestructor:
2443 case Decl::CXXConstructor:
2444 valueKind = VK_RValue;
2445 break;
2446 }
2447
2448 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2449 }
2450
John McCallc63de662011-02-02 13:00:07 +00002451 }
John McCall7decc9e2010-11-18 06:31:45 +00002452
John McCall351762c2011-02-07 10:33:21 +00002453 llvm_unreachable("unknown capture result");
2454 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002455}
Chris Lattnere168f762006-11-10 05:29:30 +00002456
John McCall2979fe02011-04-12 00:42:48 +00002457ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002458 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002459
Chris Lattnere168f762006-11-10 05:29:30 +00002460 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002461 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002462 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2463 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2464 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002465 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002466
Chris Lattnera81a0272008-01-12 08:14:25 +00002467 // Pre-defined identifiers are of type char[x], where x is the length of the
2468 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002469
Anders Carlsson2fb08242009-09-08 18:24:21 +00002470 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002471 if (!currentDecl && getCurBlock())
2472 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002473 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002474 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002475 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002476 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477
Anders Carlsson0b209a82009-09-11 01:22:35 +00002478 QualType ResTy;
2479 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2480 ResTy = Context.DependentTy;
2481 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002482 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002483
Anders Carlsson0b209a82009-09-11 01:22:35 +00002484 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002485 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002486 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2487 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002488 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002489}
2490
John McCalldadc5752010-08-24 06:29:42 +00002491ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002492 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002493 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002494 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002495 if (Invalid)
2496 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002497
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002498 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002499 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002500 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002501 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002502
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002503 QualType Ty;
2504 if (!getLangOptions().CPlusPlus)
2505 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2506 else if (Literal.isWide())
2507 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002508 else if (Literal.isUTF16())
2509 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2510 else if (Literal.isUTF32())
2511 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002512 else if (Literal.isMultiChar())
2513 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002514 else
2515 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002516
Douglas Gregorfb65e592011-07-27 05:40:30 +00002517 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2518 if (Literal.isWide())
2519 Kind = CharacterLiteral::Wide;
2520 else if (Literal.isUTF16())
2521 Kind = CharacterLiteral::UTF16;
2522 else if (Literal.isUTF32())
2523 Kind = CharacterLiteral::UTF32;
2524
2525 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2526 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002527}
2528
John McCalldadc5752010-08-24 06:29:42 +00002529ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002531 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2532 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002533 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002534 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002535 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002536 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002537 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002538
Chris Lattner23b7eb62007-06-15 23:05:46 +00002539 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002540 // Add padding so that NumericLiteralParser can overread by one character.
2541 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002542 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002543
Chris Lattner67ca9252007-05-21 01:08:44 +00002544 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002545 bool Invalid = false;
2546 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2547 if (Invalid)
2548 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002549
Mike Stump11289f42009-09-09 15:08:12 +00002550 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002551 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002552 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553 return ExprError();
2554
Chris Lattner1c20a172007-08-26 03:42:43 +00002555 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002556
Chris Lattner1c20a172007-08-26 03:42:43 +00002557 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002558 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002559 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002560 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002561 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002562 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002563 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002564 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002565
2566 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2567
John McCall53b93a02009-12-24 09:08:04 +00002568 using llvm::APFloat;
2569 APFloat Val(Format);
2570
2571 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002572
2573 // Overflow is always an error, but underflow is only an error if
2574 // we underflowed to zero (APFloat reports denormals as underflow).
2575 if ((result & APFloat::opOverflow) ||
2576 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002577 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002578 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002579 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002580 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002581 APFloat::getLargest(Format).toString(buffer);
2582 } else {
John McCall62abc942010-02-26 23:35:57 +00002583 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002584 APFloat::getSmallest(Format).toString(buffer);
2585 }
2586
2587 Diag(Tok.getLocation(), diagnostic)
2588 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002589 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002590 }
2591
2592 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002593 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002594
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002595 if (Ty == Context.DoubleTy) {
2596 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002597 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002598 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2599 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002600 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002601 }
2602 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002603 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002604 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002605 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002606 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002607
Neil Boothac582c52007-08-29 22:00:19 +00002608 // long long is a C99 feature.
2609 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002610 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002611 Diag(Tok.getLocation(), diag::ext_longlong);
2612
Chris Lattner67ca9252007-05-21 01:08:44 +00002613 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002614 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002615
Chris Lattner67ca9252007-05-21 01:08:44 +00002616 if (Literal.GetIntegerValue(ResultVal)) {
2617 // If this value didn't fit into uintmax_t, warn and force to ull.
2618 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002619 Ty = Context.UnsignedLongLongTy;
2620 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002621 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002622 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 // If this value fits into a ULL, try to figure out what else it fits into
2624 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002625
Chris Lattner67ca9252007-05-21 01:08:44 +00002626 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2627 // be an unsigned int.
2628 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2629
2630 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002631 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002632 if (!Literal.isLong && !Literal.isLongLong) {
2633 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002634 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002635
Chris Lattner67ca9252007-05-21 01:08:44 +00002636 // Does it fit in a unsigned int?
2637 if (ResultVal.isIntN(IntSize)) {
2638 // Does it fit in a signed int?
2639 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002640 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002642 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002643 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002644 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002646
Chris Lattner67ca9252007-05-21 01:08:44 +00002647 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002648 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002649 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002650
Chris Lattner67ca9252007-05-21 01:08:44 +00002651 // Does it fit in a unsigned long?
2652 if (ResultVal.isIntN(LongSize)) {
2653 // Does it fit in a signed long?
2654 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002655 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002657 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002658 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002660 }
2661
Chris Lattner67ca9252007-05-21 01:08:44 +00002662 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002663 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002664 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002665
Chris Lattner67ca9252007-05-21 01:08:44 +00002666 // Does it fit in a unsigned long long?
2667 if (ResultVal.isIntN(LongLongSize)) {
2668 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002669 // To be compatible with MSVC, hex integer literals ending with the
2670 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002671 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2672 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002673 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002674 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002675 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002676 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002677 }
2678 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002679
Chris Lattner67ca9252007-05-21 01:08:44 +00002680 // If we still couldn't decide a type, we probably have something that
2681 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002687
Chris Lattner55258cf2008-05-09 05:59:00 +00002688 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002689 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002690 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002691 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002692 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002693
Chris Lattner1c20a172007-08-26 03:42:43 +00002694 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2695 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002696 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002697 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002698
2699 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002700}
2701
John McCalldadc5752010-08-24 06:29:42 +00002702ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002703 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002704 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002705 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002706}
2707
Chandler Carruth62da79c2011-05-26 08:53:12 +00002708static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2709 SourceLocation Loc,
2710 SourceRange ArgRange) {
2711 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2712 // scalar or vector data type argument..."
2713 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2714 // type (C99 6.2.5p18) or void.
2715 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2716 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2717 << T << ArgRange;
2718 return true;
2719 }
2720
2721 assert((T->isVoidType() || !T->isIncompleteType()) &&
2722 "Scalar types should always be complete");
2723 return false;
2724}
2725
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002726static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2727 SourceLocation Loc,
2728 SourceRange ArgRange,
2729 UnaryExprOrTypeTrait TraitKind) {
2730 // C99 6.5.3.4p1:
2731 if (T->isFunctionType()) {
2732 // alignof(function) is allowed as an extension.
2733 if (TraitKind == UETT_SizeOf)
2734 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2735 return false;
2736 }
2737
2738 // Allow sizeof(void)/alignof(void) as an extension.
2739 if (T->isVoidType()) {
2740 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2741 return false;
2742 }
2743
2744 return true;
2745}
2746
2747static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2748 SourceLocation Loc,
2749 SourceRange ArgRange,
2750 UnaryExprOrTypeTrait TraitKind) {
2751 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2752 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2753 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2754 << T << (TraitKind == UETT_SizeOf)
2755 << ArgRange;
2756 return true;
2757 }
2758
2759 return false;
2760}
2761
Chandler Carruth14502c22011-05-26 08:53:10 +00002762/// \brief Check the constrains on expression operands to unary type expression
2763/// and type traits.
2764///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002765/// Completes any types necessary and validates the constraints on the operand
2766/// expression. The logic mostly mirrors the type-based overload, but may modify
2767/// the expression as it completes the type for that expression through template
2768/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002769bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2770 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002771 QualType ExprTy = Op->getType();
2772
2773 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2774 // the result is the size of the referenced type."
2775 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2776 // result shall be the alignment of the referenced type."
2777 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2778 ExprTy = Ref->getPointeeType();
2779
2780 if (ExprKind == UETT_VecStep)
2781 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2782 Op->getSourceRange());
2783
2784 // Whitelist some types as extensions
2785 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2786 Op->getSourceRange(), ExprKind))
2787 return false;
2788
2789 if (RequireCompleteExprType(Op,
2790 PDiag(diag::err_sizeof_alignof_incomplete_type)
2791 << ExprKind << Op->getSourceRange(),
2792 std::make_pair(SourceLocation(), PDiag(0))))
2793 return true;
2794
2795 // Completeing the expression's type may have changed it.
2796 ExprTy = Op->getType();
2797 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2798 ExprTy = Ref->getPointeeType();
2799
2800 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2801 Op->getSourceRange(), ExprKind))
2802 return true;
2803
Nico Weber0870deb2011-06-15 02:47:03 +00002804 if (ExprKind == UETT_SizeOf) {
2805 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2806 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2807 QualType OType = PVD->getOriginalType();
2808 QualType Type = PVD->getType();
2809 if (Type->isPointerType() && OType->isArrayType()) {
2810 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2811 << Type << OType;
2812 Diag(PVD->getLocation(), diag::note_declared_at);
2813 }
2814 }
2815 }
2816 }
2817
Chandler Carruth7c430c02011-05-27 01:33:31 +00002818 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002819}
2820
2821/// \brief Check the constraints on operands to unary expression and type
2822/// traits.
2823///
2824/// This will complete any types necessary, and validate the various constraints
2825/// on those operands.
2826///
Steve Naroff71b59a92007-06-04 22:22:31 +00002827/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002828/// C99 6.3.2.1p[2-4] all state:
2829/// Except when it is the operand of the sizeof operator ...
2830///
2831/// C++ [expr.sizeof]p4
2832/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2833/// standard conversions are not applied to the operand of sizeof.
2834///
2835/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002836bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2837 SourceLocation OpLoc,
2838 SourceRange ExprRange,
2839 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002840 if (exprType->isDependentType())
2841 return false;
2842
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002843 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2844 // the result is the size of the referenced type."
2845 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2846 // result shall be the alignment of the referenced type."
2847 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2848 exprType = Ref->getPointeeType();
2849
Chandler Carruth62da79c2011-05-26 08:53:12 +00002850 if (ExprKind == UETT_VecStep)
2851 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002853 // Whitelist some types as extensions
2854 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2855 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002856 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002857
Chris Lattner62975a72009-04-24 00:30:45 +00002858 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002859 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002860 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002861 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002862
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002863 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2864 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002865 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002866
Chris Lattner62975a72009-04-24 00:30:45 +00002867 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002868}
2869
Chandler Carruth14502c22011-05-26 08:53:10 +00002870static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002871 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002872
Mike Stump11289f42009-09-09 15:08:12 +00002873 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002874 if (isa<DeclRefExpr>(E))
2875 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002876
2877 // Cannot know anything else if the expression is dependent.
2878 if (E->isTypeDependent())
2879 return false;
2880
Douglas Gregor71235ec2009-05-02 02:18:30 +00002881 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002882 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2883 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002884 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002885 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002886
2887 // Alignment of a field access is always okay, so long as it isn't a
2888 // bit-field.
2889 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002890 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002891 return false;
2892
Chandler Carruth14502c22011-05-26 08:53:10 +00002893 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002894}
2895
Chandler Carruth14502c22011-05-26 08:53:10 +00002896bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 E = E->IgnoreParens();
2898
2899 // Cannot know anything else if the expression is dependent.
2900 if (E->isTypeDependent())
2901 return false;
2902
Chandler Carruth14502c22011-05-26 08:53:10 +00002903 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002904}
2905
Douglas Gregor0950e412009-03-13 21:01:28 +00002906/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002907ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002908Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2909 SourceLocation OpLoc,
2910 UnaryExprOrTypeTrait ExprKind,
2911 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002912 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002913 return ExprError();
2914
John McCallbcd03502009-12-07 02:54:59 +00002915 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002916
Douglas Gregor0950e412009-03-13 21:01:28 +00002917 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002918 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002919 return ExprError();
2920
2921 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002922 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2923 Context.getSizeType(),
2924 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002925}
2926
2927/// \brief Build a sizeof or alignof expression given an expression
2928/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002929ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002930Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2931 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002932 ExprResult PE = CheckPlaceholderExpr(E);
2933 if (PE.isInvalid())
2934 return ExprError();
2935
2936 E = PE.get();
2937
Douglas Gregor0950e412009-03-13 21:01:28 +00002938 // Verify that the operand is valid.
2939 bool isInvalid = false;
2940 if (E->isTypeDependent()) {
2941 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002942 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002943 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002944 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002945 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002946 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002947 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002948 isInvalid = true;
2949 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002950 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002951 }
2952
2953 if (isInvalid)
2954 return ExprError();
2955
2956 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002957 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002958 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002959 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002960}
2961
Peter Collingbournee190dee2011-03-11 19:24:49 +00002962/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2963/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002964/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002965ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002966Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2967 UnaryExprOrTypeTrait ExprKind, bool isType,
2968 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002969 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002970 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002971
Sebastian Redl6f282892008-11-11 17:56:53 +00002972 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002973 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002974 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002975 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002976 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002977
Douglas Gregor0950e412009-03-13 21:01:28 +00002978 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002979 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002980 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002981}
2982
John Wiegley01296292011-04-08 18:41:53 +00002983static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002984 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002985 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002986 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002987
John McCall34376a62010-12-04 03:47:34 +00002988 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002989 if (V.get()->getObjectKind() != OK_Ordinary) {
2990 V = S.DefaultLvalueConversion(V.take());
2991 if (V.isInvalid())
2992 return QualType();
2993 }
John McCall34376a62010-12-04 03:47:34 +00002994
Chris Lattnere267f5d2007-08-26 05:39:26 +00002995 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002996 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002997 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002998
Chris Lattnere267f5d2007-08-26 05:39:26 +00002999 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003000 if (V.get()->getType()->isArithmeticType())
3001 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003002
John McCall36226622010-10-12 02:09:17 +00003003 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003004 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003005 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003006 if (PR.get() != V.get()) {
3007 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003008 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003009 }
3010
Chris Lattnere267f5d2007-08-26 05:39:26 +00003011 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003012 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003013 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003014 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003015}
3016
3017
Chris Lattnere168f762006-11-10 05:29:30 +00003018
John McCalldadc5752010-08-24 06:29:42 +00003019ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003020Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003021 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003022 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003023 switch (Kind) {
3024 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003025 case tok::plusplus: Opc = UO_PostInc; break;
3026 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003027 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003028
John McCallb268a282010-08-23 23:25:46 +00003029 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003030}
3031
John McCalldadc5752010-08-24 06:29:42 +00003032ExprResult
John McCallb268a282010-08-23 23:25:46 +00003033Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3034 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003035 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003036 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003037 if (Result.isInvalid()) return ExprError();
3038 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003039
John McCallb268a282010-08-23 23:25:46 +00003040 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003041
Douglas Gregor40412ac2008-11-19 17:17:41 +00003042 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003043 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003044 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003045 Context.DependentTy,
3046 VK_LValue, OK_Ordinary,
3047 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003048 }
3049
Mike Stump11289f42009-09-09 15:08:12 +00003050 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003051 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003052 LHSExp->getType()->isEnumeralType() ||
3053 RHSExp->getType()->isRecordType() ||
3054 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003055 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003056 }
3057
John McCallb268a282010-08-23 23:25:46 +00003058 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003059}
3060
3061
John McCalldadc5752010-08-24 06:29:42 +00003062ExprResult
John McCallb268a282010-08-23 23:25:46 +00003063Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3064 Expr *Idx, SourceLocation RLoc) {
3065 Expr *LHSExp = Base;
3066 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003067
Chris Lattner36d572b2007-07-16 00:14:47 +00003068 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003069 if (!LHSExp->getType()->getAs<VectorType>()) {
3070 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3071 if (Result.isInvalid())
3072 return ExprError();
3073 LHSExp = Result.take();
3074 }
3075 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3076 if (Result.isInvalid())
3077 return ExprError();
3078 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003079
Chris Lattner36d572b2007-07-16 00:14:47 +00003080 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003081 ExprValueKind VK = VK_LValue;
3082 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003083
Steve Naroffc1aadb12007-03-28 21:49:40 +00003084 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003085 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003086 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003087 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003088 Expr *BaseExpr, *IndexExpr;
3089 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003090 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3091 BaseExpr = LHSExp;
3092 IndexExpr = RHSExp;
3093 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003094 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003095 BaseExpr = LHSExp;
3096 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003097 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003098 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003099 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003102 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003103 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003104 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003105 BaseExpr = LHSExp;
3106 IndexExpr = RHSExp;
3107 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003108 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003109 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003110 // Handle the uncommon case of "123[Ptr]".
3111 BaseExpr = RHSExp;
3112 IndexExpr = LHSExp;
3113 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003114 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003115 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003116 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003117 VK = LHSExp->getValueKind();
3118 if (VK != VK_RValue)
3119 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003120
Chris Lattner36d572b2007-07-16 00:14:47 +00003121 // FIXME: need to deal with const...
3122 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003123 } else if (LHSTy->isArrayType()) {
3124 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003125 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003126 // wasn't promoted because of the C90 rule that doesn't
3127 // allow promoting non-lvalue arrays. Warn, then
3128 // force the promotion here.
3129 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3130 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003131 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3132 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003133 LHSTy = LHSExp->getType();
3134
3135 BaseExpr = LHSExp;
3136 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003137 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003138 } else if (RHSTy->isArrayType()) {
3139 // Same as previous, except for 123[f().a] case
3140 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3141 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003142 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3143 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003144 RHSTy = RHSExp->getType();
3145
3146 BaseExpr = RHSExp;
3147 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003148 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003149 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003150 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3151 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003152 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003153 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003154 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003155 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3156 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003157
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003158 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003159 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3160 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003161 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3162
Douglas Gregorac1fb652009-03-24 19:52:54 +00003163 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003164 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3165 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003166 // incomplete types are not object types.
3167 if (ResultType->isFunctionType()) {
3168 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3169 << ResultType << BaseExpr->getSourceRange();
3170 return ExprError();
3171 }
Mike Stump11289f42009-09-09 15:08:12 +00003172
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003173 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3174 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003175 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3176 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003177
3178 // C forbids expressions of unqualified void type from being l-values.
3179 // See IsCForbiddenLValueType.
3180 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003181 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003182 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003183 PDiag(diag::err_subscript_incomplete_type)
3184 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003185 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003186
Chris Lattner62975a72009-04-24 00:30:45 +00003187 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003188 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003189 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3190 << ResultType << BaseExpr->getSourceRange();
3191 return ExprError();
3192 }
Mike Stump11289f42009-09-09 15:08:12 +00003193
John McCall4bc41ae2010-11-18 19:01:18 +00003194 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003195 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003196
Mike Stump4e1f26a2009-02-19 03:04:26 +00003197 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003198 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003199}
3200
John McCalldadc5752010-08-24 06:29:42 +00003201ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003202 FunctionDecl *FD,
3203 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003204 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003205 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003206 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003207 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003208 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003209 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003210 return ExprError();
3211 }
3212
3213 if (Param->hasUninstantiatedDefaultArg()) {
3214 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003215
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003216 // Instantiate the expression.
3217 MultiLevelTemplateArgumentList ArgList
3218 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003219
Nico Weber44887f62010-11-29 18:19:25 +00003220 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003221 = ArgList.getInnermost();
3222 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3223 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003224
Nico Weber44887f62010-11-29 18:19:25 +00003225 ExprResult Result;
3226 {
3227 // C++ [dcl.fct.default]p5:
3228 // The names in the [default argument] expression are bound, and
3229 // the semantic constraints are checked, at the point where the
3230 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003231 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003232 Result = SubstExpr(UninstExpr, ArgList);
3233 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003234 if (Result.isInvalid())
3235 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003236
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003237 // Check the expression as an initializer for the parameter.
3238 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003239 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003240 InitializationKind Kind
3241 = InitializationKind::CreateCopy(Param->getLocation(),
3242 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3243 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003244
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003245 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3246 Result = InitSeq.Perform(*this, Entity, Kind,
3247 MultiExprArg(*this, &ResultE, 1));
3248 if (Result.isInvalid())
3249 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003250
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003251 // Build the default argument expression.
3252 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3253 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003254 }
3255
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003256 // If the default expression creates temporaries, we need to
3257 // push them to the current stack of expression temporaries so they'll
3258 // be properly destroyed.
3259 // FIXME: We should really be rebuilding the default argument with new
3260 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003261 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3262 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3263 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3264 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3265 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003266 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003267 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003268
3269 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003270 // Just mark all of the declarations in this potentially-evaluated expression
3271 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003272 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003273 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003274}
3275
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003276/// ConvertArgumentsForCall - Converts the arguments specified in
3277/// Args/NumArgs to the parameter types of the function FDecl with
3278/// function prototype Proto. Call is the call expression itself, and
3279/// Fn is the function expression. For a C++ member function, this
3280/// routine does not attempt to convert the object argument. Returns
3281/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003282bool
3283Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003284 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003285 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003286 Expr **Args, unsigned NumArgs,
3287 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003288 // Bail out early if calling a builtin with custom typechecking.
3289 // We don't need to do this in the
3290 if (FDecl)
3291 if (unsigned ID = FDecl->getBuiltinID())
3292 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3293 return false;
3294
Mike Stump4e1f26a2009-02-19 03:04:26 +00003295 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003296 // assignment, to the types of the corresponding parameter, ...
3297 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003298 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003299
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003300 // If too few arguments are available (and we don't have default
3301 // arguments for the remaining parameters), don't make the call.
3302 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003303 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3304 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003305 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003306 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003307
3308 // Emit the location of the prototype.
3309 if (FDecl && !FDecl->getBuiltinID())
3310 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3311 << FDecl;
3312
3313 return true;
3314 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003315 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003316 }
3317
3318 // If too many are passed and not variadic, error on the extras and drop
3319 // them.
3320 if (NumArgs > NumArgsInProto) {
3321 if (!Proto->isVariadic()) {
3322 Diag(Args[NumArgsInProto]->getLocStart(),
3323 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003324 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003325 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003326 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3327 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003328
3329 // Emit the location of the prototype.
3330 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003331 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3332 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003333
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003334 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003335 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003336 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003337 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003339 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003340 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003341 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3342 if (Fn->getType()->isBlockPointerType())
3343 CallType = VariadicBlock; // Block
3344 else if (isa<MemberExpr>(Fn))
3345 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003346 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003347 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003348 if (Invalid)
3349 return true;
3350 unsigned TotalNumArgs = AllArgs.size();
3351 for (unsigned i = 0; i < TotalNumArgs; ++i)
3352 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003353
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003354 return false;
3355}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003356
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3358 FunctionDecl *FDecl,
3359 const FunctionProtoType *Proto,
3360 unsigned FirstProtoArg,
3361 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003362 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003363 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003364 unsigned NumArgsInProto = Proto->getNumArgs();
3365 unsigned NumArgsToCheck = NumArgs;
3366 bool Invalid = false;
3367 if (NumArgs != NumArgsInProto)
3368 // Use default arguments for missing arguments
3369 NumArgsToCheck = NumArgsInProto;
3370 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003371 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003372 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003373 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003374
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003375 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003376 if (ArgIx < NumArgs) {
3377 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003378
Eli Friedman3164fb12009-03-22 22:00:50 +00003379 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3380 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003381 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003382 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003383 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003384
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003385 // Pass the argument
3386 ParmVarDecl *Param = 0;
3387 if (FDecl && i < FDecl->getNumParams())
3388 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003389
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003390 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003391 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003392 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3393 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003394 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003395 SourceLocation(),
3396 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003397 if (ArgE.isInvalid())
3398 return true;
3399
3400 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003401 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003402 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003403
John McCalldadc5752010-08-24 06:29:42 +00003404 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003405 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003406 if (ArgExpr.isInvalid())
3407 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003408
Anders Carlsson355933d2009-08-25 03:49:14 +00003409 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003410 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003411
3412 // Check for array bounds violations for each argument to the call. This
3413 // check only triggers warnings when the argument isn't a more complex Expr
3414 // with its own checking, such as a BinaryOperator.
3415 CheckArrayAccess(Arg);
3416
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003417 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003418 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003419
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003420 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003421 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003422
3423 // Assume that extern "C" functions with variadic arguments that
3424 // return __unknown_anytype aren't *really* variadic.
3425 if (Proto->getResultType() == Context.UnknownAnyTy &&
3426 FDecl && FDecl->isExternC()) {
3427 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3428 ExprResult arg;
3429 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3430 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3431 else
3432 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3433 Invalid |= arg.isInvalid();
3434 AllArgs.push_back(arg.take());
3435 }
3436
3437 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3438 } else {
3439 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003440 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3441 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003442 Invalid |= Arg.isInvalid();
3443 AllArgs.push_back(Arg.take());
3444 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003445 }
3446 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003447 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003448}
3449
John McCall2979fe02011-04-12 00:42:48 +00003450/// Given a function expression of unknown-any type, try to rebuild it
3451/// to have a function type.
3452static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3453
Steve Naroff83895f72007-09-16 03:34:24 +00003454/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003455/// This provides the location of the left/right parens and a list of comma
3456/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003457ExprResult
John McCallb268a282010-08-23 23:25:46 +00003458Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003459 MultiExprArg args, SourceLocation RParenLoc,
3460 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003461 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003462
3463 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003464 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003465 if (Result.isInvalid()) return ExprError();
3466 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003467
John McCallb268a282010-08-23 23:25:46 +00003468 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003469
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003470 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003471 // If this is a pseudo-destructor expression, build the call immediately.
3472 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3473 if (NumArgs > 0) {
3474 // Pseudo-destructor calls should not have any arguments.
3475 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003476 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003477 SourceRange(Args[0]->getLocStart(),
3478 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003479
Douglas Gregorad8a3362009-09-04 17:36:40 +00003480 NumArgs = 0;
3481 }
Mike Stump11289f42009-09-09 15:08:12 +00003482
Douglas Gregorad8a3362009-09-04 17:36:40 +00003483 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003484 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003485 }
Mike Stump11289f42009-09-09 15:08:12 +00003486
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003487 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003488 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003489 // FIXME: Will need to cache the results of name lookup (including ADL) in
3490 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003491 bool Dependent = false;
3492 if (Fn->isTypeDependent())
3493 Dependent = true;
3494 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3495 Dependent = true;
3496
Peter Collingbourne41f85462011-02-09 21:07:24 +00003497 if (Dependent) {
3498 if (ExecConfig) {
3499 return Owned(new (Context) CUDAKernelCallExpr(
3500 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3501 Context.DependentTy, VK_RValue, RParenLoc));
3502 } else {
3503 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3504 Context.DependentTy, VK_RValue,
3505 RParenLoc));
3506 }
3507 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003508
3509 // Determine whether this is a call to an object (C++ [over.call.object]).
3510 if (Fn->getType()->isRecordType())
3511 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003512 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003513
John McCall2979fe02011-04-12 00:42:48 +00003514 if (Fn->getType() == Context.UnknownAnyTy) {
3515 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3516 if (result.isInvalid()) return ExprError();
3517 Fn = result.take();
3518 }
3519
John McCall0009fcc2011-04-26 20:42:42 +00003520 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003521 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003522 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003523 }
John McCall0009fcc2011-04-26 20:42:42 +00003524 }
John McCall10eae182009-11-30 22:42:35 +00003525
John McCall0009fcc2011-04-26 20:42:42 +00003526 // Check for overloaded calls. This can happen even in C due to extensions.
3527 if (Fn->getType() == Context.OverloadTy) {
3528 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3529
3530 // We aren't supposed to apply this logic if there's an '&' involved.
3531 if (!find.IsAddressOfOperand) {
3532 OverloadExpr *ovl = find.Expression;
3533 if (isa<UnresolvedLookupExpr>(ovl)) {
3534 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3535 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3536 RParenLoc, ExecConfig);
3537 } else {
John McCall2d74de92009-12-01 22:10:20 +00003538 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003539 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003540 }
3541 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003542 }
3543
Douglas Gregore254f902009-02-04 00:32:51 +00003544 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003545
Eli Friedmane14b1992009-12-26 03:35:45 +00003546 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003547
John McCall57500772009-12-16 12:17:52 +00003548 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003549 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3550 if (UnOp->getOpcode() == UO_AddrOf)
3551 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3552
John McCall57500772009-12-16 12:17:52 +00003553 if (isa<DeclRefExpr>(NakedFn))
3554 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003555 else if (isa<MemberExpr>(NakedFn))
3556 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003557
Peter Collingbourne41f85462011-02-09 21:07:24 +00003558 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3559 ExecConfig);
3560}
3561
3562ExprResult
3563Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3564 MultiExprArg execConfig, SourceLocation GGGLoc) {
3565 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3566 if (!ConfigDecl)
3567 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3568 << "cudaConfigureCall");
3569 QualType ConfigQTy = ConfigDecl->getType();
3570
3571 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3572 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3573
3574 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003575}
3576
Tanya Lattner55808c12011-06-04 00:47:47 +00003577/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3578///
3579/// __builtin_astype( value, dst type )
3580///
3581ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3582 SourceLocation BuiltinLoc,
3583 SourceLocation RParenLoc) {
3584 ExprValueKind VK = VK_RValue;
3585 ExprObjectKind OK = OK_Ordinary;
3586 QualType DstTy = GetTypeFromParser(destty);
3587 QualType SrcTy = expr->getType();
3588 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3589 return ExprError(Diag(BuiltinLoc,
3590 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003591 << DstTy
3592 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003593 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003594 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3595 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003596}
3597
John McCall57500772009-12-16 12:17:52 +00003598/// BuildResolvedCallExpr - Build a call to a resolved expression,
3599/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003600/// unary-convert to an expression of function-pointer or
3601/// block-pointer type.
3602///
3603/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003604ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003605Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3606 SourceLocation LParenLoc,
3607 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003608 SourceLocation RParenLoc,
3609 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003610 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3611
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003612 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003613 ExprResult Result = UsualUnaryConversions(Fn);
3614 if (Result.isInvalid())
3615 return ExprError();
3616 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003617
Chris Lattner08464942007-12-28 05:29:59 +00003618 // Make the call expr early, before semantic checks. This guarantees cleanup
3619 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003620 CallExpr *TheCall;
3621 if (Config) {
3622 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3623 cast<CallExpr>(Config),
3624 Args, NumArgs,
3625 Context.BoolTy,
3626 VK_RValue,
3627 RParenLoc);
3628 } else {
3629 TheCall = new (Context) CallExpr(Context, Fn,
3630 Args, NumArgs,
3631 Context.BoolTy,
3632 VK_RValue,
3633 RParenLoc);
3634 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003635
John McCallbebede42011-02-26 05:39:39 +00003636 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3637
3638 // Bail out early if calling a builtin with custom typechecking.
3639 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3640 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3641
John McCall31996342011-04-07 08:22:57 +00003642 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003643 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003644 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003645 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3646 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003647 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003648 if (FuncT == 0)
3649 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3650 << Fn->getType() << Fn->getSourceRange());
3651 } else if (const BlockPointerType *BPT =
3652 Fn->getType()->getAs<BlockPointerType>()) {
3653 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3654 } else {
John McCall31996342011-04-07 08:22:57 +00003655 // Handle calls to expressions of unknown-any type.
3656 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003657 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003658 if (rewrite.isInvalid()) return ExprError();
3659 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003660 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003661 goto retry;
3662 }
3663
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003664 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3665 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003666 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003667
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003668 if (getLangOptions().CUDA) {
3669 if (Config) {
3670 // CUDA: Kernel calls must be to global functions
3671 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3672 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3673 << FDecl->getName() << Fn->getSourceRange());
3674
3675 // CUDA: Kernel function must have 'void' return type
3676 if (!FuncT->getResultType()->isVoidType())
3677 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3678 << Fn->getType() << Fn->getSourceRange());
3679 }
3680 }
3681
Eli Friedman3164fb12009-03-22 22:00:50 +00003682 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003683 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003684 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003685 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003686 return ExprError();
3687
Chris Lattner08464942007-12-28 05:29:59 +00003688 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003689 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003690 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003691
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003692 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003693 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003694 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003695 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003696 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003697 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003698
Douglas Gregord8e97de2009-04-02 15:37:10 +00003699 if (FDecl) {
3700 // Check if we have too few/too many template arguments, based
3701 // on our knowledge of the function definition.
3702 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003703 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003704 const FunctionProtoType *Proto
3705 = Def->getType()->getAs<FunctionProtoType>();
3706 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003707 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3708 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003709 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003710
3711 // If the function we're calling isn't a function prototype, but we have
3712 // a function prototype from a prior declaratiom, use that prototype.
3713 if (!FDecl->hasPrototype())
3714 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003715 }
3716
Steve Naroff0b661582007-08-28 23:30:39 +00003717 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003718 for (unsigned i = 0; i != NumArgs; i++) {
3719 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003720
3721 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003722 InitializedEntity Entity
3723 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003724 Proto->getArgType(i),
3725 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003726 ExprResult ArgE = PerformCopyInitialization(Entity,
3727 SourceLocation(),
3728 Owned(Arg));
3729 if (ArgE.isInvalid())
3730 return true;
3731
3732 Arg = ArgE.takeAs<Expr>();
3733
3734 } else {
John Wiegley01296292011-04-08 18:41:53 +00003735 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3736
3737 if (ArgE.isInvalid())
3738 return true;
3739
3740 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003741 }
3742
Douglas Gregor83025412010-10-26 05:45:40 +00003743 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3744 Arg->getType(),
3745 PDiag(diag::err_call_incomplete_argument)
3746 << Arg->getSourceRange()))
3747 return ExprError();
3748
Chris Lattner08464942007-12-28 05:29:59 +00003749 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003750 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003751 }
Chris Lattner08464942007-12-28 05:29:59 +00003752
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003753 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3754 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003755 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3756 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003757
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003758 // Check for sentinels
3759 if (NDecl)
3760 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003761
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003762 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003763 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003764 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003765 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003766
John McCallbebede42011-02-26 05:39:39 +00003767 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003768 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003769 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003770 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003771 return ExprError();
3772 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003773
John McCallb268a282010-08-23 23:25:46 +00003774 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003775}
3776
John McCalldadc5752010-08-24 06:29:42 +00003777ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003778Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003779 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003780 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003781 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003782 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003783
3784 TypeSourceInfo *TInfo;
3785 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3786 if (!TInfo)
3787 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3788
John McCallb268a282010-08-23 23:25:46 +00003789 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003790}
3791
John McCalldadc5752010-08-24 06:29:42 +00003792ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003793Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003794 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003795 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003796
Eli Friedman37a186d2008-05-20 05:22:08 +00003797 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003798 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3799 PDiag(diag::err_illegal_decl_array_incomplete_type)
3800 << SourceRange(LParenLoc,
3801 literalExpr->getSourceRange().getEnd())))
3802 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003803 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003804 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3805 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003806 } else if (!literalType->isDependentType() &&
3807 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003808 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003809 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003810 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003811 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003812
Douglas Gregor85dabae2009-12-16 01:38:02 +00003813 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003814 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003815 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003816 = InitializationKind::CreateCStyleCast(LParenLoc,
3817 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003818 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003819 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003820 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003821 &literalType);
3822 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003823 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003824 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003825
Chris Lattner79413952008-12-04 23:50:19 +00003826 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003827 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003828 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003829 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003830 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003831
John McCall7decc9e2010-11-18 06:31:45 +00003832 // In C, compound literals are l-values for some reason.
3833 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3834
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003835 return MaybeBindToTemporary(
3836 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3837 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003838}
3839
John McCalldadc5752010-08-24 06:29:42 +00003840ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003841Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003842 SourceLocation RBraceLoc) {
3843 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003844 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003845
Steve Naroff30d242c2007-09-15 18:49:24 +00003846 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003847 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003848
Ted Kremenekac034612010-04-13 23:39:13 +00003849 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3850 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003851 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003852 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003853}
3854
John McCalld7646252010-11-14 08:17:51 +00003855/// Prepares for a scalar cast, performing all the necessary stages
3856/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003857static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003858 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3859 // Also, callers should have filtered out the invalid cases with
3860 // pointers. Everything else should be possible.
3861
John Wiegley01296292011-04-08 18:41:53 +00003862 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003863 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003864 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003865
John McCall8cb679e2010-11-15 09:13:47 +00003866 switch (SrcTy->getScalarTypeKind()) {
3867 case Type::STK_MemberPointer:
3868 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003869
John McCall8cb679e2010-11-15 09:13:47 +00003870 case Type::STK_Pointer:
3871 switch (DestTy->getScalarTypeKind()) {
3872 case Type::STK_Pointer:
3873 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003874 CK_AnyPointerToObjCPointerCast :
3875 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003876 case Type::STK_Bool:
3877 return CK_PointerToBoolean;
3878 case Type::STK_Integral:
3879 return CK_PointerToIntegral;
3880 case Type::STK_Floating:
3881 case Type::STK_FloatingComplex:
3882 case Type::STK_IntegralComplex:
3883 case Type::STK_MemberPointer:
3884 llvm_unreachable("illegal cast from pointer");
3885 }
3886 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003887
John McCall8cb679e2010-11-15 09:13:47 +00003888 case Type::STK_Bool: // casting from bool is like casting from an integer
3889 case Type::STK_Integral:
3890 switch (DestTy->getScalarTypeKind()) {
3891 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003892 if (Src.get()->isNullPointerConstant(S.Context,
3893 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003894 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003895 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003896 case Type::STK_Bool:
3897 return CK_IntegralToBoolean;
3898 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003899 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003900 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003901 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003902 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003903 Src = S.ImpCastExprToType(Src.take(),
3904 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003905 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003906 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003907 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003908 Src = S.ImpCastExprToType(Src.take(),
3909 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003910 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003911 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003912 case Type::STK_MemberPointer:
3913 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003914 }
3915 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003916
John McCall8cb679e2010-11-15 09:13:47 +00003917 case Type::STK_Floating:
3918 switch (DestTy->getScalarTypeKind()) {
3919 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003920 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003921 case Type::STK_Bool:
3922 return CK_FloatingToBoolean;
3923 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003924 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003925 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003926 Src = S.ImpCastExprToType(Src.take(),
3927 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003928 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003929 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003930 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003931 Src = S.ImpCastExprToType(Src.take(),
3932 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003933 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003934 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003935 case Type::STK_Pointer:
3936 llvm_unreachable("valid float->pointer cast?");
3937 case Type::STK_MemberPointer:
3938 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003939 }
3940 break;
3941
John McCall8cb679e2010-11-15 09:13:47 +00003942 case Type::STK_FloatingComplex:
3943 switch (DestTy->getScalarTypeKind()) {
3944 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003945 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003946 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003947 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003948 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003949 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003950 if (S.Context.hasSameType(ET, DestTy))
3951 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003952 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003953 return CK_FloatingCast;
3954 }
John McCall8cb679e2010-11-15 09:13:47 +00003955 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003956 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003957 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003958 Src = S.ImpCastExprToType(Src.take(),
3959 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003960 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003961 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003962 case Type::STK_Pointer:
3963 llvm_unreachable("valid complex float->pointer cast?");
3964 case Type::STK_MemberPointer:
3965 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003966 }
3967 break;
3968
John McCall8cb679e2010-11-15 09:13:47 +00003969 case Type::STK_IntegralComplex:
3970 switch (DestTy->getScalarTypeKind()) {
3971 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003972 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003973 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003974 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003975 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003976 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003977 if (S.Context.hasSameType(ET, DestTy))
3978 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003979 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003980 return CK_IntegralCast;
3981 }
John McCall8cb679e2010-11-15 09:13:47 +00003982 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003983 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003984 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003985 Src = S.ImpCastExprToType(Src.take(),
3986 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003987 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003988 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003989 case Type::STK_Pointer:
3990 llvm_unreachable("valid complex int->pointer cast?");
3991 case Type::STK_MemberPointer:
3992 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003993 }
3994 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003995 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003996
John McCalld7646252010-11-14 08:17:51 +00003997 llvm_unreachable("Unhandled scalar cast");
3998 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003999}
4000
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004001/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00004002ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
4003 QualType castType, Expr *castExpr,
4004 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00004005 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00004006 if (castExpr->getType() == Context.UnknownAnyTy)
4007 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
4008
Sebastian Redl9f831db2009-07-25 15:41:38 +00004009 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004010 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00004011 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004012 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004013 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004014
John McCall3aef3d82011-04-10 19:13:55 +00004015 assert(!castExpr->getType()->isPlaceholderType());
4016
John McCall7decc9e2010-11-18 06:31:45 +00004017 // We only support r-value casts in C.
4018 VK = VK_RValue;
4019
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004020 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4021 // type needs to be scalar.
4022 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004023 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00004024 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4025 if (castExprRes.isInvalid())
4026 return ExprError();
4027 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004028
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004029 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004030 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00004031 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004032 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004033
John Wiegley01296292011-04-08 18:41:53 +00004034 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4035 if (castExprRes.isInvalid())
4036 return ExprError();
4037 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004038
Eli Friedmane98194d2010-07-17 20:43:49 +00004039 if (RequireCompleteType(TyR.getBegin(), castType,
4040 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004041 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004042
Anders Carlssonef918ac2009-10-16 02:35:04 +00004043 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004044 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004045 (castType->isStructureType() || castType->isUnionType())) {
4046 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004047 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004048 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4049 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004050 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00004051 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004052 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004053
Anders Carlsson525b76b2009-10-16 02:48:28 +00004054 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004055 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004056 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004057 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004058 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004059 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004060 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004061 castExpr->getType()) &&
4062 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004063 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4064 << castExpr->getSourceRange();
4065 break;
4066 }
4067 }
John Wiegley01296292011-04-08 18:41:53 +00004068 if (Field == FieldEnd) {
4069 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004070 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004071 return ExprError();
4072 }
John McCalle3027922010-08-25 11:45:40 +00004073 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004074 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004076
Anders Carlsson525b76b2009-10-16 02:48:28 +00004077 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004078 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004079 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004080 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004081 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004082
John McCalld7646252010-11-14 08:17:51 +00004083 // The type we're casting to is known to be a scalar or vector.
4084
4085 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004086 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004087 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004088 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004089 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004090 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004091 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004092 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004093
4094 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004095 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004096
Anton Yartsev28ccef72011-03-27 09:32:40 +00004097 if (castType->isVectorType()) {
4098 if (castType->getAs<VectorType>()->getVectorKind() ==
4099 VectorType::AltiVecVector &&
4100 (castExpr->getType()->isIntegerType() ||
4101 castExpr->getType()->isFloatingType())) {
4102 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004103 return Owned(castExpr);
4104 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4105 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004106 } else
John Wiegley01296292011-04-08 18:41:53 +00004107 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004108 }
John Wiegley01296292011-04-08 18:41:53 +00004109 if (castExpr->getType()->isVectorType()) {
4110 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4111 return ExprError();
4112 else
4113 return Owned(castExpr);
4114 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004115
John McCalld7646252010-11-14 08:17:51 +00004116 // The source and target types are both scalars, i.e.
4117 // - arithmetic types (fundamental, enum, and complex)
4118 // - all kinds of pointers
4119 // Note that member pointers were filtered out with C++, above.
4120
John Wiegley01296292011-04-08 18:41:53 +00004121 if (isa<ObjCSelectorExpr>(castExpr)) {
4122 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4123 return ExprError();
4124 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004125
John McCalld7646252010-11-14 08:17:51 +00004126 // If either type is a pointer, the other type has to be either an
4127 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004128 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004129 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004130 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004131 castExprType->isArithmeticType()) {
4132 Diag(castExpr->getLocStart(),
4133 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004134 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004135 return ExprError();
4136 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004137 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004138 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4139 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004140 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004141 return ExprError();
4142 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004143 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004144
John McCall31168b02011-06-15 23:02:42 +00004145 if (getLangOptions().ObjCAutoRefCount) {
4146 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4147 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4148 castType, castExpr, CCK_CStyleCast);
4149
4150 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4151 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4152 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4153 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4154 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4155 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4156 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4157 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004158 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004159 << castExprType << castType << AA_Casting
4160 << castExpr->getSourceRange();
4161
4162 return ExprError();
4163 }
4164 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004165 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004166 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4167 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004168 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004169 << castExprType << castType
4170 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004171 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004172 }
4173 }
4174
John Wiegley01296292011-04-08 18:41:53 +00004175 castExprRes = Owned(castExpr);
4176 Kind = PrepareScalarCast(*this, castExprRes, castType);
4177 if (castExprRes.isInvalid())
4178 return ExprError();
4179 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004180
John McCalld7646252010-11-14 08:17:51 +00004181 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004182 CheckCastAlign(castExpr, castType, TyR);
4183
John Wiegley01296292011-04-08 18:41:53 +00004184 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004185}
4186
Anders Carlsson525b76b2009-10-16 02:48:28 +00004187bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004188 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004189 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004190
Anders Carlssonde71adf2007-11-27 05:51:55 +00004191 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004192 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004193 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004194 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004195 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004196 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004197 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004198 } else
4199 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004200 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004201 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004202
John McCalle3027922010-08-25 11:45:40 +00004203 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004204 return false;
4205}
4206
John Wiegley01296292011-04-08 18:41:53 +00004207ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4208 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004209 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004210
Anders Carlsson43d70f82009-10-16 05:23:41 +00004211 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004212
Nate Begemanc8961a42009-06-27 22:05:55 +00004213 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4214 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004215 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004216 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4217 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004218 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004219 return ExprError();
4220 }
John McCalle3027922010-08-25 11:45:40 +00004221 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004222 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004223 }
4224
Nate Begemanbd956c42009-06-28 02:36:38 +00004225 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004226 // conversion will take place first from scalar to elt type, and then
4227 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004228 if (SrcTy->isPointerType())
4229 return Diag(R.getBegin(),
4230 diag::err_invalid_conversion_between_vector_and_scalar)
4231 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004232
4233 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004234 ExprResult CastExprRes = Owned(CastExpr);
4235 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4236 if (CastExprRes.isInvalid())
4237 return ExprError();
4238 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004239
John McCalle3027922010-08-25 11:45:40 +00004240 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004241 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004242}
4243
John McCalldadc5752010-08-24 06:29:42 +00004244ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004245Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4246 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004247 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004248 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004249 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004250
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004251 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4252 if (D.isInvalidType())
4253 return ExprError();
4254
4255 if (getLangOptions().CPlusPlus) {
4256 // Check that there are no default arguments (C++ only).
4257 CheckExtraCXXDefaultArguments(D);
4258 }
4259
4260 QualType castType = castTInfo->getType();
4261 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004262
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004263 bool isVectorLiteral = false;
4264
4265 // Check for an altivec or OpenCL literal,
4266 // i.e. all the elements are integer constants.
4267 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4268 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4269 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4270 if (PLE && PLE->getNumExprs() == 0) {
4271 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4272 return ExprError();
4273 }
4274 if (PE || PLE->getNumExprs() == 1) {
4275 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4276 if (!E->getType()->isVectorType())
4277 isVectorLiteral = true;
4278 }
4279 else
4280 isVectorLiteral = true;
4281 }
4282
4283 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4284 // then handle it as such.
4285 if (isVectorLiteral)
4286 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4287
Nate Begeman5ec4b312009-08-10 23:49:36 +00004288 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004289 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4290 // sequence of BinOp comma operators.
4291 if (isa<ParenListExpr>(castExpr)) {
4292 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4293 if (Result.isInvalid()) return ExprError();
4294 castExpr = Result.take();
4295 }
John McCallebe54742010-01-15 18:56:44 +00004296
John McCallb268a282010-08-23 23:25:46 +00004297 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004298}
4299
John McCalldadc5752010-08-24 06:29:42 +00004300ExprResult
John McCallebe54742010-01-15 18:56:44 +00004301Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004302 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004303 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004304 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004305 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004306 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004307 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4308 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004309 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004310 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004311 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004312
Richard Trieucfc491d2011-08-02 04:35:43 +00004313 return Owned(CStyleCastExpr::Create(
4314 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4315 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004316}
4317
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004318ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4319 SourceLocation RParenLoc, Expr *E,
4320 TypeSourceInfo *TInfo) {
4321 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4322 "Expected paren or paren list expression");
4323
4324 Expr **exprs;
4325 unsigned numExprs;
4326 Expr *subExpr;
4327 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4328 exprs = PE->getExprs();
4329 numExprs = PE->getNumExprs();
4330 } else {
4331 subExpr = cast<ParenExpr>(E)->getSubExpr();
4332 exprs = &subExpr;
4333 numExprs = 1;
4334 }
4335
4336 QualType Ty = TInfo->getType();
4337 assert(Ty->isVectorType() && "Expected vector type");
4338
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004339 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004340 const VectorType *VTy = Ty->getAs<VectorType>();
4341 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4342
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004343 // '(...)' form of vector initialization in AltiVec: the number of
4344 // initializers must be one or must match the size of the vector.
4345 // If a single value is specified in the initializer then it will be
4346 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004347 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004348 // The number of initializers must be one or must match the size of the
4349 // vector. If a single value is specified in the initializer then it will
4350 // be replicated to all the components of the vector
4351 if (numExprs == 1) {
4352 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4353 ExprResult Literal = Owned(exprs[0]);
4354 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4355 PrepareScalarCast(*this, Literal, ElemTy));
4356 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4357 }
4358 else if (numExprs < numElems) {
4359 Diag(E->getExprLoc(),
4360 diag::err_incorrect_number_of_vector_initializers);
4361 return ExprError();
4362 }
4363 else
4364 for (unsigned i = 0, e = numExprs; i != e; ++i)
4365 initExprs.push_back(exprs[i]);
4366 }
Tanya Lattner83559382011-07-15 23:07:01 +00004367 else {
4368 // For OpenCL, when the number of initializers is a single value,
4369 // it will be replicated to all components of the vector.
4370 if (getLangOptions().OpenCL &&
4371 VTy->getVectorKind() == VectorType::GenericVector &&
4372 numExprs == 1) {
4373 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4374 ExprResult Literal = Owned(exprs[0]);
4375 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4376 PrepareScalarCast(*this, Literal, ElemTy));
4377 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4378 }
4379
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004380 for (unsigned i = 0, e = numExprs; i != e; ++i)
4381 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004382 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004383 // FIXME: This means that pretty-printing the final AST will produce curly
4384 // braces instead of the original commas.
4385 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4386 &initExprs[0],
4387 initExprs.size(), RParenLoc);
4388 initE->setType(Ty);
4389 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4390}
4391
Nate Begeman5ec4b312009-08-10 23:49:36 +00004392/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4393/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004394ExprResult
John McCallb268a282010-08-23 23:25:46 +00004395Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004396 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4397 if (!E)
4398 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004399
John McCalldadc5752010-08-24 06:29:42 +00004400 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004401
Nate Begeman5ec4b312009-08-10 23:49:36 +00004402 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004403 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4404 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004405
John McCallb268a282010-08-23 23:25:46 +00004406 if (Result.isInvalid()) return ExprError();
4407
4408 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004409}
4410
John McCalldadc5752010-08-24 06:29:42 +00004411ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004412 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004413 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004414 unsigned nexprs = Val.size();
4415 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004416 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4417 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004418 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004419 expr = new (Context) ParenExpr(L, R, exprs[0]);
4420 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004421 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4422 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004423 return Owned(expr);
4424}
4425
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004426/// \brief Emit a specialized diagnostic when one expression is a null pointer
4427/// constant and the other is not a pointer.
4428bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4429 SourceLocation QuestionLoc) {
4430 Expr *NullExpr = LHS;
4431 Expr *NonPointerExpr = RHS;
4432 Expr::NullPointerConstantKind NullKind =
4433 NullExpr->isNullPointerConstant(Context,
4434 Expr::NPC_ValueDependentIsNotNull);
4435
4436 if (NullKind == Expr::NPCK_NotNull) {
4437 NullExpr = RHS;
4438 NonPointerExpr = LHS;
4439 NullKind =
4440 NullExpr->isNullPointerConstant(Context,
4441 Expr::NPC_ValueDependentIsNotNull);
4442 }
4443
4444 if (NullKind == Expr::NPCK_NotNull)
4445 return false;
4446
4447 if (NullKind == Expr::NPCK_ZeroInteger) {
4448 // In this case, check to make sure that we got here from a "NULL"
4449 // string in the source code.
4450 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004451 SourceLocation loc = NullExpr->getExprLoc();
4452 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004453 return false;
4454 }
4455
4456 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4457 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4458 << NonPointerExpr->getType() << DiagType
4459 << NonPointerExpr->getSourceRange();
4460 return true;
4461}
4462
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004463/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4464/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004465/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004466QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4467 ExprResult &RHS, ExprValueKind &VK,
4468 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004469 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004470
John McCall3aef3d82011-04-10 19:13:55 +00004471 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004472 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004473 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004474
John McCall3aef3d82011-04-10 19:13:55 +00004475 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004476 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004477 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004478
Sebastian Redl1a99f442009-04-16 17:51:27 +00004479 // C++ is sufficiently different to merit its own checker.
4480 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004481 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004482
4483 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004484 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004485
John Wiegley01296292011-04-08 18:41:53 +00004486 Cond = UsualUnaryConversions(Cond.take());
4487 if (Cond.isInvalid())
4488 return QualType();
4489 LHS = UsualUnaryConversions(LHS.take());
4490 if (LHS.isInvalid())
4491 return QualType();
4492 RHS = UsualUnaryConversions(RHS.take());
4493 if (RHS.isInvalid())
4494 return QualType();
4495
4496 QualType CondTy = Cond.get()->getType();
4497 QualType LHSTy = LHS.get()->getType();
4498 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004499
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004500 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004501 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004502 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4503 // Throw an error if its not either.
4504 if (getLangOptions().OpenCL) {
4505 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004506 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004507 diag::err_typecheck_cond_expect_scalar_or_vector)
4508 << CondTy;
4509 return QualType();
4510 }
4511 }
4512 else {
John Wiegley01296292011-04-08 18:41:53 +00004513 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004514 << CondTy;
4515 return QualType();
4516 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004517 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004518
Chris Lattnere2949f42008-01-06 22:42:25 +00004519 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004520 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004521 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004522
Nate Begemanabb5a732010-09-20 22:41:17 +00004523 // OpenCL: If the condition is a vector, and both operands are scalar,
4524 // attempt to implicity convert them to the vector type to act like the
4525 // built in select.
4526 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4527 // Both operands should be of scalar type.
4528 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004529 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004530 << CondTy;
4531 return QualType();
4532 }
4533 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004534 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004535 << CondTy;
4536 return QualType();
4537 }
4538 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004539 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4540 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004541 }
4542
Chris Lattnere2949f42008-01-06 22:42:25 +00004543 // If both operands have arithmetic type, do the usual arithmetic conversions
4544 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004545 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4546 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004547 if (LHS.isInvalid() || RHS.isInvalid())
4548 return QualType();
4549 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004550 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004551
Chris Lattnere2949f42008-01-06 22:42:25 +00004552 // If both operands are the same structure or union type, the result is that
4553 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004554 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4555 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004556 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004557 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004558 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004559 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004560 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004561 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004562
Chris Lattnere2949f42008-01-06 22:42:25 +00004563 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004564 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004565 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4566 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004567 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4568 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004569 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004570 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4571 << LHS.get()->getSourceRange();
4572 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4573 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004574 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004575 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004576 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4577 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004578 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004579 RHS.get()->isNullPointerConstant(Context,
4580 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004581 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004582 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004583 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004584 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004585 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004586 LHS.get()->isNullPointerConstant(Context,
4587 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00004588 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004589 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004590 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004591
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004592 // All objective-c pointer type analysis is done here.
4593 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4594 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004595 if (LHS.isInvalid() || RHS.isInvalid())
4596 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004597 if (!compositeType.isNull())
4598 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004599
4600
Steve Naroff05efa972009-07-01 14:36:47 +00004601 // Handle block pointer types.
4602 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4603 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4604 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4605 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004606 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4607 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004608 return destType;
4609 }
4610 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004611 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4612 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004613 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004614 }
Steve Naroff05efa972009-07-01 14:36:47 +00004615 // We have 2 block pointer types.
4616 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4617 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004618 return LHSTy;
4619 }
Steve Naroff05efa972009-07-01 14:36:47 +00004620 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004621 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4622 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004623
Steve Naroff05efa972009-07-01 14:36:47 +00004624 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4625 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004626 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004627 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4628 << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004629 // In this situation, we assume void* type. No especially good
4630 // reason, but this is what gcc does, and we do have to pick
4631 // to get a consistent AST.
4632 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004633 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4634 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004635 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004636 }
Steve Naroff05efa972009-07-01 14:36:47 +00004637 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004638 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4639 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004640 return LHSTy;
4641 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004642
Steve Naroff05efa972009-07-01 14:36:47 +00004643 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4644 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4645 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004646 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4647 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004648
4649 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4650 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4651 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004652 QualType destPointee
4653 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004654 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004655 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004656 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004657 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004658 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004659 return destType;
4660 }
4661 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004662 QualType destPointee
4663 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004664 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004665 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004666 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004667 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004668 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004669 return destType;
4670 }
4671
4672 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4673 // Two identical pointer types are always compatible.
4674 return LHSTy;
4675 }
4676 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4677 rhptee.getUnqualifiedType())) {
4678 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004679 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4680 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004681 // In this situation, we assume void* type. No especially good
4682 // reason, but this is what gcc does, and we do have to pick
4683 // to get a consistent AST.
4684 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004685 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4686 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004687 return incompatTy;
4688 }
4689 // The pointer types are compatible.
4690 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4691 // differently qualified versions of compatible types, the result type is
4692 // a pointer to an appropriately qualified version of the *composite*
4693 // type.
4694 // FIXME: Need to calculate the composite type.
4695 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004696 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4697 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004698 return LHSTy;
4699 }
Mike Stump11289f42009-09-09 15:08:12 +00004700
John McCalle84af4e2010-11-13 01:35:44 +00004701 // GCC compatibility: soften pointer/integer mismatch. Note that
4702 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004703 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4704 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004705 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4706 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004707 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004708 return RHSTy;
4709 }
4710 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4711 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004712 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4713 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004714 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004715 return LHSTy;
4716 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004717
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004718 // Emit a better diagnostic if one of the expressions is a null pointer
4719 // constant and the other is not a pointer type. In this case, the user most
4720 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004721 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004722 return QualType();
4723
Chris Lattnere2949f42008-01-06 22:42:25 +00004724 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004725 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004726 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4727 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004728 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004729}
4730
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004731/// FindCompositeObjCPointerType - Helper method to find composite type of
4732/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004733QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004734 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004735 QualType LHSTy = LHS.get()->getType();
4736 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004737
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004738 // Handle things like Class and struct objc_class*. Here we case the result
4739 // to the pseudo-builtin, because that will be implicitly cast back to the
4740 // redefinition type if an attempt is made to access its fields.
4741 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004742 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004743 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004744 return LHSTy;
4745 }
4746 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004747 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004748 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 return RHSTy;
4750 }
4751 // And the same for struct objc_object* / id
4752 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004753 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004754 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004755 return LHSTy;
4756 }
4757 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004758 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004759 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004760 return RHSTy;
4761 }
4762 // And the same for struct objc_selector* / SEL
4763 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004764 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004765 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004766 return LHSTy;
4767 }
4768 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004769 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004770 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004771 return RHSTy;
4772 }
4773 // Check constraints for Objective-C object pointers types.
4774 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004775
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004776 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4777 // Two identical object pointer types are always compatible.
4778 return LHSTy;
4779 }
4780 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4781 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4782 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004783
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004784 // If both operands are interfaces and either operand can be
4785 // assigned to the other, use that type as the composite
4786 // type. This allows
4787 // xxx ? (A*) a : (B*) b
4788 // where B is a subclass of A.
4789 //
4790 // Additionally, as for assignment, if either type is 'id'
4791 // allow silent coercion. Finally, if the types are
4792 // incompatible then make sure to use 'id' as the composite
4793 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004794
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004795 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4796 // It could return the composite type.
4797 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4798 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4799 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4800 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4801 } else if ((LHSTy->isObjCQualifiedIdType() ||
4802 RHSTy->isObjCQualifiedIdType()) &&
4803 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4804 // Need to handle "id<xx>" explicitly.
4805 // GCC allows qualified id and any Objective-C type to devolve to
4806 // id. Currently localizing to here until clear this should be
4807 // part of ObjCQualifiedIdTypesAreCompatible.
4808 compositeType = Context.getObjCIdType();
4809 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4810 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004811 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004812 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4813 ;
4814 else {
4815 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4816 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004817 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004818 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004819 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4820 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004821 return incompatTy;
4822 }
4823 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004824 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4825 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004826 return compositeType;
4827 }
4828 // Check Objective-C object pointer types and 'void *'
4829 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4830 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4831 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4832 QualType destPointee
4833 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4834 QualType destType = Context.getPointerType(destPointee);
4835 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004836 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004837 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004838 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004839 return destType;
4840 }
4841 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4842 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4843 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4844 QualType destPointee
4845 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4846 QualType destType = Context.getPointerType(destPointee);
4847 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004848 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004850 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004851 return destType;
4852 }
4853 return QualType();
4854}
4855
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004856/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004857/// ParenRange in parentheses.
4858static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004859 const PartialDiagnostic &Note,
4860 SourceRange ParenRange) {
4861 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4862 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4863 EndLoc.isValid()) {
4864 Self.Diag(Loc, Note)
4865 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4866 << FixItHint::CreateInsertion(EndLoc, ")");
4867 } else {
4868 // We can't display the parentheses, so just show the bare note.
4869 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004870 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004871}
4872
4873static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4874 return Opc >= BO_Mul && Opc <= BO_Shr;
4875}
4876
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004877/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4878/// expression, either using a built-in or overloaded operator,
4879/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4880static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4881 Expr **RHS) {
4882 E = E->IgnoreParenImpCasts();
4883 E = E->IgnoreConversionOperator();
4884 E = E->IgnoreParenImpCasts();
4885
4886 // Built-in binary operator.
4887 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4888 if (IsArithmeticOp(OP->getOpcode())) {
4889 *Opcode = OP->getOpcode();
4890 *RHS = OP->getRHS();
4891 return true;
4892 }
4893 }
4894
4895 // Overloaded operator.
4896 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4897 if (Call->getNumArgs() != 2)
4898 return false;
4899
4900 // Make sure this is really a binary operator that is safe to pass into
4901 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4902 OverloadedOperatorKind OO = Call->getOperator();
4903 if (OO < OO_Plus || OO > OO_Arrow)
4904 return false;
4905
4906 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4907 if (IsArithmeticOp(OpKind)) {
4908 *Opcode = OpKind;
4909 *RHS = Call->getArg(1);
4910 return true;
4911 }
4912 }
4913
4914 return false;
4915}
4916
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004917static bool IsLogicOp(BinaryOperatorKind Opc) {
4918 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4919}
4920
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004921/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4922/// or is a logical expression such as (x==y) which has int type, but is
4923/// commonly interpreted as boolean.
4924static bool ExprLooksBoolean(Expr *E) {
4925 E = E->IgnoreParenImpCasts();
4926
4927 if (E->getType()->isBooleanType())
4928 return true;
4929 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4930 return IsLogicOp(OP->getOpcode());
4931 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4932 return OP->getOpcode() == UO_LNot;
4933
4934 return false;
4935}
4936
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004937/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4938/// and binary operator are mixed in a way that suggests the programmer assumed
4939/// the conditional operator has higher precedence, for example:
4940/// "int x = a + someBinaryCondition ? 1 : 2".
4941static void DiagnoseConditionalPrecedence(Sema &Self,
4942 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004943 Expr *Condition,
4944 Expr *LHS,
4945 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004946 BinaryOperatorKind CondOpcode;
4947 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004948
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004949 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004950 return;
4951 if (!ExprLooksBoolean(CondRHS))
4952 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004953
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004954 // The condition is an arithmetic binary expression, with a right-
4955 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004956
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004957 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004958 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004959 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004960
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004961 SuggestParentheses(Self, OpLoc,
4962 Self.PDiag(diag::note_precedence_conditional_silence)
4963 << BinaryOperator::getOpcodeStr(CondOpcode),
4964 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004965
4966 SuggestParentheses(Self, OpLoc,
4967 Self.PDiag(diag::note_precedence_conditional_first),
4968 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004969}
4970
Steve Naroff83895f72007-09-16 03:34:24 +00004971/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004972/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004973ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004974 SourceLocation ColonLoc,
4975 Expr *CondExpr, Expr *LHSExpr,
4976 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004977 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4978 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004979 OpaqueValueExpr *opaqueValue = 0;
4980 Expr *commonExpr = 0;
4981 if (LHSExpr == 0) {
4982 commonExpr = CondExpr;
4983
4984 // We usually want to apply unary conversions *before* saving, except
4985 // in the special case of a C++ l-value conditional.
4986 if (!(getLangOptions().CPlusPlus
4987 && !commonExpr->isTypeDependent()
4988 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4989 && commonExpr->isGLValue()
4990 && commonExpr->isOrdinaryOrBitFieldObject()
4991 && RHSExpr->isOrdinaryOrBitFieldObject()
4992 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004993 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4994 if (commonRes.isInvalid())
4995 return ExprError();
4996 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004997 }
4998
4999 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5000 commonExpr->getType(),
5001 commonExpr->getValueKind(),
5002 commonExpr->getObjectKind());
5003 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005004 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005005
John McCall7decc9e2010-11-18 06:31:45 +00005006 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005007 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005008 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5009 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005010 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005011 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5012 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005013 return ExprError();
5014
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005015 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5016 RHS.get());
5017
John McCallc07a0c72011-02-17 10:25:35 +00005018 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005019 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5020 LHS.take(), ColonLoc,
5021 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005022
5023 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005024 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005025 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5026 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005027}
5028
John McCallaba90822011-01-31 23:13:11 +00005029// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005030// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005031// routine is it effectively iqnores the qualifiers on the top level pointee.
5032// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5033// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005034static Sema::AssignConvertType
5035checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5036 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5037 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005038
Steve Naroff1f4d7272007-05-11 04:00:31 +00005039 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005040 const Type *lhptee, *rhptee;
5041 Qualifiers lhq, rhq;
5042 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5043 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044
John McCallaba90822011-01-31 23:13:11 +00005045 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005046
5047 // C99 6.5.16.1p1: This following citation is common to constraints
5048 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5049 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005050 Qualifiers lq;
5051
John McCall31168b02011-06-15 23:02:42 +00005052 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5053 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5054 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5055 // Ignore lifetime for further calculation.
5056 lhq.removeObjCLifetime();
5057 rhq.removeObjCLifetime();
5058 }
5059
John McCall4fff8f62011-02-01 00:10:29 +00005060 if (!lhq.compatiblyIncludes(rhq)) {
5061 // Treat address-space mismatches as fatal. TODO: address subspaces
5062 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5063 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5064
John McCall31168b02011-06-15 23:02:42 +00005065 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005066 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005067 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5068 .compatiblyIncludes(
5069 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005070 && (lhptee->isVoidType() || rhptee->isVoidType()))
5071 ; // keep old
5072
John McCall31168b02011-06-15 23:02:42 +00005073 // Treat lifetime mismatches as fatal.
5074 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5075 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5076
John McCall4fff8f62011-02-01 00:10:29 +00005077 // For GCC compatibility, other qualifier mismatches are treated
5078 // as still compatible in C.
5079 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5080 }
Steve Naroff3f597292007-05-11 22:18:03 +00005081
Mike Stump4e1f26a2009-02-19 03:04:26 +00005082 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5083 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005084 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005085 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005086 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005087 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005088
Chris Lattner0a788432008-01-03 22:56:36 +00005089 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005090 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005091 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005092 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005093
Chris Lattner0a788432008-01-03 22:56:36 +00005094 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005095 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005096 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005097
5098 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005099 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005100 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005101 }
John McCall4fff8f62011-02-01 00:10:29 +00005102
Mike Stump4e1f26a2009-02-19 03:04:26 +00005103 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005104 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005105 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5106 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005107 // Check if the pointee types are compatible ignoring the sign.
5108 // We explicitly check for char so that we catch "char" vs
5109 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005110 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005111 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005112 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005113 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005114
Chris Lattnerec3a1562009-10-17 20:33:28 +00005115 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005116 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005117 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005118 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005119
John McCall4fff8f62011-02-01 00:10:29 +00005120 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005121 // Types are compatible ignoring the sign. Qualifier incompatibility
5122 // takes priority over sign incompatibility because the sign
5123 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005124 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005125 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005126
John McCallaba90822011-01-31 23:13:11 +00005127 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005128 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005129
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005130 // If we are a multi-level pointer, it's possible that our issue is simply
5131 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5132 // the eventual target type is the same and the pointers have the same
5133 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005134 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005135 do {
John McCall4fff8f62011-02-01 00:10:29 +00005136 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5137 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005138 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005139
John McCall4fff8f62011-02-01 00:10:29 +00005140 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005141 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005142 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005143
Eli Friedman80160bd2009-03-22 23:59:44 +00005144 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005145 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005146 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005147 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005148}
5149
John McCallaba90822011-01-31 23:13:11 +00005150/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005151/// block pointer types are compatible or whether a block and normal pointer
5152/// are compatible. It is more restrict than comparing two function pointer
5153// types.
John McCallaba90822011-01-31 23:13:11 +00005154static Sema::AssignConvertType
5155checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5156 QualType rhsType) {
5157 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5158 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5159
Steve Naroff081c7422008-09-04 15:10:53 +00005160 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005161
Steve Naroff081c7422008-09-04 15:10:53 +00005162 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005163 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5164 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
John McCallaba90822011-01-31 23:13:11 +00005166 // In C++, the types have to match exactly.
5167 if (S.getLangOptions().CPlusPlus)
5168 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005169
John McCallaba90822011-01-31 23:13:11 +00005170 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005171
Steve Naroff081c7422008-09-04 15:10:53 +00005172 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005173 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5174 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005175
John McCallaba90822011-01-31 23:13:11 +00005176 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5177 return Sema::IncompatibleBlockPointer;
5178
Steve Naroff081c7422008-09-04 15:10:53 +00005179 return ConvTy;
5180}
5181
John McCallaba90822011-01-31 23:13:11 +00005182/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005183/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005184static Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005185checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5186 QualType rhsType) {
John McCallaba90822011-01-31 23:13:11 +00005187 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5188 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5189
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005190 if (lhsType->isObjCBuiltinType()) {
5191 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005192 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5193 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005194 return Sema::IncompatiblePointer;
5195 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005196 }
5197 if (rhsType->isObjCBuiltinType()) {
5198 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005199 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5200 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005201 return Sema::IncompatiblePointer;
5202 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005203 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005204 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005205 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005206 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005207 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005208
John McCallaba90822011-01-31 23:13:11 +00005209 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5210 return Sema::CompatiblePointerDiscardsQualifiers;
5211
5212 if (S.Context.typesAreCompatible(lhsType, rhsType))
5213 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005214 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005215 return Sema::IncompatibleObjCQualifiedId;
5216 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005217}
5218
John McCall29600e12010-11-16 02:32:08 +00005219Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005220Sema::CheckAssignmentConstraints(SourceLocation Loc,
5221 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005222 // Fake up an opaque expression. We don't actually care about what
5223 // cast operations are required, so if CheckAssignmentConstraints
5224 // adds casts to this they'll be wasted, but fortunately that doesn't
5225 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005226 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005227 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005228 CastKind K = CK_Invalid;
5229
5230 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5231}
5232
Mike Stump4e1f26a2009-02-19 03:04:26 +00005233/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5234/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005235/// pointers. Here are some objectionable examples that GCC considers warnings:
5236///
5237/// int a, *pint;
5238/// short *pshort;
5239/// struct foo *pfoo;
5240///
5241/// pint = pshort; // warning: assignment from incompatible pointer type
5242/// a = pint; // warning: assignment makes integer from pointer without a cast
5243/// pint = a; // warning: assignment makes pointer from integer without a cast
5244/// pint = pfoo; // warning: assignment from incompatible pointer type
5245///
5246/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005247/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005248///
John McCall8cb679e2010-11-15 09:13:47 +00005249/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005250Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005251Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005252 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005253 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005254 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005255
Chris Lattnera52c2f22008-01-04 23:18:45 +00005256 // Get canonical types. We're not formatting these types, just comparing
5257 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005258 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5259 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005260
John McCalle5255932011-01-31 22:28:28 +00005261 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005262 if (lhsType == rhsType) {
5263 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005264 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005265 }
5266
Douglas Gregor6b754842008-10-28 00:22:11 +00005267 // If the left-hand side is a reference type, then we are in a
5268 // (rare!) case where we've allowed the use of references in C,
5269 // e.g., as a parameter type in a built-in function. In this case,
5270 // just make sure that the type referenced is compatible with the
5271 // right-hand side type. The caller is responsible for adjusting
5272 // lhsType so that the resulting expression does not have reference
5273 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005274 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005275 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5276 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005277 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005278 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005279 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005280 }
John McCalle5255932011-01-31 22:28:28 +00005281
Nate Begemanbd956c42009-06-28 02:36:38 +00005282 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5283 // to the same ExtVector type.
5284 if (lhsType->isExtVectorType()) {
5285 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005286 return Incompatible;
5287 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005288 // CK_VectorSplat does T -> vector T, so first cast to the
5289 // element type.
5290 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5291 if (elType != rhsType) {
5292 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005293 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005294 }
5295 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005296 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005297 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005298 }
Mike Stump11289f42009-09-09 15:08:12 +00005299
John McCalle5255932011-01-31 22:28:28 +00005300 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005301 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005302 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005303 // Allow assignments of an AltiVec vector type to an equivalent GCC
5304 // vector type and vice versa
5305 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5306 Kind = CK_BitCast;
5307 return Compatible;
5308 }
5309
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005310 // If we are allowing lax vector conversions, and LHS and RHS are both
5311 // vectors, the total size only needs to be the same. This is a bitcast;
5312 // no bits are changed but the result type is different.
5313 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005314 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005315 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005316 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005317 }
Chris Lattner881a2122008-01-04 23:32:24 +00005318 }
5319 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005320 }
Eli Friedman3360d892008-05-30 18:07:22 +00005321
John McCalle5255932011-01-31 22:28:28 +00005322 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005323 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005324 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005325 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005326 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005327 }
Eli Friedman3360d892008-05-30 18:07:22 +00005328
John McCalle5255932011-01-31 22:28:28 +00005329 // Conversions to normal pointers.
5330 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5331 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005332 if (isa<PointerType>(rhsType)) {
5333 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005334 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005335 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005336
John McCalle5255932011-01-31 22:28:28 +00005337 // int -> T*
5338 if (rhsType->isIntegerType()) {
5339 Kind = CK_IntegralToPointer; // FIXME: null?
5340 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005341 }
John McCalle5255932011-01-31 22:28:28 +00005342
5343 // C pointers are not compatible with ObjC object pointers,
5344 // with two exceptions:
5345 if (isa<ObjCObjectPointerType>(rhsType)) {
5346 // - conversions to void*
5347 if (lhsPointer->getPointeeType()->isVoidType()) {
5348 Kind = CK_AnyPointerToObjCPointerCast;
5349 return Compatible;
5350 }
5351
5352 // - conversions from 'Class' to the redefinition type
5353 if (rhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005354 Context.hasSameType(lhsType,
5355 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005356 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005357 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005358 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005359
John McCalle5255932011-01-31 22:28:28 +00005360 Kind = CK_BitCast;
5361 return IncompatiblePointer;
5362 }
5363
5364 // U^ -> void*
5365 if (rhsType->getAs<BlockPointerType>()) {
5366 if (lhsPointer->getPointeeType()->isVoidType()) {
5367 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005368 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005369 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005370 }
John McCalle5255932011-01-31 22:28:28 +00005371
Steve Naroff081c7422008-09-04 15:10:53 +00005372 return Incompatible;
5373 }
5374
John McCalle5255932011-01-31 22:28:28 +00005375 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005376 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005377 // U^ -> T^
5378 if (rhsType->isBlockPointerType()) {
5379 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005380 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005381 }
5382
5383 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005384 if (rhsType->isIntegerType()) {
5385 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005386 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005387 }
5388
John McCalle5255932011-01-31 22:28:28 +00005389 // id -> T^
5390 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5391 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005392 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005393 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005394
John McCalle5255932011-01-31 22:28:28 +00005395 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005396 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005397 if (RHSPT->getPointeeType()->isVoidType()) {
5398 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005399 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005400 }
John McCall8cb679e2010-11-15 09:13:47 +00005401
Chris Lattnera52c2f22008-01-04 23:18:45 +00005402 return Incompatible;
5403 }
5404
John McCalle5255932011-01-31 22:28:28 +00005405 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005406 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005407 // A* -> B*
5408 if (rhsType->isObjCObjectPointerType()) {
5409 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005410 Sema::AssignConvertType result =
5411 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5412 if (getLangOptions().ObjCAutoRefCount &&
5413 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005414 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5415 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005416 return result;
John McCalle5255932011-01-31 22:28:28 +00005417 }
5418
5419 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005420 if (rhsType->isIntegerType()) {
5421 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005422 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005423 }
5424
John McCalle5255932011-01-31 22:28:28 +00005425 // In general, C pointers are not compatible with ObjC object pointers,
5426 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005427 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005428 // - conversions from 'void*'
5429 if (rhsType->isVoidPointerType()) {
5430 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005431 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005432 }
5433
5434 // - conversions to 'Class' from its redefinition type
5435 if (lhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005436 Context.hasSameType(rhsType,
5437 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005438 Kind = CK_BitCast;
5439 return Compatible;
5440 }
5441
5442 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005443 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005444 }
John McCalle5255932011-01-31 22:28:28 +00005445
5446 // T^ -> A*
5447 if (rhsType->isBlockPointerType()) {
5448 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005449 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005450 }
5451
Steve Naroff7cae42b2009-07-10 23:34:53 +00005452 return Incompatible;
5453 }
John McCalle5255932011-01-31 22:28:28 +00005454
5455 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005456 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005457 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005458 if (lhsType == Context.BoolTy) {
5459 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005460 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005461 }
Eli Friedman3360d892008-05-30 18:07:22 +00005462
John McCalle5255932011-01-31 22:28:28 +00005463 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005464 if (lhsType->isIntegerType()) {
5465 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005466 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005467 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005468
Chris Lattnera52c2f22008-01-04 23:18:45 +00005469 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005470 }
John McCalle5255932011-01-31 22:28:28 +00005471
5472 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005473 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005474 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005475 if (lhsType == Context.BoolTy) {
5476 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005477 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005478 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005479
John McCalle5255932011-01-31 22:28:28 +00005480 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005481 if (lhsType->isIntegerType()) {
5482 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005483 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005484 }
5485
Steve Naroff7cae42b2009-07-10 23:34:53 +00005486 return Incompatible;
5487 }
Eli Friedman3360d892008-05-30 18:07:22 +00005488
John McCalle5255932011-01-31 22:28:28 +00005489 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005490 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005491 if (Context.typesAreCompatible(lhsType, rhsType)) {
5492 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005493 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005494 }
Bill Wendling216423b2007-05-30 06:30:29 +00005495 }
John McCalle5255932011-01-31 22:28:28 +00005496
Steve Naroff98cf3e92007-06-06 18:38:38 +00005497 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005498}
5499
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005500/// \brief Constructs a transparent union from an expression that is
5501/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005502static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5503 ExprResult &EResult, QualType UnionType,
5504 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005505 // Build an initializer list that designates the appropriate member
5506 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005507 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005508 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005509 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005510 SourceLocation());
5511 Initializer->setType(UnionType);
5512 Initializer->setInitializedFieldInUnion(Field);
5513
5514 // Build a compound literal constructing a value of the transparent
5515 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005516 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005517 EResult = S.Owned(
5518 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5519 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005520}
5521
5522Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005523Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5524 ExprResult &rExpr) {
John Wiegley01296292011-04-08 18:41:53 +00005525 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005526
Mike Stump11289f42009-09-09 15:08:12 +00005527 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005528 // transparent_union GCC extension.
5529 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005530 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005531 return Incompatible;
5532
5533 // The field to initialize within the transparent union.
5534 RecordDecl *UD = UT->getDecl();
5535 FieldDecl *InitField = 0;
5536 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005537 for (RecordDecl::field_iterator it = UD->field_begin(),
5538 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005539 it != itend; ++it) {
5540 if (it->getType()->isPointerType()) {
5541 // If the transparent union contains a pointer type, we allow:
5542 // 1) void pointer
5543 // 2) null pointer constant
5544 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005545 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005546 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005547 InitField = *it;
5548 break;
5549 }
Mike Stump11289f42009-09-09 15:08:12 +00005550
John Wiegley01296292011-04-08 18:41:53 +00005551 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005552 Expr::NPC_ValueDependentIsNull)) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005553 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5554 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005555 InitField = *it;
5556 break;
5557 }
5558 }
5559
John McCall8cb679e2010-11-15 09:13:47 +00005560 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005561 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005562 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005563 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005564 InitField = *it;
5565 break;
5566 }
5567 }
5568
5569 if (!InitField)
5570 return Incompatible;
5571
John Wiegley01296292011-04-08 18:41:53 +00005572 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005573 return Compatible;
5574}
5575
Chris Lattner9bad62c2008-01-04 18:04:52 +00005576Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005577Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005578 if (getLangOptions().CPlusPlus) {
5579 if (!lhsType->isRecordType()) {
5580 // C++ 5.17p3: If the left operand is not of class type, the
5581 // expression is implicitly converted (C++ 4) to the
5582 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005583 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5584 lhsType.getUnqualifiedType(),
5585 AA_Assigning);
5586 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005587 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005588 Sema::AssignConvertType result = Compatible;
5589 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005590 !CheckObjCARCUnavailableWeakConversion(lhsType,
5591 rExpr.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005592 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005593 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005594 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005595 }
5596
5597 // FIXME: Currently, we fall through and treat C++ classes like C
5598 // structures.
John McCall34376a62010-12-04 03:47:34 +00005599 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005600
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005601 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5602 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005603 if ((lhsType->isPointerType() ||
5604 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005605 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005606 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005607 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005608 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005609 return Compatible;
5610 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005611
Chris Lattnere6dcd502007-10-16 02:55:40 +00005612 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005613 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005614 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005615 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005616 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005617 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005618 if (!lhsType->isReferenceType()) {
5619 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5620 if (rExpr.isInvalid())
5621 return Incompatible;
5622 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005623
John McCall8cb679e2010-11-15 09:13:47 +00005624 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005625 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005626 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005627
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005628 // C99 6.5.16.1p2: The value of the right operand is converted to the
5629 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005630 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5631 // so that we can use references in built-in functions even in C.
5632 // The getNonReferenceType() call makes sure that the resulting expression
5633 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005634 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieucfc491d2011-08-02 04:35:43 +00005635 rExpr = ImpCastExprToType(rExpr.take(),
5636 lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005637 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005638}
5639
Richard Trieucfc491d2011-08-02 04:35:43 +00005640QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5641 ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005642 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005643 << lex.get()->getType() << rex.get()->getType()
5644 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005645 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005646}
5647
Eli Friedman1408bc92011-06-23 18:10:35 +00005648QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5649 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005650 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005651 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005652 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005653 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005654 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005655 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005656
Nate Begeman191a6b12008-07-14 18:02:46 +00005657 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005658 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005659 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005660
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005661 // Handle the case of equivalent AltiVec and GCC vector types
5662 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5663 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005664 if (lhsType->isExtVectorType()) {
5665 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5666 return lhsType;
5667 }
5668
5669 if (!isCompAssign)
5670 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005671 return rhsType;
5672 }
5673
Eli Friedman1408bc92011-06-23 18:10:35 +00005674 if (getLangOptions().LaxVectorConversions &&
5675 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5676 // If we are allowing lax vector conversions, and LHS and RHS are both
5677 // vectors, the total size only needs to be the same. This is a
5678 // bitcast; no bits are changed but the result type is different.
5679 // FIXME: Should we really be allowing this?
5680 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5681 return lhsType;
5682 }
5683
Nate Begemanbd956c42009-06-28 02:36:38 +00005684 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5685 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5686 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005687 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005688 swapped = true;
5689 std::swap(rex, lex);
5690 std::swap(rhsType, lhsType);
5691 }
Mike Stump11289f42009-09-09 15:08:12 +00005692
Nate Begeman886448d2009-06-28 19:12:57 +00005693 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005694 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005695 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005696 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005697 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5698 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005699 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005700 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005701 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005702 if (swapped) std::swap(rex, lex);
5703 return lhsType;
5704 }
5705 }
5706 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5707 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005708 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5709 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005710 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005711 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005712 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005713 if (swapped) std::swap(rex, lex);
5714 return lhsType;
5715 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005716 }
5717 }
Mike Stump11289f42009-09-09 15:08:12 +00005718
Nate Begeman886448d2009-06-28 19:12:57 +00005719 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005720 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005721 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005722 << lex.get()->getType() << rex.get()->getType()
5723 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005724 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005725}
5726
Richard Trieucfc491d2011-08-02 04:35:43 +00005727QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5728 SourceLocation Loc,
5729 bool isCompAssign, bool isDiv) {
5730 if (lex.get()->getType()->isVectorType() ||
5731 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005732 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005733
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005734 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005735 if (lex.isInvalid() || rex.isInvalid())
5736 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005737
John Wiegley01296292011-04-08 18:41:53 +00005738 if (!lex.get()->getType()->isArithmeticType() ||
5739 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005740 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005741
Chris Lattnerfaa54172010-01-12 21:23:57 +00005742 // Check for division by zero.
5743 if (isDiv &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005744 rex.get()->isNullPointerConstant(Context,
5745 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005746 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieucfc491d2011-08-02 04:35:43 +00005747 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005748
Chris Lattnerfaa54172010-01-12 21:23:57 +00005749 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005750}
5751
Chris Lattnerfaa54172010-01-12 21:23:57 +00005752QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005753 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005754 if (lex.get()->getType()->isVectorType() ||
5755 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005756 if (lex.get()->getType()->hasIntegerRepresentation() &&
5757 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005758 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005759 return InvalidOperands(Loc, lex, rex);
5760 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005761
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005762 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005763 if (lex.isInvalid() || rex.isInvalid())
5764 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005765
Richard Trieucfc491d2011-08-02 04:35:43 +00005766 if (!lex.get()->getType()->isIntegerType() ||
5767 !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005768 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005769
Chris Lattnerfaa54172010-01-12 21:23:57 +00005770 // Check for remainder by zero.
Richard Trieucfc491d2011-08-02 04:35:43 +00005771 if (rex.get()->isNullPointerConstant(Context,
5772 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005773 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5774 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005775
Chris Lattnerfaa54172010-01-12 21:23:57 +00005776 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005777}
5778
Chandler Carruthc9332212011-06-27 08:02:19 +00005779/// \brief Diagnose invalid arithmetic on two void pointers.
5780static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5781 Expr *LHS, Expr *RHS) {
5782 S.Diag(Loc, S.getLangOptions().CPlusPlus
5783 ? diag::err_typecheck_pointer_arith_void_type
5784 : diag::ext_gnu_void_ptr)
5785 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5786}
5787
5788/// \brief Diagnose invalid arithmetic on a void pointer.
5789static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5790 Expr *Pointer) {
5791 S.Diag(Loc, S.getLangOptions().CPlusPlus
5792 ? diag::err_typecheck_pointer_arith_void_type
5793 : diag::ext_gnu_void_ptr)
5794 << 0 /* one pointer */ << Pointer->getSourceRange();
5795}
5796
5797/// \brief Diagnose invalid arithmetic on two function pointers.
5798static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5799 Expr *LHS, Expr *RHS) {
5800 assert(LHS->getType()->isAnyPointerType());
5801 assert(RHS->getType()->isAnyPointerType());
5802 S.Diag(Loc, S.getLangOptions().CPlusPlus
5803 ? diag::err_typecheck_pointer_arith_function_type
5804 : diag::ext_gnu_ptr_func_arith)
5805 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5806 // We only show the second type if it differs from the first.
5807 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5808 RHS->getType())
5809 << RHS->getType()->getPointeeType()
5810 << LHS->getSourceRange() << RHS->getSourceRange();
5811}
5812
5813/// \brief Diagnose invalid arithmetic on a function pointer.
5814static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5815 Expr *Pointer) {
5816 assert(Pointer->getType()->isAnyPointerType());
5817 S.Diag(Loc, S.getLangOptions().CPlusPlus
5818 ? diag::err_typecheck_pointer_arith_function_type
5819 : diag::ext_gnu_ptr_func_arith)
5820 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5821 << 0 /* one pointer, so only one type */
5822 << Pointer->getSourceRange();
5823}
5824
5825/// \brief Check the validity of an arithmetic pointer operand.
5826///
5827/// If the operand has pointer type, this code will check for pointer types
5828/// which are invalid in arithmetic operations. These will be diagnosed
5829/// appropriately, including whether or not the use is supported as an
5830/// extension.
5831///
5832/// \returns True when the operand is valid to use (even if as an extension).
5833static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5834 Expr *Operand) {
5835 if (!Operand->getType()->isAnyPointerType()) return true;
5836
5837 QualType PointeeTy = Operand->getType()->getPointeeType();
5838 if (PointeeTy->isVoidType()) {
5839 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5840 return !S.getLangOptions().CPlusPlus;
5841 }
5842 if (PointeeTy->isFunctionType()) {
5843 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5844 return !S.getLangOptions().CPlusPlus;
5845 }
5846
5847 if ((Operand->getType()->isPointerType() &&
5848 !Operand->getType()->isDependentType()) ||
5849 Operand->getType()->isObjCObjectPointerType()) {
5850 QualType PointeeTy = Operand->getType()->getPointeeType();
5851 if (S.RequireCompleteType(
5852 Loc, PointeeTy,
5853 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5854 << PointeeTy << Operand->getSourceRange()))
5855 return false;
5856 }
5857
5858 return true;
5859}
5860
5861/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5862/// operands.
5863///
5864/// This routine will diagnose any invalid arithmetic on pointer operands much
5865/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5866/// for emitting a single diagnostic even for operations where both LHS and RHS
5867/// are (potentially problematic) pointers.
5868///
5869/// \returns True when the operand is valid to use (even if as an extension).
5870static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5871 Expr *LHS, Expr *RHS) {
5872 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5873 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5874 if (!isLHSPointer && !isRHSPointer) return true;
5875
5876 QualType LHSPointeeTy, RHSPointeeTy;
5877 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5878 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5879
5880 // Check for arithmetic on pointers to incomplete types.
5881 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5882 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5883 if (isLHSVoidPtr || isRHSVoidPtr) {
5884 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5885 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5886 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5887
5888 return !S.getLangOptions().CPlusPlus;
5889 }
5890
5891 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5892 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5893 if (isLHSFuncPtr || isRHSFuncPtr) {
5894 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5895 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5896 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5897
5898 return !S.getLangOptions().CPlusPlus;
5899 }
5900
5901 Expr *Operands[] = { LHS, RHS };
5902 for (unsigned i = 0; i < 2; ++i) {
5903 Expr *Operand = Operands[i];
5904 if ((Operand->getType()->isPointerType() &&
5905 !Operand->getType()->isDependentType()) ||
5906 Operand->getType()->isObjCObjectPointerType()) {
5907 QualType PointeeTy = Operand->getType()->getPointeeType();
5908 if (S.RequireCompleteType(
5909 Loc, PointeeTy,
5910 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5911 << PointeeTy << Operand->getSourceRange()))
5912 return false;
5913 }
5914 }
5915 return true;
5916}
5917
Chris Lattnerfaa54172010-01-12 21:23:57 +00005918QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005919 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005920 if (lex.get()->getType()->isVectorType() ||
5921 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005922 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005923 if (CompLHSTy) *CompLHSTy = compType;
5924 return compType;
5925 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005926
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005927 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005928 if (lex.isInvalid() || rex.isInvalid())
5929 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005930
Steve Naroffe4718892007-04-27 18:30:00 +00005931 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005932 if (lex.get()->getType()->isArithmeticType() &&
5933 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005934 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005935 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005936 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005937
Eli Friedman8e122982008-05-18 18:08:51 +00005938 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005939 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005940 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005941 std::swap(PExp, IExp);
5942
Steve Naroff6b712a72009-07-14 18:25:06 +00005943 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005944 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005945 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5946 return QualType();
5947
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005948 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005949
Chris Lattner12bdebb2009-04-24 23:50:08 +00005950 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005951 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005952 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5953 << PointeeTy << PExp->getSourceRange();
5954 return QualType();
5955 }
Mike Stump11289f42009-09-09 15:08:12 +00005956
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005957 // Check array bounds for pointer arithemtic
5958 CheckArrayAccess(PExp, IExp);
5959
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005960 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005961 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005962 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005963 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005964 if (LHSTy->isPromotableIntegerType())
5965 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005966 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005967 *CompLHSTy = LHSTy;
5968 }
Eli Friedman8e122982008-05-18 18:08:51 +00005969 return PExp->getType();
5970 }
5971 }
5972
Chris Lattner326f7572008-11-18 01:30:42 +00005973 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005974}
5975
Chris Lattner2a3569b2008-04-07 05:30:13 +00005976// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005977QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieucfc491d2011-08-02 04:35:43 +00005978 SourceLocation Loc,
5979 QualType* CompLHSTy) {
5980 if (lex.get()->getType()->isVectorType() ||
5981 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005982 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005983 if (CompLHSTy) *CompLHSTy = compType;
5984 return compType;
5985 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005986
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005987 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005988 if (lex.isInvalid() || rex.isInvalid())
5989 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005990
Chris Lattner4d62f422007-12-09 21:53:25 +00005991 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992
Chris Lattner4d62f422007-12-09 21:53:25 +00005993 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005994 if (lex.get()->getType()->isArithmeticType() &&
5995 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005996 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005997 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005998 }
Mike Stump11289f42009-09-09 15:08:12 +00005999
Chris Lattner4d62f422007-12-09 21:53:25 +00006000 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006001 if (lex.get()->getType()->isAnyPointerType()) {
6002 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006003
Chris Lattner12bdebb2009-04-24 23:50:08 +00006004 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006005 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006006 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006007 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006008 return QualType();
6009 }
Mike Stump11289f42009-09-09 15:08:12 +00006010
Chris Lattner4d62f422007-12-09 21:53:25 +00006011 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006012 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00006013 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6014 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006015
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006016 Expr *IExpr = rex.get()->IgnoreParenCasts();
6017 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6018 OK_Ordinary, IExpr->getExprLoc());
6019 // Check array bounds for pointer arithemtic
6020 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6021
John Wiegley01296292011-04-08 18:41:53 +00006022 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6023 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006024 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006025
Chris Lattner4d62f422007-12-09 21:53:25 +00006026 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006027 if (const PointerType *RHSPTy
6028 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006029 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006030
Eli Friedman168fe152009-05-16 13:54:38 +00006031 if (getLangOptions().CPlusPlus) {
6032 // Pointee types must be the same: C++ [expr.add]
6033 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6034 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006035 << lex.get()->getType() << rex.get()->getType()
6036 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006037 return QualType();
6038 }
6039 } else {
6040 // Pointee types must be compatible C99 6.5.6p3
6041 if (!Context.typesAreCompatible(
6042 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6043 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6044 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006045 << lex.get()->getType() << rex.get()->getType()
6046 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006047 return QualType();
6048 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006049 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006050
Chandler Carruthc9332212011-06-27 08:02:19 +00006051 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6052 lex.get(), rex.get()))
6053 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006054
John Wiegley01296292011-04-08 18:41:53 +00006055 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006056 return Context.getPointerDiffType();
6057 }
6058 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006059
Chris Lattner326f7572008-11-18 01:30:42 +00006060 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006061}
6062
Douglas Gregor0bf31402010-10-08 23:50:27 +00006063static bool isScopedEnumerationType(QualType T) {
6064 if (const EnumType *ET = dyn_cast<EnumType>(T))
6065 return ET->getDecl()->isScoped();
6066 return false;
6067}
6068
John Wiegley01296292011-04-08 18:41:53 +00006069static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006070 SourceLocation Loc, unsigned Opc,
6071 QualType LHSTy) {
6072 llvm::APSInt Right;
6073 // Check right/shifter operand
Richard Trieucfc491d2011-08-02 04:35:43 +00006074 if (rex.get()->isValueDependent() ||
6075 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006076 return;
6077
6078 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006079 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006080 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006081 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006082 return;
6083 }
6084 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006085 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006086 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006087 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006088 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006089 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006090 return;
6091 }
6092 if (Opc != BO_Shl)
6093 return;
6094
6095 // When left shifting an ICE which is signed, we can check for overflow which
6096 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6097 // integers have defined behavior modulo one more than the maximum value
6098 // representable in the result type, so never warn for those.
6099 llvm::APSInt Left;
Richard Trieucfc491d2011-08-02 04:35:43 +00006100 if (lex.get()->isValueDependent() ||
6101 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006102 LHSTy->hasUnsignedIntegerRepresentation())
6103 return;
6104 llvm::APInt ResultBits =
6105 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6106 if (LeftBits.uge(ResultBits))
6107 return;
6108 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6109 Result = Result.shl(Right);
6110
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006111 // Print the bit representation of the signed integer as an unsigned
6112 // hexadecimal number.
6113 llvm::SmallString<40> HexResult;
6114 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6115
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006116 // If we are only missing a sign bit, this is less likely to result in actual
6117 // bugs -- if the result is cast back to an unsigned type, it will have the
6118 // expected value. Thus we place this behind a different warning that can be
6119 // turned off separately if needed.
6120 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006121 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6122 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006123 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006124 return;
6125 }
6126
6127 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006128 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieucfc491d2011-08-02 04:35:43 +00006129 << Left.getBitWidth() << lex.get()->getSourceRange()
6130 << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006131}
6132
Chris Lattner2a3569b2008-04-07 05:30:13 +00006133// C99 6.5.7
Richard Trieucfc491d2011-08-02 04:35:43 +00006134QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6135 SourceLocation Loc, unsigned Opc,
6136 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006137 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006138 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6139 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006140 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006141
Douglas Gregor0bf31402010-10-08 23:50:27 +00006142 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6143 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006144 if (isScopedEnumerationType(lex.get()->getType()) ||
6145 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006146 return InvalidOperands(Loc, lex, rex);
6147 }
6148
Nate Begemane46ee9a2009-10-25 02:26:48 +00006149 // Vector shifts promote their scalar inputs to vector type.
Richard Trieucfc491d2011-08-02 04:35:43 +00006150 if (lex.get()->getType()->isVectorType() ||
6151 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006152 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006153
Chris Lattner5c11c412007-12-12 05:47:28 +00006154 // Shifts don't perform usual arithmetic conversions, they just do integer
6155 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006156
John McCall57cdd882010-12-16 19:28:59 +00006157 // For the LHS, do usual unary conversions, but then reset them away
6158 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006159 ExprResult old_lex = lex;
6160 lex = UsualUnaryConversions(lex.take());
6161 if (lex.isInvalid())
6162 return QualType();
6163 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006164 if (isCompAssign) lex = old_lex;
6165
6166 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006167 rex = UsualUnaryConversions(rex.take());
6168 if (rex.isInvalid())
6169 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006170
Ryan Flynnf53fab82009-08-07 16:20:20 +00006171 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006172 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006173
Chris Lattner5c11c412007-12-12 05:47:28 +00006174 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006175 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006176}
6177
Chandler Carruth17773fc2010-07-10 12:30:03 +00006178static bool IsWithinTemplateSpecialization(Decl *D) {
6179 if (DeclContext *DC = D->getDeclContext()) {
6180 if (isa<ClassTemplateSpecializationDecl>(DC))
6181 return true;
6182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6183 return FD->isFunctionTemplateSpecialization();
6184 }
6185 return false;
6186}
6187
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006188// C99 6.5.8, C++ [expr.rel]
Richard Trieucfc491d2011-08-02 04:35:43 +00006189QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6190 SourceLocation Loc, unsigned OpaqueOpc,
6191 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006192 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006193
Chris Lattner9a152e22009-12-05 05:40:13 +00006194 // Handle vector comparisons separately.
Richard Trieucfc491d2011-08-02 04:35:43 +00006195 if (lex.get()->getType()->isVectorType() ||
6196 rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006197 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006198
John Wiegley01296292011-04-08 18:41:53 +00006199 QualType lType = lex.get()->getType();
6200 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006201
John Wiegley01296292011-04-08 18:41:53 +00006202 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6203 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006204 QualType LHSStrippedType = LHSStripped->getType();
6205 QualType RHSStrippedType = RHSStripped->getType();
6206
Douglas Gregor1beec452011-03-12 01:48:56 +00006207
6208
Chandler Carruth712563b2011-02-17 08:37:06 +00006209 // Two different enums will raise a warning when compared.
6210 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6211 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6212 if (LHSEnumType->getDecl()->getIdentifier() &&
6213 RHSEnumType->getDecl()->getIdentifier() &&
6214 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6215 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6216 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006217 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006218 }
6219 }
6220 }
6221
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006222 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006223 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006224 !lex.get()->getLocStart().isMacroID() &&
6225 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006226 // For non-floating point types, check for self-comparisons of the form
6227 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6228 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006229 //
6230 // NOTE: Don't warn about comparison expressions resulting from macro
6231 // expansion. Also don't warn about comparisons which are only self
6232 // comparisons within a template specialization. The warnings should catch
6233 // obvious cases in the definition of the template anyways. The idea is to
6234 // warn when the typed comparison operator will always evaluate to the same
6235 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006236 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006237 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006238 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006239 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006240 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006241 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006242 << (Opc == BO_EQ
6243 || Opc == BO_LE
6244 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006245 } else if (lType->isArrayType() && rType->isArrayType() &&
6246 !DRL->getDecl()->getType()->isReferenceType() &&
6247 !DRR->getDecl()->getType()->isReferenceType()) {
6248 // what is it always going to eval to?
6249 char always_evals_to;
6250 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006251 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006252 always_evals_to = 0; // false
6253 break;
John McCalle3027922010-08-25 11:45:40 +00006254 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006255 always_evals_to = 1; // true
6256 break;
6257 default:
6258 // best we can say is 'a constant'
6259 always_evals_to = 2; // e.g. array1 <= array2
6260 break;
6261 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006262 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006263 << 1 // array
6264 << always_evals_to);
6265 }
6266 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006267 }
Mike Stump11289f42009-09-09 15:08:12 +00006268
Chris Lattner222b8bd2009-03-08 19:39:53 +00006269 if (isa<CastExpr>(LHSStripped))
6270 LHSStripped = LHSStripped->IgnoreParenCasts();
6271 if (isa<CastExpr>(RHSStripped))
6272 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006273
Chris Lattner222b8bd2009-03-08 19:39:53 +00006274 // Warn about comparisons against a string constant (unless the other
6275 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006276 Expr *literalString = 0;
6277 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006278 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006279 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006280 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006281 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006282 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006283 } else if ((isa<StringLiteral>(RHSStripped) ||
6284 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006285 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006286 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006287 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006288 literalStringStripped = RHSStripped;
6289 }
6290
6291 if (literalString) {
6292 std::string resultComparison;
6293 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006294 case BO_LT: resultComparison = ") < 0"; break;
6295 case BO_GT: resultComparison = ") > 0"; break;
6296 case BO_LE: resultComparison = ") <= 0"; break;
6297 case BO_GE: resultComparison = ") >= 0"; break;
6298 case BO_EQ: resultComparison = ") == 0"; break;
6299 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006300 default: assert(false && "Invalid comparison operator");
6301 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006302
Ted Kremenek3427fac2011-02-23 01:52:04 +00006303 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006304 PDiag(diag::warn_stringcompare)
6305 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006306 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006307 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006308 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006309
Douglas Gregorec170db2010-06-08 19:50:34 +00006310 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieucfc491d2011-08-02 04:35:43 +00006311 if (lex.get()->getType()->isArithmeticType() &&
6312 rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006313 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006314 if (lex.isInvalid() || rex.isInvalid())
6315 return QualType();
6316 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006317 else {
John Wiegley01296292011-04-08 18:41:53 +00006318 lex = UsualUnaryConversions(lex.take());
6319 if (lex.isInvalid())
6320 return QualType();
6321
6322 rex = UsualUnaryConversions(rex.take());
6323 if (rex.isInvalid())
6324 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006325 }
6326
John Wiegley01296292011-04-08 18:41:53 +00006327 lType = lex.get()->getType();
6328 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006329
Douglas Gregorca63811b2008-11-19 03:25:36 +00006330 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006331 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006332
Chris Lattnerb620c342007-08-26 01:18:55 +00006333 if (isRelational) {
6334 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006335 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006336 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006337 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006338 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006339 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006340
Chris Lattnerb620c342007-08-26 01:18:55 +00006341 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006342 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006343 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006344
John Wiegley01296292011-04-08 18:41:53 +00006345 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006346 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006347 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006348 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006349
Douglas Gregorf267edd2010-06-15 21:38:40 +00006350 // All of the following pointer-related warnings are GCC extensions, except
6351 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006352 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006353 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006354 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006355 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006356 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006357
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006358 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006359 if (LCanPointeeTy == RCanPointeeTy)
6360 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006361 if (!isRelational &&
6362 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6363 // Valid unless comparison between non-null pointer and function pointer
6364 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006365 // In a SFINAE context, we treat this as a hard error to maintain
6366 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006367 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6368 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006369 Diag(Loc,
6370 isSFINAEContext()?
6371 diag::err_typecheck_comparison_of_fptr_to_void
6372 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006373 << lType << rType << lex.get()->getSourceRange()
6374 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006375
6376 if (isSFINAEContext())
6377 return QualType();
6378
John Wiegley01296292011-04-08 18:41:53 +00006379 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006380 return ResultTy;
6381 }
6382 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006383
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006384 // C++ [expr.rel]p2:
6385 // [...] Pointer conversions (4.10) and qualification
6386 // conversions (4.4) are performed on pointer operands (or on
6387 // a pointer operand and a null pointer constant) to bring
6388 // them to their composite pointer type. [...]
6389 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006390 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006391 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006392 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006393 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006394 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006395 if (T.isNull()) {
6396 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006397 << lType << rType << lex.get()->getSourceRange()
6398 << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006399 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006400 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006401 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006402 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006403 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006404 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006405 }
6406
John Wiegley01296292011-04-08 18:41:53 +00006407 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6408 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006409 return ResultTy;
6410 }
Eli Friedman16c209612009-08-23 00:27:47 +00006411 // C99 6.5.9p2 and C99 6.5.8p2
6412 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6413 RCanPointeeTy.getUnqualifiedType())) {
6414 // Valid unless a relational comparison of function pointers
6415 if (isRelational && LCanPointeeTy->isFunctionType()) {
6416 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006417 << lType << rType << lex.get()->getSourceRange()
6418 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006419 }
6420 } else if (!isRelational &&
6421 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6422 // Valid unless comparison between non-null pointer and function pointer
6423 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6424 && !LHSIsNull && !RHSIsNull) {
6425 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006426 << lType << rType << lex.get()->getSourceRange()
6427 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006428 }
6429 } else {
6430 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006431 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006432 << lType << rType << lex.get()->getSourceRange()
6433 << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006434 }
John McCall7684dde2011-03-11 04:25:25 +00006435 if (LCanPointeeTy != RCanPointeeTy) {
6436 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006437 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006438 else
John Wiegley01296292011-04-08 18:41:53 +00006439 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006440 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006441 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006442 }
Mike Stump11289f42009-09-09 15:08:12 +00006443
Sebastian Redl576fd422009-05-10 18:38:11 +00006444 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006445 // Comparison of nullptr_t with itself.
6446 if (lType->isNullPtrType() && rType->isNullPtrType())
6447 return ResultTy;
6448
Mike Stump11289f42009-09-09 15:08:12 +00006449 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006450 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006451 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006452 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006453 (!isRelational &&
6454 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006455 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006456 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006457 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006458 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006459 return ResultTy;
6460 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006461 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006462 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006463 (!isRelational &&
6464 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006465 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006466 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006467 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006468 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006469 return ResultTy;
6470 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006471
6472 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006473 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006474 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6475 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006476 // In addition, pointers to members can be compared, or a pointer to
6477 // member and a null pointer constant. Pointer to member conversions
6478 // (4.11) and qualification conversions (4.4) are performed to bring
6479 // them to a common type. If one operand is a null pointer constant,
6480 // the common type is the type of the other operand. Otherwise, the
6481 // common type is a pointer to member type similar (4.4) to the type
6482 // of one of the operands, with a cv-qualification signature (4.4)
6483 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006484 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006485 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006486 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006487 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006488 if (T.isNull()) {
6489 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006490 << lType << rType << lex.get()->getSourceRange()
6491 << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006492 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006493 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006494 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006495 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006496 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006497 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006498 }
Mike Stump11289f42009-09-09 15:08:12 +00006499
John Wiegley01296292011-04-08 18:41:53 +00006500 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6501 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006502 return ResultTy;
6503 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006504
6505 // Handle scoped enumeration types specifically, since they don't promote
6506 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006507 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieucfc491d2011-08-02 04:35:43 +00006508 Context.hasSameUnqualifiedType(lex.get()->getType(),
6509 rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006510 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006511 }
Mike Stump11289f42009-09-09 15:08:12 +00006512
Steve Naroff081c7422008-09-04 15:10:53 +00006513 // Handle block pointer types.
Richard Trieucfc491d2011-08-02 04:35:43 +00006514 if (!isRelational && lType->isBlockPointerType() &&
6515 rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006516 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6517 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006518
Steve Naroff081c7422008-09-04 15:10:53 +00006519 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006520 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006521 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006522 << lType << rType << lex.get()->getSourceRange()
6523 << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006524 }
John Wiegley01296292011-04-08 18:41:53 +00006525 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006526 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006527 }
John Wiegley01296292011-04-08 18:41:53 +00006528
Steve Naroffe18f94c2008-09-28 01:11:11 +00006529 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006530 if (!isRelational
6531 && ((lType->isBlockPointerType() && rType->isPointerType())
6532 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006533 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006534 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006535 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006536 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006537 ->getPointeeType()->isVoidType())))
6538 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006539 << lType << rType << lex.get()->getSourceRange()
6540 << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006541 }
John McCall7684dde2011-03-11 04:25:25 +00006542 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006543 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006544 else
John Wiegley01296292011-04-08 18:41:53 +00006545 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006546 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006547 }
Steve Naroff081c7422008-09-04 15:10:53 +00006548
John McCall7684dde2011-03-11 04:25:25 +00006549 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6550 const PointerType *LPT = lType->getAs<PointerType>();
6551 const PointerType *RPT = rType->getAs<PointerType>();
6552 if (LPT || RPT) {
6553 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6554 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006555
Steve Naroff753567f2008-11-17 19:49:16 +00006556 if (!LPtrToVoid && !RPtrToVoid &&
6557 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006558 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006559 << lType << rType << lex.get()->getSourceRange()
6560 << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006561 }
John McCall7684dde2011-03-11 04:25:25 +00006562 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006563 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006564 else
John Wiegley01296292011-04-08 18:41:53 +00006565 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006566 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006567 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006568 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006569 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006570 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006571 << lType << rType << lex.get()->getSourceRange()
6572 << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006573 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006574 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006575 else
John Wiegley01296292011-04-08 18:41:53 +00006576 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006577 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006578 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006579 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006580 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6581 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006582 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006583 bool isError = false;
6584 if ((LHSIsNull && lType->isIntegerType()) ||
6585 (RHSIsNull && rType->isIntegerType())) {
6586 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006587 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006588 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006589 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006590 else if (getLangOptions().CPlusPlus) {
6591 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6592 isError = true;
6593 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006594 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006595
Chris Lattnerd99bd522009-08-23 00:03:44 +00006596 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006597 Diag(Loc, DiagID)
Richard Trieucfc491d2011-08-02 04:35:43 +00006598 << lType << rType << lex.get()->getSourceRange()
6599 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006600 if (isError)
6601 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006602 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006603
6604 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006605 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006606 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006607 else
John Wiegley01296292011-04-08 18:41:53 +00006608 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006609 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006610 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006611 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006612
Steve Naroff4b191572008-09-04 16:56:14 +00006613 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006614 if (!isRelational && RHSIsNull
6615 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006616 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006617 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006618 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006619 if (!isRelational && LHSIsNull
6620 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006621 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006622 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006623 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006624
Chris Lattner326f7572008-11-18 01:30:42 +00006625 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006626}
6627
Nate Begeman191a6b12008-07-14 18:02:46 +00006628/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006629/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006630/// like a scalar comparison, a vector comparison produces a vector of integer
6631/// types.
John Wiegley01296292011-04-08 18:41:53 +00006632QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006633 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006634 bool isRelational) {
6635 // Check to make sure we're operating on vectors of the same type and width,
6636 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006637 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006638 if (vType.isNull())
6639 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006640
John Wiegley01296292011-04-08 18:41:53 +00006641 QualType lType = lex.get()->getType();
6642 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006643
Anton Yartsev530deb92011-03-27 15:36:07 +00006644 // If AltiVec, the comparison results in a numeric type, i.e.
6645 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006646 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006647 return Context.getLogicalOperationType();
6648
Nate Begeman191a6b12008-07-14 18:02:46 +00006649 // For non-floating point types, check for self-comparisons of the form
6650 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6651 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006652 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006653 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6654 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006655 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006656 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006657 PDiag(diag::warn_comparison_always)
6658 << 0 // self-
6659 << 2 // "a constant"
6660 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006661 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006662
Nate Begeman191a6b12008-07-14 18:02:46 +00006663 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006664 if (!isRelational && lType->hasFloatingRepresentation()) {
6665 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006666 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006667 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006668
Nate Begeman191a6b12008-07-14 18:02:46 +00006669 // Return the type for the comparison, which is the same as vector type for
6670 // integer vectors, or an integer type of identical size and number of
6671 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006672 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006673 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006674
John McCall9dd450b2009-09-21 23:43:11 +00006675 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006676 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006677 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006678 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006679 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006680 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6681
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006683 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006684 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6685}
6686
Steve Naroff218bc2b2007-05-04 21:54:46 +00006687inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006688 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00006689 if (lex.get()->getType()->isVectorType() ||
6690 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006691 if (lex.get()->getType()->hasIntegerRepresentation() &&
6692 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006693 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006694
6695 return InvalidOperands(Loc, lex, rex);
6696 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006697
John Wiegley01296292011-04-08 18:41:53 +00006698 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieucfc491d2011-08-02 04:35:43 +00006699 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6700 isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006701 if (lexResult.isInvalid() || rexResult.isInvalid())
6702 return QualType();
6703 lex = lexResult.take();
6704 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006705
John Wiegley01296292011-04-08 18:41:53 +00006706 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6707 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006708 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006709 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006710}
6711
Steve Naroff218bc2b2007-05-04 21:54:46 +00006712inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006713 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006714
6715 // Diagnose cases where the user write a logical and/or but probably meant a
6716 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6717 // is a constant.
Richard Trieucfc491d2011-08-02 04:35:43 +00006718 if (lex.get()->getType()->isIntegerType() &&
6719 !lex.get()->getType()->isBooleanType() &&
John Wiegley01296292011-04-08 18:41:53 +00006720 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006721 // Don't warn in macros or template instantiations.
6722 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006723 // If the RHS can be constant folded, and if it constant folds to something
6724 // that isn't 0 or 1 (which indicate a potential logical operation that
6725 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006726 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006727 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006728 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6729 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6730 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6731 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6732 << rex.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006733 << (Opc == BO_LAnd ? "&&" : "||");
6734 // Suggest replacing the logical operator with the bitwise version
6735 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6736 << (Opc == BO_LAnd ? "&" : "|")
6737 << FixItHint::CreateReplacement(SourceRange(
6738 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6739 getLangOptions())),
6740 Opc == BO_LAnd ? "&" : "|");
6741 if (Opc == BO_LAnd)
6742 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6743 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6744 << FixItHint::CreateRemoval(
6745 SourceRange(
6746 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6747 0, getSourceManager(),
6748 getLangOptions()),
6749 rex.get()->getLocEnd()));
6750 }
Chris Lattner938533d2010-07-24 01:10:11 +00006751 }
Chris Lattner8406c512010-07-13 19:41:32 +00006752
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006753 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006754 lex = UsualUnaryConversions(lex.take());
6755 if (lex.isInvalid())
6756 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006757
John Wiegley01296292011-04-08 18:41:53 +00006758 rex = UsualUnaryConversions(rex.take());
6759 if (rex.isInvalid())
6760 return QualType();
6761
Richard Trieucfc491d2011-08-02 04:35:43 +00006762 if (!lex.get()->getType()->isScalarType() ||
6763 !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006764 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006765
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006766 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006767 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006768
John McCall4a2429a2010-06-04 00:29:51 +00006769 // The following is safe because we only use this method for
6770 // non-overloadable operands.
6771
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006772 // C++ [expr.log.and]p1
6773 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006774 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006775 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6776 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006777 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006778 lex = move(lexRes);
6779
6780 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6781 if (rexRes.isInvalid())
6782 return InvalidOperands(Loc, lex, rex);
6783 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006784
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006785 // C++ [expr.log.and]p2
6786 // C++ [expr.log.or]p2
6787 // The result is a bool.
6788 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006789}
6790
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006791/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6792/// is a read-only property; return true if so. A readonly property expression
6793/// depends on various declarations and thus must be treated specially.
6794///
Mike Stump11289f42009-09-09 15:08:12 +00006795static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006796 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6797 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006798 if (PropExpr->isImplicitProperty()) return false;
6799
6800 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6801 QualType BaseType = PropExpr->isSuperReceiver() ?
6802 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006803 PropExpr->getBase()->getType();
6804
John McCallb7bd14f2010-12-02 01:19:52 +00006805 if (const ObjCObjectPointerType *OPT =
6806 BaseType->getAsObjCInterfacePointerType())
6807 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6808 if (S.isPropertyReadonly(PDecl, IFace))
6809 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006810 }
6811 return false;
6812}
6813
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006814static bool IsConstProperty(Expr *E, Sema &S) {
6815 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6816 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6817 if (PropExpr->isImplicitProperty()) return false;
6818
6819 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6820 QualType T = PDecl->getType();
6821 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006822 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006823 CanQualType CT = S.Context.getCanonicalType(T);
6824 return CT.isConstQualified();
6825 }
6826 return false;
6827}
6828
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006829static bool IsReadonlyMessage(Expr *E, Sema &S) {
6830 if (E->getStmtClass() != Expr::MemberExprClass)
6831 return false;
6832 const MemberExpr *ME = cast<MemberExpr>(E);
6833 NamedDecl *Member = ME->getMemberDecl();
6834 if (isa<FieldDecl>(Member)) {
6835 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6836 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6837 return false;
6838 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6839 }
6840 return false;
6841}
6842
Chris Lattner30bd3272008-11-18 01:22:49 +00006843/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6844/// emit an error and return true. If so, return false.
6845static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006846 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006847 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006848 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006849 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6850 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006851 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6852 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006853 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6854 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006855 if (IsLV == Expr::MLV_Valid)
6856 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006857
Chris Lattner30bd3272008-11-18 01:22:49 +00006858 unsigned Diag = 0;
6859 bool NeedType = false;
6860 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006861 case Expr::MLV_ConstQualified:
6862 Diag = diag::err_typecheck_assign_const;
6863
John McCalld4631322011-06-17 06:42:21 +00006864 // In ARC, use some specialized diagnostics for occasions where we
6865 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006866 if (S.getLangOptions().ObjCAutoRefCount) {
6867 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6868 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6869 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6870
John McCalld4631322011-06-17 06:42:21 +00006871 // Use the normal diagnostic if it's pseudo-__strong but the
6872 // user actually wrote 'const'.
6873 if (var->isARCPseudoStrong() &&
6874 (!var->getTypeSourceInfo() ||
6875 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6876 // There are two pseudo-strong cases:
6877 // - self
John McCall31168b02011-06-15 23:02:42 +00006878 ObjCMethodDecl *method = S.getCurMethodDecl();
6879 if (method && var == method->getSelfDecl())
6880 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006881
6882 // - fast enumeration variables
6883 else
John McCall31168b02011-06-15 23:02:42 +00006884 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006885
John McCall31168b02011-06-15 23:02:42 +00006886 SourceRange Assign;
6887 if (Loc != OrigLoc)
6888 Assign = SourceRange(OrigLoc, OrigLoc);
6889 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6890 // We need to preserve the AST regardless, so migration tool
6891 // can do its job.
6892 return false;
6893 }
6894 }
6895 }
6896
6897 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006898 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006899 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6900 NeedType = true;
6901 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006902 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006903 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6904 NeedType = true;
6905 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006906 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006907 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6908 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006909 case Expr::MLV_Valid:
6910 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006911 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006912 case Expr::MLV_MemberFunction:
6913 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006914 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6915 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006916 case Expr::MLV_IncompleteType:
6917 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006918 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006919 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006920 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006921 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006922 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6923 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006924 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006925 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6926 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006927 case Expr::MLV_ReadonlyProperty:
6928 Diag = diag::error_readonly_property_assignment;
6929 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006930 case Expr::MLV_NoSetterProperty:
6931 Diag = diag::error_nosetter_property_assignment;
6932 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006933 case Expr::MLV_InvalidMessageExpression:
6934 Diag = diag::error_readonly_message_assignment;
6935 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006936 case Expr::MLV_SubObjCPropertySetting:
6937 Diag = diag::error_no_subobject_property_setting;
6938 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006939 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006940
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006941 SourceRange Assign;
6942 if (Loc != OrigLoc)
6943 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006944 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006945 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006946 else
Mike Stump11289f42009-09-09 15:08:12 +00006947 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006948 return true;
6949}
6950
6951
6952
6953// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006954QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006955 SourceLocation Loc,
6956 QualType CompoundType) {
6957 // Verify that LHS is a modifiable lvalue, and emit error if not.
6958 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006959 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006960
6961 QualType LHSType = LHS->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00006962 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6963 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006964 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006965 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006966 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006967 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006968 if (LHS->getObjectKind() == OK_ObjCProperty) {
6969 ExprResult LHSResult = Owned(LHS);
6970 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6971 if (LHSResult.isInvalid())
6972 return QualType();
6973 LHS = LHSResult.take();
6974 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006975 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006976 if (RHS.isInvalid())
6977 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006978 // Special case of NSObject attributes on c-style pointer types.
6979 if (ConvTy == IncompatiblePointer &&
6980 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006981 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006982 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006983 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006984 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006985
John McCall7decc9e2010-11-18 06:31:45 +00006986 if (ConvTy == Compatible &&
6987 getLangOptions().ObjCNonFragileABI &&
6988 LHSType->isObjCObjectType())
6989 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6990 << LHSType;
6991
Chris Lattnerea714382008-08-21 18:04:13 +00006992 // If the RHS is a unary plus or minus, check to see if they = and + are
6993 // right next to each other. If so, the user may have typo'd "x =+ 4"
6994 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006995 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6997 RHSCheck = ICE->getSubExpr();
6998 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006999 if ((UO->getOpcode() == UO_Plus ||
7000 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007001 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007002 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007003 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7004 // And there is a space or other character before the subexpr of the
7005 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007006 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7007 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007008 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007009 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007010 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007011 }
Chris Lattnerea714382008-08-21 18:04:13 +00007012 }
John McCall31168b02011-06-15 23:02:42 +00007013
7014 if (ConvTy == Compatible) {
7015 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7016 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007017 else if (getLangOptions().ObjCAutoRefCount)
7018 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007019 }
Chris Lattnerea714382008-08-21 18:04:13 +00007020 } else {
7021 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007022 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007023 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007024
Chris Lattner326f7572008-11-18 01:30:42 +00007025 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007026 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007027 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007028
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007029 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007030
Steve Naroff98cf3e92007-06-06 18:38:38 +00007031 // C99 6.5.16p3: The type of an assignment expression is the type of the
7032 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007033 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007034 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7035 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007036 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007037 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007038 return (getLangOptions().CPlusPlus
7039 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007040}
7041
Chris Lattner326f7572008-11-18 01:30:42 +00007042// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007043static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007044 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007045 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007046
John McCall3aef3d82011-04-10 19:13:55 +00007047 LHS = S.CheckPlaceholderExpr(LHS.take());
7048 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007049 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007050 return QualType();
7051
John McCall73d36182010-10-12 07:14:40 +00007052 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7053 // operands, but not unary promotions.
7054 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007055
John McCall34376a62010-12-04 03:47:34 +00007056 // So we treat the LHS as a ignored value, and in C++ we allow the
7057 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007058 LHS = S.IgnoredValueConversions(LHS.take());
7059 if (LHS.isInvalid())
7060 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007061
7062 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007063 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7064 if (RHS.isInvalid())
7065 return QualType();
7066 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007067 S.RequireCompleteType(Loc, RHS.get()->getType(),
7068 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007069 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007070
John Wiegley01296292011-04-08 18:41:53 +00007071 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007072}
7073
Steve Naroff7a5af782007-07-13 16:58:59 +00007074/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7075/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007076static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7077 ExprValueKind &VK,
7078 SourceLocation OpLoc,
7079 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007080 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007081 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007082
Chris Lattner6b0cf142008-11-21 07:05:48 +00007083 QualType ResType = Op->getType();
7084 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007085
John McCall4bc41ae2010-11-18 19:01:18 +00007086 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007087 // Decrement of bool is not allowed.
7088 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007089 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007090 return QualType();
7091 }
7092 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007093 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007094 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007095 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007096 } else if (ResType->isAnyPointerType()) {
7097 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007098
Chris Lattner6b0cf142008-11-21 07:05:48 +00007099 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007100 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007101 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007102
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007103 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007104 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7105 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007106 << PointeeTy << Op->getSourceRange();
7107 return QualType();
7108 }
Eli Friedman090addd2010-01-03 00:20:48 +00007109 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007110 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007111 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007112 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007113 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007114 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007115 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007116 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7117 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007118 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7119 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007120 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007121 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007122 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007123 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007124 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007125 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007126 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007127 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007128 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007129 // In C++, a prefix increment is the same type as the operand. Otherwise
7130 // (in C or with postfix), the increment is the unqualified type of the
7131 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007132 if (isPrefix && S.getLangOptions().CPlusPlus) {
7133 VK = VK_LValue;
7134 return ResType;
7135 } else {
7136 VK = VK_RValue;
7137 return ResType.getUnqualifiedType();
7138 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007139}
7140
John Wiegley01296292011-04-08 18:41:53 +00007141ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007142 assert(E->getValueKind() == VK_LValue &&
7143 E->getObjectKind() == OK_ObjCProperty);
7144 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7145
Douglas Gregor33823722011-06-11 01:09:30 +00007146 QualType T = E->getType();
7147 QualType ReceiverType;
7148 if (PRE->isObjectReceiver())
7149 ReceiverType = PRE->getBase()->getType();
7150 else if (PRE->isSuperReceiver())
7151 ReceiverType = PRE->getSuperReceiverType();
7152 else
7153 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7154
John McCall34376a62010-12-04 03:47:34 +00007155 ExprValueKind VK = VK_RValue;
7156 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007157 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007158 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007159 T = getMessageSendResultType(ReceiverType, GetterMethod,
7160 PRE->isClassReceiver(),
7161 PRE->isSuperReceiver());
7162 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007163 }
7164 else {
7165 Diag(PRE->getLocation(), diag::err_getter_not_found)
7166 << PRE->getBase()->getType();
7167 }
John McCall34376a62010-12-04 03:47:34 +00007168 }
Douglas Gregor33823722011-06-11 01:09:30 +00007169
7170 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007171 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007172
7173 ExprResult Result = MaybeBindToTemporary(E);
7174 if (!Result.isInvalid())
7175 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007176
7177 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007178}
7179
Richard Trieucfc491d2011-08-02 04:35:43 +00007180void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7181 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007182 assert(LHS.get()->getValueKind() == VK_LValue &&
7183 LHS.get()->getObjectKind() == OK_ObjCProperty);
7184 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007185
John McCall31168b02011-06-15 23:02:42 +00007186 bool Consumed = false;
7187
John Wiegley01296292011-04-08 18:41:53 +00007188 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007189 // If using property-dot syntax notation for assignment, and there is a
7190 // setter, RHS expression is being passed to the setter argument. So,
7191 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007192 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007193 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7194 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007195 Consumed = (getLangOptions().ObjCAutoRefCount &&
7196 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007197
7198 // Otherwise, if the getter returns an l-value, just call that.
7199 } else {
John Wiegley01296292011-04-08 18:41:53 +00007200 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007201 ExprValueKind VK = Expr::getValueKindForType(Result);
7202 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007203 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7204 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007205 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007206 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007207 }
John McCall31168b02011-06-15 23:02:42 +00007208 } else if (getLangOptions().ObjCAutoRefCount) {
7209 const ObjCMethodDecl *setter
7210 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7211 if (setter) {
7212 ObjCMethodDecl::param_iterator P = setter->param_begin();
7213 LHSTy = (*P)->getType();
7214 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7215 }
John McCall34376a62010-12-04 03:47:34 +00007216 }
7217
John McCall31168b02011-06-15 23:02:42 +00007218 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7219 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007220 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007221 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007222 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007223 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007224 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007225 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7226 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7227 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007228 }
7229}
7230
7231
Anders Carlsson806700f2008-02-01 07:15:58 +00007232/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007233/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007234/// where the declaration is needed for type checking. We only need to
7235/// handle cases when the expression references a function designator
7236/// or is an lvalue. Here are some examples:
7237/// - &(x) => x
7238/// - &*****f => f for f a function designator.
7239/// - &s.xx => s
7240/// - &s.zz[1].yy -> s, if zz is an array
7241/// - *(x + 1) -> x, if x is an array
7242/// - &"123"[2] -> 0
7243/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007244static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007245 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007246 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007247 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007248 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007249 // If this is an arrow operator, the address is an offset from
7250 // the base's value, so the object the base refers to is
7251 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007252 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007253 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007254 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007255 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007256 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007257 // FIXME: This code shouldn't be necessary! We should catch the implicit
7258 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007259 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7260 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7261 if (ICE->getSubExpr()->getType()->isArrayType())
7262 return getPrimaryDecl(ICE->getSubExpr());
7263 }
7264 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007265 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007266 case Stmt::UnaryOperatorClass: {
7267 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007268
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007269 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007270 case UO_Real:
7271 case UO_Imag:
7272 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007273 return getPrimaryDecl(UO->getSubExpr());
7274 default:
7275 return 0;
7276 }
7277 }
Steve Naroff47500512007-04-19 23:00:49 +00007278 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007279 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007280 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007281 // If the result of an implicit cast is an l-value, we care about
7282 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007283 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007284 default:
7285 return 0;
7286 }
7287}
7288
7289/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007290/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007291/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007292/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007293/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007294/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007295/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007296static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7297 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007298 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007299 return S.Context.DependentTy;
7300 if (OrigOp->getType() == S.Context.OverloadTy)
7301 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007302 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7303 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007304 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7305 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7306 << OrigOp->getSourceRange();
7307 return QualType();
7308 }
John McCall8d08b9b2010-08-27 09:08:28 +00007309
John McCall2979fe02011-04-12 00:42:48 +00007310 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007311
John McCall8d08b9b2010-08-27 09:08:28 +00007312 // Make sure to ignore parentheses in subsequent checks
7313 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007314
John McCall4bc41ae2010-11-18 19:01:18 +00007315 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007316 // Implement C99-only parts of addressof rules.
7317 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007318 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007319 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7320 // (assuming the deref expression is valid).
7321 return uOp->getSubExpr()->getType();
7322 }
7323 // Technically, there should be a check for array subscript
7324 // expressions here, but the result of one is always an lvalue anyway.
7325 }
John McCallf3a88602011-02-03 08:15:49 +00007326 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007327 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007328
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007329 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007330 bool sfinae = S.isSFINAEContext();
7331 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7332 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007333 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007334 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007335 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007336 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007337 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007338 } else if (lval == Expr::LV_MemberFunction) {
7339 // If it's an instance method, make a member pointer.
7340 // The expression must have exactly the form &A::foo.
7341
7342 // If the underlying expression isn't a decl ref, give up.
7343 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007344 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007345 << OrigOp->getSourceRange();
7346 return QualType();
7347 }
7348 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7349 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7350
7351 // The id-expression was parenthesized.
7352 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007353 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007354 << OrigOp->getSourceRange();
7355
7356 // The method was named without a qualifier.
7357 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007358 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007359 << op->getSourceRange();
7360 }
7361
John McCall4bc41ae2010-11-18 19:01:18 +00007362 return S.Context.getMemberPointerType(op->getType(),
7363 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007364 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007365 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007366 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007367 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007368 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007369 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007370 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007371 return QualType();
7372 }
John McCall086a4642010-11-24 05:12:34 +00007373 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007374 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007375 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007376 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007377 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007378 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007379 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007380 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007381 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007382 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007383 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007384 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007385 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007386 << "property expression" << op->getSourceRange();
7387 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007388 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007389 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007390 // with the register storage-class specifier.
7391 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007392 // in C++ it is not error to take address of a register
7393 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007394 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007395 !S.getLangOptions().CPlusPlus) {
7396 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007397 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007398 return QualType();
7399 }
John McCalld14a8642009-11-21 08:51:07 +00007400 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007401 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007402 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007403 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007404 // Could be a pointer to member, though, if there is an explicit
7405 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007406 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007407 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007408 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007409 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007410 S.Diag(OpLoc,
7411 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007412 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007413 return QualType();
7414 }
Mike Stump11289f42009-09-09 15:08:12 +00007415
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007416 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7417 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007418 return S.Context.getMemberPointerType(op->getType(),
7419 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007420 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007421 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007422 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007423 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007424 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007425
Eli Friedmance7f9002009-05-16 23:27:50 +00007426 if (lval == Expr::LV_IncompleteVoidType) {
7427 // Taking the address of a void variable is technically illegal, but we
7428 // allow it in cases which are otherwise valid.
7429 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007430 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007431 }
7432
Steve Naroff47500512007-04-19 23:00:49 +00007433 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007434 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007435 return S.Context.getObjCObjectPointerType(op->getType());
7436 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007437}
7438
Chris Lattner9156f1b2010-07-05 19:17:26 +00007439/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007440static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7441 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007442 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007443 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007444
John Wiegley01296292011-04-08 18:41:53 +00007445 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7446 if (ConvResult.isInvalid())
7447 return QualType();
7448 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007449 QualType OpTy = Op->getType();
7450 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007451
7452 if (isa<CXXReinterpretCastExpr>(Op)) {
7453 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7454 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7455 Op->getSourceRange());
7456 }
7457
Chris Lattner9156f1b2010-07-05 19:17:26 +00007458 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7459 // is an incomplete type or void. It would be possible to warn about
7460 // dereferencing a void pointer, but it's completely well-defined, and such a
7461 // warning is unlikely to catch any mistakes.
7462 if (const PointerType *PT = OpTy->getAs<PointerType>())
7463 Result = PT->getPointeeType();
7464 else if (const ObjCObjectPointerType *OPT =
7465 OpTy->getAs<ObjCObjectPointerType>())
7466 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007467 else {
John McCall3aef3d82011-04-10 19:13:55 +00007468 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007469 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007470 if (PR.take() != Op)
7471 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007472 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007473
Chris Lattner9156f1b2010-07-05 19:17:26 +00007474 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007475 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007476 << OpTy << Op->getSourceRange();
7477 return QualType();
7478 }
John McCall4bc41ae2010-11-18 19:01:18 +00007479
7480 // Dereferences are usually l-values...
7481 VK = VK_LValue;
7482
7483 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007484 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007485 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007486
7487 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007488}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007489
John McCalle3027922010-08-25 11:45:40 +00007490static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007491 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007492 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007493 switch (Kind) {
7494 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007495 case tok::periodstar: Opc = BO_PtrMemD; break;
7496 case tok::arrowstar: Opc = BO_PtrMemI; break;
7497 case tok::star: Opc = BO_Mul; break;
7498 case tok::slash: Opc = BO_Div; break;
7499 case tok::percent: Opc = BO_Rem; break;
7500 case tok::plus: Opc = BO_Add; break;
7501 case tok::minus: Opc = BO_Sub; break;
7502 case tok::lessless: Opc = BO_Shl; break;
7503 case tok::greatergreater: Opc = BO_Shr; break;
7504 case tok::lessequal: Opc = BO_LE; break;
7505 case tok::less: Opc = BO_LT; break;
7506 case tok::greaterequal: Opc = BO_GE; break;
7507 case tok::greater: Opc = BO_GT; break;
7508 case tok::exclaimequal: Opc = BO_NE; break;
7509 case tok::equalequal: Opc = BO_EQ; break;
7510 case tok::amp: Opc = BO_And; break;
7511 case tok::caret: Opc = BO_Xor; break;
7512 case tok::pipe: Opc = BO_Or; break;
7513 case tok::ampamp: Opc = BO_LAnd; break;
7514 case tok::pipepipe: Opc = BO_LOr; break;
7515 case tok::equal: Opc = BO_Assign; break;
7516 case tok::starequal: Opc = BO_MulAssign; break;
7517 case tok::slashequal: Opc = BO_DivAssign; break;
7518 case tok::percentequal: Opc = BO_RemAssign; break;
7519 case tok::plusequal: Opc = BO_AddAssign; break;
7520 case tok::minusequal: Opc = BO_SubAssign; break;
7521 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7522 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7523 case tok::ampequal: Opc = BO_AndAssign; break;
7524 case tok::caretequal: Opc = BO_XorAssign; break;
7525 case tok::pipeequal: Opc = BO_OrAssign; break;
7526 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007527 }
7528 return Opc;
7529}
7530
John McCalle3027922010-08-25 11:45:40 +00007531static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007532 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007533 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007534 switch (Kind) {
7535 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007536 case tok::plusplus: Opc = UO_PreInc; break;
7537 case tok::minusminus: Opc = UO_PreDec; break;
7538 case tok::amp: Opc = UO_AddrOf; break;
7539 case tok::star: Opc = UO_Deref; break;
7540 case tok::plus: Opc = UO_Plus; break;
7541 case tok::minus: Opc = UO_Minus; break;
7542 case tok::tilde: Opc = UO_Not; break;
7543 case tok::exclaim: Opc = UO_LNot; break;
7544 case tok::kw___real: Opc = UO_Real; break;
7545 case tok::kw___imag: Opc = UO_Imag; break;
7546 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007547 }
7548 return Opc;
7549}
7550
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007551/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7552/// This warning is only emitted for builtin assignment operations. It is also
7553/// suppressed in the event of macro expansions.
7554static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7555 SourceLocation OpLoc) {
7556 if (!S.ActiveTemplateInstantiations.empty())
7557 return;
7558 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7559 return;
7560 lhs = lhs->IgnoreParenImpCasts();
7561 rhs = rhs->IgnoreParenImpCasts();
7562 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7563 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7564 if (!LeftDeclRef || !RightDeclRef ||
7565 LeftDeclRef->getLocation().isMacroID() ||
7566 RightDeclRef->getLocation().isMacroID())
7567 return;
7568 const ValueDecl *LeftDecl =
7569 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7570 const ValueDecl *RightDecl =
7571 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7572 if (LeftDecl != RightDecl)
7573 return;
7574 if (LeftDecl->getType().isVolatileQualified())
7575 return;
7576 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7577 if (RefTy->getPointeeType().isVolatileQualified())
7578 return;
7579
7580 S.Diag(OpLoc, diag::warn_self_assignment)
7581 << LeftDeclRef->getType()
7582 << lhs->getSourceRange() << rhs->getSourceRange();
7583}
7584
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007585/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7586/// operator @p Opc at location @c TokLoc. This routine only supports
7587/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007588ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007589 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007590 Expr *lhsExpr, Expr *rhsExpr) {
7591 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007592 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007593 // The following two variables are used for compound assignment operators
7594 QualType CompLHSTy; // Type of LHS after promotions for computation
7595 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007596 ExprValueKind VK = VK_RValue;
7597 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007598
Douglas Gregor1beec452011-03-12 01:48:56 +00007599 // Check if a 'foo<int>' involved in a binary op, identifies a single
7600 // function unambiguously (i.e. an lvalue ala 13.4)
7601 // But since an assignment can trigger target based overload, exclude it in
7602 // our blind search. i.e:
7603 // template<class T> void f(); template<class T, class U> void f(U);
7604 // f<int> == 0; // resolve f<int> blindly
7605 // void (*p)(int); p = f<int>; // resolve f<int> using target
7606 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007607 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007608 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007609 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007610
John McCall3aef3d82011-04-10 19:13:55 +00007611 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007612 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007613 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007614 }
7615
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007616 // The canonical way to check for a GNU null is with isNullPointerConstant,
7617 // but we use a bit of a hack here for speed; this is a relatively
7618 // hot path, and isNullPointerConstant is slow.
7619 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7620 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007621
7622 // Detect when a NULL constant is used improperly in an expression. These
7623 // are mainly cases where the null pointer is used as an integer instead
7624 // of a pointer.
7625 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007626 // Avoid analyzing cases where the result will either be invalid (and
7627 // diagnosed as such) or entirely valid and not something to warn about.
7628 QualType LeftType = lhs.get()->getType();
7629 QualType RightType = rhs.get()->getType();
7630 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7631 !LeftType->isFunctionType() &&
7632 !RightType->isBlockPointerType() &&
7633 !RightType->isMemberPointerType() &&
7634 !RightType->isFunctionType()) {
7635 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7636 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7637 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7638 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7639 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7640 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7641 // These are the operations that would not make sense with a null pointer
Richard Trieucfc491d2011-08-02 04:35:43 +00007642 // pointer no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007643 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007644 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7645 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7646 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7647 Opc == BO_EQ || Opc == BO_NE) {
7648 // These are the operations that would not make sense with a null pointer
7649 // if the other expression the other expression is not a pointer.
7650 if (LeftNull != RightNull &&
7651 !LeftType->isAnyPointerType() &&
7652 !LeftType->canDecayToPointerType() &&
7653 !RightType->isAnyPointerType() &&
7654 !RightType->canDecayToPointerType()) {
Richard Trieuaee9e762011-08-11 22:38:21 +00007655 Diag(OpLoc, diag::warn_null_in_comparison_operation)
7656 << LeftNull /* LHS is NULL */
7657 << (LeftNull ? rhs.get()->getType() : lhs.get()->getType())
7658 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
Chandler Carruth4f04b432011-06-20 07:38:51 +00007659 }
Richard Trieu701fb362011-06-16 21:36:56 +00007660 }
7661 }
7662 }
7663
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007664 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007665 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007666 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007667 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007668 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7669 VK = lhs.get()->getValueKind();
7670 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007671 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007672 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007673 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007674 break;
John McCalle3027922010-08-25 11:45:40 +00007675 case BO_PtrMemD:
7676 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007677 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007678 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007679 break;
John McCalle3027922010-08-25 11:45:40 +00007680 case BO_Mul:
7681 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007682 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007683 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007684 break;
John McCalle3027922010-08-25 11:45:40 +00007685 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007686 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7687 break;
John McCalle3027922010-08-25 11:45:40 +00007688 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007689 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7690 break;
John McCalle3027922010-08-25 11:45:40 +00007691 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007692 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7693 break;
John McCalle3027922010-08-25 11:45:40 +00007694 case BO_Shl:
7695 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007696 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007697 break;
John McCalle3027922010-08-25 11:45:40 +00007698 case BO_LE:
7699 case BO_LT:
7700 case BO_GE:
7701 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007702 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007703 break;
John McCalle3027922010-08-25 11:45:40 +00007704 case BO_EQ:
7705 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007706 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007707 break;
John McCalle3027922010-08-25 11:45:40 +00007708 case BO_And:
7709 case BO_Xor:
7710 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007711 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7712 break;
John McCalle3027922010-08-25 11:45:40 +00007713 case BO_LAnd:
7714 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007715 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007716 break;
John McCalle3027922010-08-25 11:45:40 +00007717 case BO_MulAssign:
7718 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007719 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007720 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007721 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007722 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7723 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007724 break;
John McCalle3027922010-08-25 11:45:40 +00007725 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007726 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7727 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007728 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7729 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007730 break;
John McCalle3027922010-08-25 11:45:40 +00007731 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007732 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007733 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7734 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007735 break;
John McCalle3027922010-08-25 11:45:40 +00007736 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007737 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007738 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7739 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007740 break;
John McCalle3027922010-08-25 11:45:40 +00007741 case BO_ShlAssign:
7742 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007743 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007744 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007745 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7746 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007747 break;
John McCalle3027922010-08-25 11:45:40 +00007748 case BO_AndAssign:
7749 case BO_XorAssign:
7750 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007751 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7752 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007753 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7754 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007755 break;
John McCalle3027922010-08-25 11:45:40 +00007756 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007757 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007758 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7759 VK = rhs.get()->getValueKind();
7760 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007761 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007762 break;
7763 }
John Wiegley01296292011-04-08 18:41:53 +00007764 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007765 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007766
7767 // Check for array bounds violations for both sides of the BinaryOperator
7768 CheckArrayAccess(lhs.get());
7769 CheckArrayAccess(rhs.get());
7770
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007771 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007772 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7773 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007774 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7775 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007776 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007777 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007778 }
John Wiegley01296292011-04-08 18:41:53 +00007779 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7780 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007781 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007782}
7783
Sebastian Redl44615072009-10-27 12:10:02 +00007784/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7785/// operators are mixed in a way that suggests that the programmer forgot that
7786/// comparison operators have higher precedence. The most typical example of
7787/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007788static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007789 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007790 typedef BinaryOperator BinOp;
7791 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7792 rhsopc = static_cast<BinOp::Opcode>(-1);
7793 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007794 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007795 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007796 rhsopc = BO->getOpcode();
7797
7798 // Subs are not binary operators.
7799 if (lhsopc == -1 && rhsopc == -1)
7800 return;
7801
7802 // Bitwise operations are sometimes used as eager logical ops.
7803 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007804 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7805 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007806 return;
7807
Richard Trieu73088052011-08-10 22:41:34 +00007808 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7809 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7810 if (!isLeftComp && !isRightComp) return;
7811
7812 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7813 : SourceRange(OpLoc, rhs->getLocEnd());
7814 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7815 : BinOp::getOpcodeStr(rhsopc);
7816 SourceRange ParensRange = isLeftComp ?
7817 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7818 rhs->getLocEnd())
7819 : SourceRange(lhs->getLocStart(),
7820 cast<BinOp>(rhs)->getLHS()->getLocStart());
7821
7822 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7823 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7824 SuggestParentheses(Self, OpLoc,
7825 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7826 rhs->getSourceRange());
7827 SuggestParentheses(Self, OpLoc,
7828 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7829 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007830}
7831
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007832/// \brief It accepts a '&' expr that is inside a '|' one.
7833/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7834/// in parentheses.
7835static void
7836EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7837 BinaryOperator *Bop) {
7838 assert(Bop->getOpcode() == BO_And);
7839 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7840 << Bop->getSourceRange() << OpLoc;
7841 SuggestParentheses(Self, Bop->getOperatorLoc(),
7842 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7843 Bop->getSourceRange());
7844}
7845
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007846/// \brief It accepts a '&&' expr that is inside a '||' one.
7847/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7848/// in parentheses.
7849static void
7850EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007851 BinaryOperator *Bop) {
7852 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007853 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7854 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007855 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007856 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007857 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007858}
7859
7860/// \brief Returns true if the given expression can be evaluated as a constant
7861/// 'true'.
7862static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7863 bool Res;
7864 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7865}
7866
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007867/// \brief Returns true if the given expression can be evaluated as a constant
7868/// 'false'.
7869static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7870 bool Res;
7871 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7872}
7873
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007874/// \brief Look for '&&' in the left hand of a '||' expr.
7875static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007876 Expr *OrLHS, Expr *OrRHS) {
7877 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007878 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007879 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7880 if (EvaluatesAsFalse(S, OrRHS))
7881 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007882 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7883 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7884 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7885 } else if (Bop->getOpcode() == BO_LOr) {
7886 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7887 // If it's "a || b && 1 || c" we didn't warn earlier for
7888 // "a || b && 1", but warn now.
7889 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7890 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7891 }
7892 }
7893 }
7894}
7895
7896/// \brief Look for '&&' in the right hand of a '||' expr.
7897static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007898 Expr *OrLHS, Expr *OrRHS) {
7899 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007900 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007901 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7902 if (EvaluatesAsFalse(S, OrLHS))
7903 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007904 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7905 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7906 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007907 }
7908 }
7909}
7910
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007911/// \brief Look for '&' in the left or right hand of a '|' expr.
7912static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7913 Expr *OrArg) {
7914 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7915 if (Bop->getOpcode() == BO_And)
7916 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7917 }
7918}
7919
Sebastian Redl43028242009-10-26 15:24:15 +00007920/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007921/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007922static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007923 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007924 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007925 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007926 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7927
7928 // Diagnose "arg1 & arg2 | arg3"
7929 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7930 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7931 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7932 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007933
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007934 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7935 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007936 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007937 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7938 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007939 }
Sebastian Redl43028242009-10-26 15:24:15 +00007940}
7941
Steve Naroff218bc2b2007-05-04 21:54:46 +00007942// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007943ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007944 tok::TokenKind Kind,
7945 Expr *lhs, Expr *rhs) {
7946 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007947 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7948 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007949
Sebastian Redl43028242009-10-26 15:24:15 +00007950 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7951 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7952
Douglas Gregor5287f092009-11-05 00:51:44 +00007953 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7954}
7955
John McCalldadc5752010-08-24 06:29:42 +00007956ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007957 BinaryOperatorKind Opc,
7958 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007959 if (getLangOptions().CPlusPlus) {
7960 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007961
John McCall622114c2010-12-06 05:26:58 +00007962 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7963 UseBuiltinOperator = false;
7964 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7965 UseBuiltinOperator = true;
7966 } else {
7967 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7968 !rhs->getType()->isOverloadableType();
7969 }
7970
7971 if (!UseBuiltinOperator) {
7972 // Find all of the overloaded operators visible from this
7973 // point. We perform both an operator-name lookup from the local
7974 // scope and an argument-dependent lookup based on the types of
7975 // the arguments.
7976 UnresolvedSet<16> Functions;
7977 OverloadedOperatorKind OverOp
7978 = BinaryOperator::getOverloadedOperator(Opc);
7979 if (S && OverOp != OO_None)
7980 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7981 Functions);
7982
7983 // Build the (potentially-overloaded, potentially-dependent)
7984 // binary operation.
7985 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7986 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007987 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007988
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007989 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007990 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007991}
7992
John McCalldadc5752010-08-24 06:29:42 +00007993ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007994 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007995 Expr *InputExpr) {
7996 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007997 ExprValueKind VK = VK_RValue;
7998 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007999 QualType resultType;
8000 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008001 case UO_PreInc:
8002 case UO_PreDec:
8003 case UO_PostInc:
8004 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008005 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008006 Opc == UO_PreInc ||
8007 Opc == UO_PostInc,
8008 Opc == UO_PreInc ||
8009 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008010 break;
John McCalle3027922010-08-25 11:45:40 +00008011 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008012 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008013 break;
John McCall31996342011-04-07 08:22:57 +00008014 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008015 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008016 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008017 Input = move(resolved);
8018 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8019 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008020 break;
John McCall31996342011-04-07 08:22:57 +00008021 }
John McCalle3027922010-08-25 11:45:40 +00008022 case UO_Plus:
8023 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008024 Input = UsualUnaryConversions(Input.take());
8025 if (Input.isInvalid()) return ExprError();
8026 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008027 if (resultType->isDependentType())
8028 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008029 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8030 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008031 break;
8032 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8033 resultType->isEnumeralType())
8034 break;
8035 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008036 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008037 resultType->isPointerType())
8038 break;
John McCall36226622010-10-12 02:09:17 +00008039 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008040 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008041 if (Input.isInvalid()) return ExprError();
8042 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008043 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008044
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008045 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008046 << resultType << Input.get()->getSourceRange());
8047
John McCalle3027922010-08-25 11:45:40 +00008048 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008049 Input = UsualUnaryConversions(Input.take());
8050 if (Input.isInvalid()) return ExprError();
8051 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008052 if (resultType->isDependentType())
8053 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008054 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8055 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8056 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008057 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008058 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008059 else if (resultType->hasIntegerRepresentation())
8060 break;
8061 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008062 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008063 if (Input.isInvalid()) return ExprError();
8064 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008065 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008066 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008067 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008068 }
Steve Naroff35d85152007-05-07 00:24:15 +00008069 break;
John Wiegley01296292011-04-08 18:41:53 +00008070
John McCalle3027922010-08-25 11:45:40 +00008071 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008072 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008073 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8074 if (Input.isInvalid()) return ExprError();
8075 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008076 if (resultType->isDependentType())
8077 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008078 if (resultType->isScalarType()) {
8079 // C99 6.5.3.3p1: ok, fallthrough;
8080 if (Context.getLangOptions().CPlusPlus) {
8081 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8082 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008083 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8084 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008085 }
John McCall36226622010-10-12 02:09:17 +00008086 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008087 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008088 if (Input.isInvalid()) return ExprError();
8089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008090 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008091 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008092 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008093 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008094
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008095 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008096 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008097 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008098 break;
John McCalle3027922010-08-25 11:45:40 +00008099 case UO_Real:
8100 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008101 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008102 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008103 if (Input.isInvalid()) return ExprError();
8104 if (Input.get()->getValueKind() != VK_RValue &&
8105 Input.get()->getObjectKind() == OK_Ordinary)
8106 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008107 break;
John McCalle3027922010-08-25 11:45:40 +00008108 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008109 resultType = Input.get()->getType();
8110 VK = Input.get()->getValueKind();
8111 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008112 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008113 }
John Wiegley01296292011-04-08 18:41:53 +00008114 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008115 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008116
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008117 // Check for array bounds violations in the operand of the UnaryOperator,
8118 // except for the '*' and '&' operators that have to be handled specially
8119 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8120 // that are explicitly defined as valid by the standard).
8121 if (Opc != UO_AddrOf && Opc != UO_Deref)
8122 CheckArrayAccess(Input.get());
8123
John Wiegley01296292011-04-08 18:41:53 +00008124 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008125 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008126}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008127
John McCalldadc5752010-08-24 06:29:42 +00008128ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008129 UnaryOperatorKind Opc,
8130 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008131 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008132 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008133 // Find all of the overloaded operators visible from this
8134 // point. We perform both an operator-name lookup from the local
8135 // scope and an argument-dependent lookup based on the types of
8136 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008137 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008138 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008139 if (S && OverOp != OO_None)
8140 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8141 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008142
John McCallb268a282010-08-23 23:25:46 +00008143 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008144 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008145
John McCallb268a282010-08-23 23:25:46 +00008146 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008147}
8148
Douglas Gregor5287f092009-11-05 00:51:44 +00008149// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008150ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008151 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008152 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008153}
8154
Steve Naroff66356bd2007-09-16 14:56:35 +00008155/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008156ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008157 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008158 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008159 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008160 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008161 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008162}
8163
John McCall31168b02011-06-15 23:02:42 +00008164/// Given the last statement in a statement-expression, check whether
8165/// the result is a producing expression (like a call to an
8166/// ns_returns_retained function) and, if so, rebuild it to hoist the
8167/// release out of the full-expression. Otherwise, return null.
8168/// Cannot fail.
8169static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8170 // Should always be wrapped with one of these.
8171 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8172 if (!cleanups) return 0;
8173
8174 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8175 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8176 return 0;
8177
8178 // Splice out the cast. This shouldn't modify any interesting
8179 // features of the statement.
8180 Expr *producer = cast->getSubExpr();
8181 assert(producer->getType() == cast->getType());
8182 assert(producer->getValueKind() == cast->getValueKind());
8183 cleanups->setSubExpr(producer);
8184 return cleanups;
8185}
8186
John McCalldadc5752010-08-24 06:29:42 +00008187ExprResult
John McCallb268a282010-08-23 23:25:46 +00008188Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008189 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008190 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8191 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8192
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008193 bool isFileScope
8194 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008195 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008196 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008197
Chris Lattner366727f2007-07-24 16:58:17 +00008198 // FIXME: there are a variety of strange constraints to enforce here, for
8199 // example, it is not possible to goto into a stmt expression apparently.
8200 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008201
Chris Lattner366727f2007-07-24 16:58:17 +00008202 // If there are sub stmts in the compound stmt, take the type of the last one
8203 // as the type of the stmtexpr.
8204 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008205 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008206 if (!Compound->body_empty()) {
8207 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008208 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008209 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008210 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8211 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008212 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008213 }
John McCall31168b02011-06-15 23:02:42 +00008214
John Wiegley01296292011-04-08 18:41:53 +00008215 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008216 // Do function/array conversion on the last expression, but not
8217 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008218 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8219 if (LastExpr.isInvalid())
8220 return ExprError();
8221 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008222
John Wiegley01296292011-04-08 18:41:53 +00008223 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008224 // In ARC, if the final expression ends in a consume, splice
8225 // the consume out and bind it later. In the alternate case
8226 // (when dealing with a retainable type), the result
8227 // initialization will create a produce. In both cases the
8228 // result will be +1, and we'll need to balance that out with
8229 // a bind.
8230 if (Expr *rebuiltLastStmt
8231 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8232 LastExpr = rebuiltLastStmt;
8233 } else {
8234 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008235 InitializedEntity::InitializeResult(LPLoc,
8236 Ty,
8237 false),
8238 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008239 LastExpr);
8240 }
8241
John Wiegley01296292011-04-08 18:41:53 +00008242 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008243 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008244 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008245 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008246 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008247 else
John Wiegley01296292011-04-08 18:41:53 +00008248 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008249 StmtExprMayBindToTemp = true;
8250 }
8251 }
8252 }
Chris Lattner944d3062008-07-26 19:51:01 +00008253 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008254
Eli Friedmanba961a92009-03-23 00:24:07 +00008255 // FIXME: Check that expression type is complete/non-abstract; statement
8256 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008257 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8258 if (StmtExprMayBindToTemp)
8259 return MaybeBindToTemporary(ResStmtExpr);
8260 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008261}
Steve Naroff78864672007-08-01 22:05:33 +00008262
John McCalldadc5752010-08-24 06:29:42 +00008263ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008264 TypeSourceInfo *TInfo,
8265 OffsetOfComponent *CompPtr,
8266 unsigned NumComponents,
8267 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008268 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008269 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008270 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008271
Chris Lattnerf17bd422007-08-30 17:45:32 +00008272 // We must have at least one component that refers to the type, and the first
8273 // one is known to be a field designator. Verify that the ArgTy represents
8274 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008275 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008276 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8277 << ArgTy << TypeRange);
8278
8279 // Type must be complete per C99 7.17p3 because a declaring a variable
8280 // with an incomplete type would be ill-formed.
8281 if (!Dependent
8282 && RequireCompleteType(BuiltinLoc, ArgTy,
8283 PDiag(diag::err_offsetof_incomplete_type)
8284 << TypeRange))
8285 return ExprError();
8286
Chris Lattner78502cf2007-08-31 21:49:13 +00008287 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8288 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008289 // FIXME: This diagnostic isn't actually visible because the location is in
8290 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008291 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008292 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8293 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008294
8295 bool DidWarnAboutNonPOD = false;
8296 QualType CurrentType = ArgTy;
8297 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008298 SmallVector<OffsetOfNode, 4> Comps;
8299 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008300 for (unsigned i = 0; i != NumComponents; ++i) {
8301 const OffsetOfComponent &OC = CompPtr[i];
8302 if (OC.isBrackets) {
8303 // Offset of an array sub-field. TODO: Should we allow vector elements?
8304 if (!CurrentType->isDependentType()) {
8305 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8306 if(!AT)
8307 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8308 << CurrentType);
8309 CurrentType = AT->getElementType();
8310 } else
8311 CurrentType = Context.DependentTy;
8312
8313 // The expression must be an integral expression.
8314 // FIXME: An integral constant expression?
8315 Expr *Idx = static_cast<Expr*>(OC.U.E);
8316 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8317 !Idx->getType()->isIntegerType())
8318 return ExprError(Diag(Idx->getLocStart(),
8319 diag::err_typecheck_subscript_not_integer)
8320 << Idx->getSourceRange());
8321
8322 // Record this array index.
8323 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8324 Exprs.push_back(Idx);
8325 continue;
8326 }
8327
8328 // Offset of a field.
8329 if (CurrentType->isDependentType()) {
8330 // We have the offset of a field, but we can't look into the dependent
8331 // type. Just record the identifier of the field.
8332 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8333 CurrentType = Context.DependentTy;
8334 continue;
8335 }
8336
8337 // We need to have a complete type to look into.
8338 if (RequireCompleteType(OC.LocStart, CurrentType,
8339 diag::err_offsetof_incomplete_type))
8340 return ExprError();
8341
8342 // Look for the designated field.
8343 const RecordType *RC = CurrentType->getAs<RecordType>();
8344 if (!RC)
8345 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8346 << CurrentType);
8347 RecordDecl *RD = RC->getDecl();
8348
8349 // C++ [lib.support.types]p5:
8350 // The macro offsetof accepts a restricted set of type arguments in this
8351 // International Standard. type shall be a POD structure or a POD union
8352 // (clause 9).
8353 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8354 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008355 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008356 PDiag(diag::warn_offsetof_non_pod_type)
8357 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8358 << CurrentType))
8359 DidWarnAboutNonPOD = true;
8360 }
8361
8362 // Look for the field.
8363 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8364 LookupQualifiedName(R, RD);
8365 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008366 IndirectFieldDecl *IndirectMemberDecl = 0;
8367 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008368 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008369 MemberDecl = IndirectMemberDecl->getAnonField();
8370 }
8371
Douglas Gregor882211c2010-04-28 22:16:22 +00008372 if (!MemberDecl)
8373 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8374 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8375 OC.LocEnd));
8376
Douglas Gregor10982ea2010-04-28 22:36:06 +00008377 // C99 7.17p3:
8378 // (If the specified member is a bit-field, the behavior is undefined.)
8379 //
8380 // We diagnose this as an error.
8381 if (MemberDecl->getBitWidth()) {
8382 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8383 << MemberDecl->getDeclName()
8384 << SourceRange(BuiltinLoc, RParenLoc);
8385 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8386 return ExprError();
8387 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008388
8389 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008390 if (IndirectMemberDecl)
8391 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008392
Douglas Gregord1702062010-04-29 00:18:15 +00008393 // If the member was found in a base class, introduce OffsetOfNodes for
8394 // the base class indirections.
8395 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8396 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008397 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008398 CXXBasePath &Path = Paths.front();
8399 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8400 B != BEnd; ++B)
8401 Comps.push_back(OffsetOfNode(B->Base));
8402 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008403
Francois Pichet783dd6e2010-11-21 06:08:52 +00008404 if (IndirectMemberDecl) {
8405 for (IndirectFieldDecl::chain_iterator FI =
8406 IndirectMemberDecl->chain_begin(),
8407 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8408 assert(isa<FieldDecl>(*FI));
8409 Comps.push_back(OffsetOfNode(OC.LocStart,
8410 cast<FieldDecl>(*FI), OC.LocEnd));
8411 }
8412 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008413 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008414
Douglas Gregor882211c2010-04-28 22:16:22 +00008415 CurrentType = MemberDecl->getType().getNonReferenceType();
8416 }
8417
8418 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8419 TInfo, Comps.data(), Comps.size(),
8420 Exprs.data(), Exprs.size(), RParenLoc));
8421}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008422
John McCalldadc5752010-08-24 06:29:42 +00008423ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008424 SourceLocation BuiltinLoc,
8425 SourceLocation TypeLoc,
8426 ParsedType argty,
8427 OffsetOfComponent *CompPtr,
8428 unsigned NumComponents,
8429 SourceLocation RPLoc) {
8430
Douglas Gregor882211c2010-04-28 22:16:22 +00008431 TypeSourceInfo *ArgTInfo;
8432 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8433 if (ArgTy.isNull())
8434 return ExprError();
8435
Eli Friedman06dcfd92010-08-05 10:15:45 +00008436 if (!ArgTInfo)
8437 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8438
8439 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8440 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008441}
8442
8443
John McCalldadc5752010-08-24 06:29:42 +00008444ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008445 Expr *CondExpr,
8446 Expr *LHSExpr, Expr *RHSExpr,
8447 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008448 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8449
John McCall7decc9e2010-11-18 06:31:45 +00008450 ExprValueKind VK = VK_RValue;
8451 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008452 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008453 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008454 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008455 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008456 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008457 } else {
8458 // The conditional expression is required to be a constant expression.
8459 llvm::APSInt condEval(32);
8460 SourceLocation ExpLoc;
8461 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008462 return ExprError(Diag(ExpLoc,
8463 diag::err_typecheck_choose_expr_requires_constant)
8464 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008465
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008466 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008467 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8468
8469 resType = ActiveExpr->getType();
8470 ValueDependent = ActiveExpr->isValueDependent();
8471 VK = ActiveExpr->getValueKind();
8472 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008473 }
8474
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008475 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008476 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008477 resType->isDependentType(),
8478 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008479}
8480
Steve Naroffc540d662008-09-03 18:15:37 +00008481//===----------------------------------------------------------------------===//
8482// Clang Extensions.
8483//===----------------------------------------------------------------------===//
8484
8485/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008486void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008487 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8488 PushBlockScope(BlockScope, Block);
8489 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008490 if (BlockScope)
8491 PushDeclContext(BlockScope, Block);
8492 else
8493 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008494}
8495
Mike Stump82f071f2009-02-04 22:31:32 +00008496void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008497 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008498 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008499 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008500
John McCall8cb7bdf2010-06-04 23:28:52 +00008501 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008502 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008503
John McCall3882ace2011-01-05 12:14:39 +00008504 // GetTypeForDeclarator always produces a function type for a block
8505 // literal signature. Furthermore, it is always a FunctionProtoType
8506 // unless the function was written with a typedef.
8507 assert(T->isFunctionType() &&
8508 "GetTypeForDeclarator made a non-function block signature");
8509
8510 // Look for an explicit signature in that function type.
8511 FunctionProtoTypeLoc ExplicitSignature;
8512
8513 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8514 if (isa<FunctionProtoTypeLoc>(tmp)) {
8515 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8516
8517 // Check whether that explicit signature was synthesized by
8518 // GetTypeForDeclarator. If so, don't save that as part of the
8519 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008520 if (ExplicitSignature.getLocalRangeBegin() ==
8521 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008522 // This would be much cheaper if we stored TypeLocs instead of
8523 // TypeSourceInfos.
8524 TypeLoc Result = ExplicitSignature.getResultLoc();
8525 unsigned Size = Result.getFullDataSize();
8526 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8527 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8528
8529 ExplicitSignature = FunctionProtoTypeLoc();
8530 }
John McCalla3ccba02010-06-04 11:21:44 +00008531 }
Mike Stump11289f42009-09-09 15:08:12 +00008532
John McCall3882ace2011-01-05 12:14:39 +00008533 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8534 CurBlock->FunctionType = T;
8535
8536 const FunctionType *Fn = T->getAs<FunctionType>();
8537 QualType RetTy = Fn->getResultType();
8538 bool isVariadic =
8539 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8540
John McCall8e346702010-06-04 19:02:56 +00008541 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008542
John McCalla3ccba02010-06-04 11:21:44 +00008543 // Don't allow returning a objc interface by value.
8544 if (RetTy->isObjCObjectType()) {
8545 Diag(ParamInfo.getSourceRange().getBegin(),
8546 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8547 return;
8548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008549
John McCalla3ccba02010-06-04 11:21:44 +00008550 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008551 // return type. TODO: what should we do with declarators like:
8552 // ^ * { ... }
8553 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008554 if (RetTy != Context.DependentTy)
8555 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008556
John McCalla3ccba02010-06-04 11:21:44 +00008557 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008558 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008559 if (ExplicitSignature) {
8560 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8561 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008562 if (Param->getIdentifier() == 0 &&
8563 !Param->isImplicit() &&
8564 !Param->isInvalidDecl() &&
8565 !getLangOptions().CPlusPlus)
8566 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008567 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008568 }
John McCalla3ccba02010-06-04 11:21:44 +00008569
8570 // Fake up parameter variables if we have a typedef, like
8571 // ^ fntype { ... }
8572 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8573 for (FunctionProtoType::arg_type_iterator
8574 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8575 ParmVarDecl *Param =
8576 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8577 ParamInfo.getSourceRange().getBegin(),
8578 *I);
John McCall8e346702010-06-04 19:02:56 +00008579 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008580 }
Steve Naroffc540d662008-09-03 18:15:37 +00008581 }
John McCalla3ccba02010-06-04 11:21:44 +00008582
John McCall8e346702010-06-04 19:02:56 +00008583 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008584 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008585 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008586 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8587 CurBlock->TheDecl->param_end(),
8588 /*CheckParameterNames=*/false);
8589 }
8590
John McCalla3ccba02010-06-04 11:21:44 +00008591 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008592 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008593
John McCall8e346702010-06-04 19:02:56 +00008594 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008595 Diag(ParamInfo.getAttributes()->getLoc(),
8596 diag::warn_attribute_sentinel_not_variadic) << 1;
8597 // FIXME: remove the attribute.
8598 }
8599
8600 // Put the parameter variables in scope. We can bail out immediately
8601 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008602 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008603 return;
8604
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008605 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008606 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8607 (*AI)->setOwningFunction(CurBlock->TheDecl);
8608
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008609 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008610 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008611 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008612
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008613 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008614 }
John McCallf7b2fb52010-01-22 00:28:27 +00008615 }
Steve Naroffc540d662008-09-03 18:15:37 +00008616}
8617
8618/// ActOnBlockError - If there is an error parsing a block, this callback
8619/// is invoked to pop the information about the block from the action impl.
8620void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008621 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008622 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008623 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008624}
8625
8626/// ActOnBlockStmtExpr - This is called when the body of a block statement
8627/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008628ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008629 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008630 // If blocks are disabled, emit an error.
8631 if (!LangOpts.Blocks)
8632 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008633
Douglas Gregor9a28e842010-03-01 23:15:13 +00008634 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008635
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008636 PopDeclContext();
8637
Steve Naroffc540d662008-09-03 18:15:37 +00008638 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008639 if (!BSI->ReturnType.isNull())
8640 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008641
Mike Stump3bf1ab42009-07-28 22:04:01 +00008642 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008643 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008644
John McCallc63de662011-02-02 13:00:07 +00008645 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008646 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8647 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008648
John McCall8e346702010-06-04 19:02:56 +00008649 // If the user wrote a function type in some form, try to use that.
8650 if (!BSI->FunctionType.isNull()) {
8651 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8652
8653 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8654 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8655
8656 // Turn protoless block types into nullary block types.
8657 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008658 FunctionProtoType::ExtProtoInfo EPI;
8659 EPI.ExtInfo = Ext;
8660 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008661
8662 // Otherwise, if we don't need to change anything about the function type,
8663 // preserve its sugar structure.
8664 } else if (FTy->getResultType() == RetTy &&
8665 (!NoReturn || FTy->getNoReturnAttr())) {
8666 BlockTy = BSI->FunctionType;
8667
8668 // Otherwise, make the minimal modifications to the function type.
8669 } else {
8670 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008671 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8672 EPI.TypeQuals = 0; // FIXME: silently?
8673 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008674 BlockTy = Context.getFunctionType(RetTy,
8675 FPT->arg_type_begin(),
8676 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008677 EPI);
John McCall8e346702010-06-04 19:02:56 +00008678 }
8679
8680 // If we don't have a function type, just build one from nothing.
8681 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008682 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008683 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008684 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008685 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008686
John McCall8e346702010-06-04 19:02:56 +00008687 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8688 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008689 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008690
Chris Lattner45542ea2009-04-19 05:28:12 +00008691 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008692 if (getCurFunction()->NeedsScopeChecking() &&
8693 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008694 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008695
Chris Lattner60f84492011-02-17 23:58:47 +00008696 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008697
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008698 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8699 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8700 const VarDecl *variable = ci->getVariable();
8701 QualType T = variable->getType();
8702 QualType::DestructionKind destructKind = T.isDestructedType();
8703 if (destructKind != QualType::DK_none)
8704 getCurFunction()->setHasBranchProtectedScope();
8705 }
8706
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008707 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8708 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8709 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8710
Douglas Gregor9a28e842010-03-01 23:15:13 +00008711 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008712}
8713
John McCalldadc5752010-08-24 06:29:42 +00008714ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008715 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008716 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008717 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008718 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008719 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008720}
8721
John McCalldadc5752010-08-24 06:29:42 +00008722ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008723 Expr *E, TypeSourceInfo *TInfo,
8724 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008725 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008726
Eli Friedman121ba0c2008-08-09 23:32:40 +00008727 // Get the va_list type
8728 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008729 if (VaListType->isArrayType()) {
8730 // Deal with implicit array decay; for example, on x86-64,
8731 // va_list is an array, but it's supposed to decay to
8732 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008733 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008734 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008735 ExprResult Result = UsualUnaryConversions(E);
8736 if (Result.isInvalid())
8737 return ExprError();
8738 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008739 } else {
8740 // Otherwise, the va_list argument must be an l-value because
8741 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008742 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008743 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008744 return ExprError();
8745 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008746
Douglas Gregorad3150c2009-05-19 23:10:31 +00008747 if (!E->isTypeDependent() &&
8748 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008749 return ExprError(Diag(E->getLocStart(),
8750 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008751 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008752 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008753
David Majnemerc75d1a12011-06-14 05:17:32 +00008754 if (!TInfo->getType()->isDependentType()) {
8755 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8756 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8757 << TInfo->getTypeLoc().getSourceRange()))
8758 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008759
David Majnemerc75d1a12011-06-14 05:17:32 +00008760 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8761 TInfo->getType(),
8762 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8763 << TInfo->getTypeLoc().getSourceRange()))
8764 return ExprError();
8765
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008766 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008767 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008768 TInfo->getType()->isObjCLifetimeType()
8769 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8770 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008771 << TInfo->getType()
8772 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008773 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008774
8775 // Check for va_arg where arguments of the given type will be promoted
8776 // (i.e. this va_arg is guaranteed to have undefined behavior).
8777 QualType PromoteType;
8778 if (TInfo->getType()->isPromotableIntegerType()) {
8779 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8780 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8781 PromoteType = QualType();
8782 }
8783 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8784 PromoteType = Context.DoubleTy;
8785 if (!PromoteType.isNull())
8786 Diag(TInfo->getTypeLoc().getBeginLoc(),
8787 diag::warn_second_parameter_to_va_arg_never_compatible)
8788 << TInfo->getType()
8789 << PromoteType
8790 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008791 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008792
Abramo Bagnara27db2392010-08-10 10:06:15 +00008793 QualType T = TInfo->getType().getNonLValueExprType(Context);
8794 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008795}
8796
John McCalldadc5752010-08-24 06:29:42 +00008797ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008798 // The type of __null will be int or long, depending on the size of
8799 // pointers on the target.
8800 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008801 unsigned pw = Context.Target.getPointerWidth(0);
8802 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008803 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008804 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008805 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008806 else if (pw == Context.Target.getLongLongWidth())
8807 Ty = Context.LongLongTy;
8808 else {
8809 assert(!"I don't know size of pointer!");
8810 Ty = Context.IntTy;
8811 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008812
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008813 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008814}
8815
Alexis Huntc46382e2010-04-28 23:02:27 +00008816static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008817 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008818 if (!SemaRef.getLangOptions().ObjC1)
8819 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008820
Anders Carlssonace5d072009-11-10 04:46:30 +00008821 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8822 if (!PT)
8823 return;
8824
8825 // Check if the destination is of type 'id'.
8826 if (!PT->isObjCIdType()) {
8827 // Check if the destination is the 'NSString' interface.
8828 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8829 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8830 return;
8831 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008832
Anders Carlssonace5d072009-11-10 04:46:30 +00008833 // Strip off any parens and casts.
8834 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008835 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008836 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008837
Douglas Gregora771f462010-03-31 17:46:05 +00008838 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008839}
8840
Chris Lattner9bad62c2008-01-04 18:04:52 +00008841bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8842 SourceLocation Loc,
8843 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008844 Expr *SrcExpr, AssignmentAction Action,
8845 bool *Complained) {
8846 if (Complained)
8847 *Complained = false;
8848
Chris Lattner9bad62c2008-01-04 18:04:52 +00008849 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008850 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008851 bool isInvalid = false;
8852 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008853 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008854 ConversionFixItGenerator ConvHints;
8855 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008856
Chris Lattner9bad62c2008-01-04 18:04:52 +00008857 switch (ConvTy) {
8858 default: assert(0 && "Unknown conversion type");
8859 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008860 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008861 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008862 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8863 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008864 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008865 case IntToPointer:
8866 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008867 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8868 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008869 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008870 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008871 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008872 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008873 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8874 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008875 if (Hint.isNull() && !CheckInferredResultType) {
8876 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8877 }
8878 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008879 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008880 case IncompatiblePointerSign:
8881 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8882 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008883 case FunctionVoidPointer:
8884 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8885 break;
John McCall4fff8f62011-02-01 00:10:29 +00008886 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008887 // Perform array-to-pointer decay if necessary.
8888 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8889
John McCall4fff8f62011-02-01 00:10:29 +00008890 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8891 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8892 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8893 DiagKind = diag::err_typecheck_incompatible_address_space;
8894 break;
John McCall31168b02011-06-15 23:02:42 +00008895
8896
8897 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008898 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008899 break;
John McCall4fff8f62011-02-01 00:10:29 +00008900 }
8901
8902 llvm_unreachable("unknown error case for discarding qualifiers!");
8903 // fallthrough
8904 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008905 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008906 // If the qualifiers lost were because we were applying the
8907 // (deprecated) C++ conversion from a string literal to a char*
8908 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8909 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008910 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008911 // bit of refactoring (so that the second argument is an
8912 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008913 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008914 // C++ semantics.
8915 if (getLangOptions().CPlusPlus &&
8916 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8917 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008918 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8919 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008920 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008921 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008922 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008923 case IntToBlockPointer:
8924 DiagKind = diag::err_int_to_block_pointer;
8925 break;
8926 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008927 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008928 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008929 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008930 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008931 // it can give a more specific diagnostic.
8932 DiagKind = diag::warn_incompatible_qualified_id;
8933 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008934 case IncompatibleVectors:
8935 DiagKind = diag::warn_incompatible_vectors;
8936 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008937 case IncompatibleObjCWeakRef:
8938 DiagKind = diag::err_arc_weak_unavailable_assign;
8939 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008940 case Incompatible:
8941 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008942 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8943 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008944 isInvalid = true;
8945 break;
8946 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008947
Douglas Gregorc68e1402010-04-09 00:35:39 +00008948 QualType FirstType, SecondType;
8949 switch (Action) {
8950 case AA_Assigning:
8951 case AA_Initializing:
8952 // The destination type comes first.
8953 FirstType = DstType;
8954 SecondType = SrcType;
8955 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008956
Douglas Gregorc68e1402010-04-09 00:35:39 +00008957 case AA_Returning:
8958 case AA_Passing:
8959 case AA_Converting:
8960 case AA_Sending:
8961 case AA_Casting:
8962 // The source type comes first.
8963 FirstType = SrcType;
8964 SecondType = DstType;
8965 break;
8966 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008967
Anna Zaks3b402712011-07-28 19:51:27 +00008968 PartialDiagnostic FDiag = PDiag(DiagKind);
8969 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8970
8971 // If we can fix the conversion, suggest the FixIts.
8972 assert(ConvHints.isNull() || Hint.isNull());
8973 if (!ConvHints.isNull()) {
8974 for (llvm::SmallVector<FixItHint, 1>::iterator
8975 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8976 HI != HE; ++HI)
8977 FDiag << *HI;
8978 } else {
8979 FDiag << Hint;
8980 }
8981 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8982
8983 Diag(Loc, FDiag);
8984
Douglas Gregor33823722011-06-11 01:09:30 +00008985 if (CheckInferredResultType)
8986 EmitRelatedResultTypeNote(SrcExpr);
8987
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008988 if (Complained)
8989 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008990 return isInvalid;
8991}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008992
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008993bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008994 llvm::APSInt ICEResult;
8995 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8996 if (Result)
8997 *Result = ICEResult;
8998 return false;
8999 }
9000
Anders Carlssone54e8a12008-11-30 19:50:32 +00009001 Expr::EvalResult EvalResult;
9002
Mike Stump4e1f26a2009-02-19 03:04:26 +00009003 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009004 EvalResult.HasSideEffects) {
9005 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9006
9007 if (EvalResult.Diag) {
9008 // We only show the note if it's not the usual "invalid subexpression"
9009 // or if it's actually in a subexpression.
9010 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9011 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9012 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9013 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009014
Anders Carlssone54e8a12008-11-30 19:50:32 +00009015 return true;
9016 }
9017
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009018 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9019 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009020
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009021 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009022 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9023 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009024 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009025
Anders Carlssone54e8a12008-11-30 19:50:32 +00009026 if (Result)
9027 *Result = EvalResult.Val.getInt();
9028 return false;
9029}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009030
Douglas Gregorff790f12009-11-26 00:44:06 +00009031void
Mike Stump11289f42009-09-09 15:08:12 +00009032Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009033 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009034 ExpressionEvaluationContextRecord(NewContext,
9035 ExprTemporaries.size(),
9036 ExprNeedsCleanups));
9037 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009038}
9039
Richard Trieucfc491d2011-08-02 04:35:43 +00009040void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009041 // Pop the current expression evaluation context off the stack.
9042 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9043 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009044
Douglas Gregorfab31f42009-12-12 07:57:52 +00009045 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9046 if (Rec.PotentiallyReferenced) {
9047 // Mark any remaining declarations in the current position of the stack
9048 // as "referenced". If they were not meant to be referenced, semantic
9049 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009050 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009051 I = Rec.PotentiallyReferenced->begin(),
9052 IEnd = Rec.PotentiallyReferenced->end();
9053 I != IEnd; ++I)
9054 MarkDeclarationReferenced(I->first, I->second);
9055 }
9056
9057 if (Rec.PotentiallyDiagnosed) {
9058 // Emit any pending diagnostics.
9059 for (PotentiallyEmittedDiagnostics::iterator
9060 I = Rec.PotentiallyDiagnosed->begin(),
9061 IEnd = Rec.PotentiallyDiagnosed->end();
9062 I != IEnd; ++I)
9063 Diag(I->first, I->second);
9064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009065 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009066
9067 // When are coming out of an unevaluated context, clear out any
9068 // temporaries that we may have created as part of the evaluation of
9069 // the expression in that context: they aren't relevant because they
9070 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009071 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009072 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9073 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009074 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9075
9076 // Otherwise, merge the contexts together.
9077 } else {
9078 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9079 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009080
9081 // Destroy the popped expression evaluation record.
9082 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009083}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009084
John McCall31168b02011-06-15 23:02:42 +00009085void Sema::DiscardCleanupsInEvaluationContext() {
9086 ExprTemporaries.erase(
9087 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9088 ExprTemporaries.end());
9089 ExprNeedsCleanups = false;
9090}
9091
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009092/// \brief Note that the given declaration was referenced in the source code.
9093///
9094/// This routine should be invoke whenever a given declaration is referenced
9095/// in the source code, and where that reference occurred. If this declaration
9096/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9097/// C99 6.9p3), then the declaration will be marked as used.
9098///
9099/// \param Loc the location where the declaration was referenced.
9100///
9101/// \param D the declaration that has been referenced by the source code.
9102void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9103 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009104
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009105 D->setReferenced();
9106
Douglas Gregorebada0772010-06-17 23:14:26 +00009107 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009108 return;
Mike Stump11289f42009-09-09 15:08:12 +00009109
Richard Trieucfc491d2011-08-02 04:35:43 +00009110 // Mark a parameter or variable declaration "used", regardless of whether
9111 // we're in a template or not. The reason for this is that unevaluated
9112 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9113 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009114 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009115 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009116 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009117 return;
9118 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009119
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009120 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9121 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009122
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009123 // Do not mark anything as "used" within a dependent context; wait for
9124 // an instantiation.
9125 if (CurContext->isDependentContext())
9126 return;
Mike Stump11289f42009-09-09 15:08:12 +00009127
Douglas Gregorff790f12009-11-26 00:44:06 +00009128 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009129 case Unevaluated:
9130 // We are in an expression that is not potentially evaluated; do nothing.
9131 return;
Mike Stump11289f42009-09-09 15:08:12 +00009132
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009133 case PotentiallyEvaluated:
9134 // We are in a potentially-evaluated expression, so this declaration is
9135 // "used"; handle this below.
9136 break;
Mike Stump11289f42009-09-09 15:08:12 +00009137
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009138 case PotentiallyPotentiallyEvaluated:
9139 // We are in an expression that may be potentially evaluated; queue this
9140 // declaration reference until we know whether the expression is
9141 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009142 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009143 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009144
9145 case PotentiallyEvaluatedIfUsed:
9146 // Referenced declarations will only be used if the construct in the
9147 // containing expression is used.
9148 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009149 }
Mike Stump11289f42009-09-09 15:08:12 +00009150
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009151 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009152 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009153 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9154 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00009155 return;
9156 if (!Constructor->isUsed(false))
9157 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00009158 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00009159 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009160 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009161 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009162 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009163
Douglas Gregor88d292c2010-05-13 16:44:06 +00009164 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009165 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009166 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009167 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009168 if (Destructor->isVirtual())
9169 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009170 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009171 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009172 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009173 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009174 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009175 } else if (MethodDecl->isVirtual())
9176 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009177 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009178 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009179 // Recursive functions should be marked when used from another function.
9180 if (CurContext == Function) return;
9181
Mike Stump11289f42009-09-09 15:08:12 +00009182 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009183 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009184 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009185 bool AlreadyInstantiated = false;
9186 if (FunctionTemplateSpecializationInfo *SpecInfo
9187 = Function->getTemplateSpecializationInfo()) {
9188 if (SpecInfo->getPointOfInstantiation().isInvalid())
9189 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009190 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009191 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009192 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009193 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009194 = Function->getMemberSpecializationInfo()) {
9195 if (MSInfo->getPointOfInstantiation().isInvalid())
9196 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009197 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009198 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009199 AlreadyInstantiated = true;
9200 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009201
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009202 if (!AlreadyInstantiated) {
9203 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9204 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9205 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9206 Loc));
9207 else
Chandler Carruth54080172010-08-25 08:44:16 +00009208 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009209 }
John McCall83779672011-02-19 02:53:41 +00009210 } else {
9211 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009212 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9213 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009214 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009215 MarkDeclarationReferenced(Loc, *i);
9216 }
John McCall83779672011-02-19 02:53:41 +00009217 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009218
John McCall83779672011-02-19 02:53:41 +00009219 // Keep track of used but undefined functions.
9220 if (!Function->isPure() && !Function->hasBody() &&
9221 Function->getLinkage() != ExternalLinkage) {
9222 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9223 if (old.isInvalid()) old = Loc;
9224 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009225
John McCall83779672011-02-19 02:53:41 +00009226 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009227 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009228 }
Mike Stump11289f42009-09-09 15:08:12 +00009229
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009230 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009231 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009232 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009233 Var->getInstantiatedFromStaticDataMember()) {
9234 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9235 assert(MSInfo && "Missing member specialization information?");
9236 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9237 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9238 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009239 // This is a modification of an existing AST node. Notify listeners.
9240 if (ASTMutationListener *L = getASTMutationListener())
9241 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009242 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009243 }
9244 }
Mike Stump11289f42009-09-09 15:08:12 +00009245
John McCall15dd4042011-02-21 19:25:48 +00009246 // Keep track of used but undefined variables. We make a hole in
9247 // the warning for static const data members with in-line
9248 // initializers.
John McCall83779672011-02-19 02:53:41 +00009249 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009250 && Var->getLinkage() != ExternalLinkage
9251 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009252 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9253 if (old.isInvalid()) old = Loc;
9254 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009255
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009256 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009257 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009258 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009259}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009260
Douglas Gregor5597ab42010-05-07 23:12:07 +00009261namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009262 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009263 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009264 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009265 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9266 Sema &S;
9267 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009268
Douglas Gregor5597ab42010-05-07 23:12:07 +00009269 public:
9270 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009271
Douglas Gregor5597ab42010-05-07 23:12:07 +00009272 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009273
9274 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9275 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009276 };
9277}
9278
Chandler Carruthaf80f662010-06-09 08:17:30 +00009279bool MarkReferencedDecls::TraverseTemplateArgument(
9280 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009281 if (Arg.getKind() == TemplateArgument::Declaration) {
9282 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9283 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009284
9285 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009286}
9287
Chandler Carruthaf80f662010-06-09 08:17:30 +00009288bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009289 if (ClassTemplateSpecializationDecl *Spec
9290 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9291 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009292 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009293 }
9294
Chandler Carruthc65667c2010-06-10 10:31:57 +00009295 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009296}
9297
9298void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9299 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009300 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009301}
9302
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009303namespace {
9304 /// \brief Helper class that marks all of the declarations referenced by
9305 /// potentially-evaluated subexpressions as "referenced".
9306 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9307 Sema &S;
9308
9309 public:
9310 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9311
9312 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9313
9314 void VisitDeclRefExpr(DeclRefExpr *E) {
9315 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9316 }
9317
9318 void VisitMemberExpr(MemberExpr *E) {
9319 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009320 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009321 }
9322
9323 void VisitCXXNewExpr(CXXNewExpr *E) {
9324 if (E->getConstructor())
9325 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9326 if (E->getOperatorNew())
9327 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9328 if (E->getOperatorDelete())
9329 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009330 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009331 }
9332
9333 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9334 if (E->getOperatorDelete())
9335 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009336 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9337 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9338 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9339 S.MarkDeclarationReferenced(E->getLocStart(),
9340 S.LookupDestructor(Record));
9341 }
9342
Douglas Gregor32b3de52010-09-11 23:32:50 +00009343 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009344 }
9345
9346 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9347 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009348 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009349 }
9350
9351 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9352 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9353 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009354
9355 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9356 Visit(E->getExpr());
9357 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009358 };
9359}
9360
9361/// \brief Mark any declarations that appear within this expression or any
9362/// potentially-evaluated subexpressions as "referenced".
9363void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9364 EvaluatedExprMarker(*this).Visit(E);
9365}
9366
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009367/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9368/// of the program being compiled.
9369///
9370/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009371/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009372/// possibility that the code will actually be executable. Code in sizeof()
9373/// expressions, code used only during overload resolution, etc., are not
9374/// potentially evaluated. This routine will suppress such diagnostics or,
9375/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009376/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009377/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009378///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009379/// This routine should be used for all diagnostics that describe the run-time
9380/// behavior of a program, such as passing a non-POD value through an ellipsis.
9381/// Failure to do so will likely result in spurious diagnostics or failures
9382/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009383bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009384 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009385 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009386 case Unevaluated:
9387 // The argument will never be evaluated, so don't complain.
9388 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009389
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009390 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009391 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009392 if (stmt && getCurFunctionOrMethodDecl()) {
9393 FunctionScopes.back()->PossiblyUnreachableDiags.
9394 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9395 }
9396 else
9397 Diag(Loc, PD);
9398
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009399 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009400
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009401 case PotentiallyPotentiallyEvaluated:
9402 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9403 break;
9404 }
9405
9406 return false;
9407}
9408
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009409bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9410 CallExpr *CE, FunctionDecl *FD) {
9411 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9412 return false;
9413
9414 PartialDiagnostic Note =
9415 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9416 << FD->getDeclName() : PDiag();
9417 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009418
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009419 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009420 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009421 PDiag(diag::err_call_function_incomplete_return)
9422 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009423 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009424 << CE->getSourceRange(),
9425 std::make_pair(NoteLoc, Note)))
9426 return true;
9427
9428 return false;
9429}
9430
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009431// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009432// will prevent this condition from triggering, which is what we want.
9433void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9434 SourceLocation Loc;
9435
John McCall0506e4a2009-11-11 02:41:58 +00009436 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009437 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009438
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009439 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009440 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009441 return;
9442
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009443 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9444
John McCallb0e419e2009-11-12 00:06:05 +00009445 // Greylist some idioms by putting them into a warning subcategory.
9446 if (ObjCMessageExpr *ME
9447 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9448 Selector Sel = ME->getSelector();
9449
John McCallb0e419e2009-11-12 00:06:05 +00009450 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009451 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009452 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9453
9454 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009455 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009456 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9457 }
John McCall0506e4a2009-11-11 02:41:58 +00009458
John McCalld5707ab2009-10-12 21:59:07 +00009459 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009460 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009461 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009462 return;
9463
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009464 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009465 Loc = Op->getOperatorLoc();
9466 } else {
9467 // Not an assignment.
9468 return;
9469 }
9470
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009471 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009472
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009473 SourceLocation Open = E->getSourceRange().getBegin();
9474 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9475 Diag(Loc, diag::note_condition_assign_silence)
9476 << FixItHint::CreateInsertion(Open, "(")
9477 << FixItHint::CreateInsertion(Close, ")");
9478
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009479 if (IsOrAssign)
9480 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9481 << FixItHint::CreateReplacement(Loc, "!=");
9482 else
9483 Diag(Loc, diag::note_condition_assign_to_comparison)
9484 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009485}
9486
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009487/// \brief Redundant parentheses over an equality comparison can indicate
9488/// that the user intended an assignment used as condition.
9489void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009490 // Don't warn if the parens came from a macro.
9491 SourceLocation parenLoc = parenE->getLocStart();
9492 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9493 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009494 // Don't warn for dependent expressions.
9495 if (parenE->isTypeDependent())
9496 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009497
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009498 Expr *E = parenE->IgnoreParens();
9499
9500 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009501 if (opE->getOpcode() == BO_EQ &&
9502 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9503 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009504 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009505
Ted Kremenekae022092011-02-02 02:20:30 +00009506 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009507 Diag(Loc, diag::note_equality_comparison_silence)
9508 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9509 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009510 Diag(Loc, diag::note_equality_comparison_to_assign)
9511 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009512 }
9513}
9514
John Wiegley01296292011-04-08 18:41:53 +00009515ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009516 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009517 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9518 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009519
John McCall0009fcc2011-04-26 20:42:42 +00009520 ExprResult result = CheckPlaceholderExpr(E);
9521 if (result.isInvalid()) return ExprError();
9522 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009523
John McCall0009fcc2011-04-26 20:42:42 +00009524 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009525 if (getLangOptions().CPlusPlus)
9526 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9527
John Wiegley01296292011-04-08 18:41:53 +00009528 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9529 if (ERes.isInvalid())
9530 return ExprError();
9531 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009532
9533 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009534 if (!T->isScalarType()) { // C99 6.8.4.1p1
9535 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9536 << T << E->getSourceRange();
9537 return ExprError();
9538 }
John McCalld5707ab2009-10-12 21:59:07 +00009539 }
9540
John Wiegley01296292011-04-08 18:41:53 +00009541 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009542}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009543
John McCalldadc5752010-08-24 06:29:42 +00009544ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9545 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009546 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009547 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009548
9549 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009550}
John McCall36e7fe32010-10-12 00:20:44 +00009551
John McCall31996342011-04-07 08:22:57 +00009552namespace {
John McCall2979fe02011-04-12 00:42:48 +00009553 /// A visitor for rebuilding a call to an __unknown_any expression
9554 /// to have an appropriate type.
9555 struct RebuildUnknownAnyFunction
9556 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9557
9558 Sema &S;
9559
9560 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9561
9562 ExprResult VisitStmt(Stmt *S) {
9563 llvm_unreachable("unexpected statement!");
9564 return ExprError();
9565 }
9566
9567 ExprResult VisitExpr(Expr *expr) {
9568 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9569 << expr->getSourceRange();
9570 return ExprError();
9571 }
9572
9573 /// Rebuild an expression which simply semantically wraps another
9574 /// expression which it shares the type and value kind of.
9575 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9576 ExprResult subResult = Visit(expr->getSubExpr());
9577 if (subResult.isInvalid()) return ExprError();
9578
9579 Expr *subExpr = subResult.take();
9580 expr->setSubExpr(subExpr);
9581 expr->setType(subExpr->getType());
9582 expr->setValueKind(subExpr->getValueKind());
9583 assert(expr->getObjectKind() == OK_Ordinary);
9584 return expr;
9585 }
9586
9587 ExprResult VisitParenExpr(ParenExpr *paren) {
9588 return rebuildSugarExpr(paren);
9589 }
9590
9591 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9592 return rebuildSugarExpr(op);
9593 }
9594
9595 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9596 ExprResult subResult = Visit(op->getSubExpr());
9597 if (subResult.isInvalid()) return ExprError();
9598
9599 Expr *subExpr = subResult.take();
9600 op->setSubExpr(subExpr);
9601 op->setType(S.Context.getPointerType(subExpr->getType()));
9602 assert(op->getValueKind() == VK_RValue);
9603 assert(op->getObjectKind() == OK_Ordinary);
9604 return op;
9605 }
9606
9607 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9608 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9609
9610 expr->setType(decl->getType());
9611
9612 assert(expr->getValueKind() == VK_RValue);
9613 if (S.getLangOptions().CPlusPlus &&
9614 !(isa<CXXMethodDecl>(decl) &&
9615 cast<CXXMethodDecl>(decl)->isInstance()))
9616 expr->setValueKind(VK_LValue);
9617
9618 return expr;
9619 }
9620
9621 ExprResult VisitMemberExpr(MemberExpr *mem) {
9622 return resolveDecl(mem, mem->getMemberDecl());
9623 }
9624
9625 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9626 return resolveDecl(ref, ref->getDecl());
9627 }
9628 };
9629}
9630
9631/// Given a function expression of unknown-any type, try to rebuild it
9632/// to have a function type.
9633static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9634 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9635 if (result.isInvalid()) return ExprError();
9636 return S.DefaultFunctionArrayConversion(result.take());
9637}
9638
9639namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009640 /// A visitor for rebuilding an expression of type __unknown_anytype
9641 /// into one which resolves the type directly on the referring
9642 /// expression. Strict preservation of the original source
9643 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009644 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009645 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009646
9647 Sema &S;
9648
9649 /// The current destination type.
9650 QualType DestType;
9651
9652 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9653 : S(S), DestType(castType) {}
9654
John McCall39439732011-04-09 22:50:59 +00009655 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009656 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009657 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009658 }
9659
John McCall2d2e8702011-04-11 07:02:50 +00009660 ExprResult VisitExpr(Expr *expr) {
9661 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9662 << expr->getSourceRange();
9663 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009664 }
9665
John McCall2d2e8702011-04-11 07:02:50 +00009666 ExprResult VisitCallExpr(CallExpr *call);
9667 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9668
John McCall39439732011-04-09 22:50:59 +00009669 /// Rebuild an expression which simply semantically wraps another
9670 /// expression which it shares the type and value kind of.
9671 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9672 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009673 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009674 Expr *subExpr = subResult.take();
9675 expr->setSubExpr(subExpr);
9676 expr->setType(subExpr->getType());
9677 expr->setValueKind(subExpr->getValueKind());
9678 assert(expr->getObjectKind() == OK_Ordinary);
9679 return expr;
9680 }
John McCall31996342011-04-07 08:22:57 +00009681
John McCall39439732011-04-09 22:50:59 +00009682 ExprResult VisitParenExpr(ParenExpr *paren) {
9683 return rebuildSugarExpr(paren);
9684 }
9685
9686 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9687 return rebuildSugarExpr(op);
9688 }
9689
John McCall2979fe02011-04-12 00:42:48 +00009690 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9691 const PointerType *ptr = DestType->getAs<PointerType>();
9692 if (!ptr) {
9693 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9694 << op->getSourceRange();
9695 return ExprError();
9696 }
9697 assert(op->getValueKind() == VK_RValue);
9698 assert(op->getObjectKind() == OK_Ordinary);
9699 op->setType(DestType);
9700
9701 // Build the sub-expression as if it were an object of the pointee type.
9702 DestType = ptr->getPointeeType();
9703 ExprResult subResult = Visit(op->getSubExpr());
9704 if (subResult.isInvalid()) return ExprError();
9705 op->setSubExpr(subResult.take());
9706 return op;
9707 }
9708
John McCall2d2e8702011-04-11 07:02:50 +00009709 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009710
John McCall2979fe02011-04-12 00:42:48 +00009711 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009712
John McCall2979fe02011-04-12 00:42:48 +00009713 ExprResult VisitMemberExpr(MemberExpr *mem) {
9714 return resolveDecl(mem, mem->getMemberDecl());
9715 }
John McCall39439732011-04-09 22:50:59 +00009716
9717 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009718 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009719 }
9720 };
9721}
9722
John McCall2d2e8702011-04-11 07:02:50 +00009723/// Rebuilds a call expression which yielded __unknown_anytype.
9724ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9725 Expr *callee = call->getCallee();
9726
9727 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009728 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009729 FK_FunctionPointer,
9730 FK_BlockPointer
9731 };
9732
9733 FnKind kind;
9734 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009735 if (type == S.Context.BoundMemberTy) {
9736 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9737 kind = FK_MemberFunction;
9738 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009739 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9740 type = ptr->getPointeeType();
9741 kind = FK_FunctionPointer;
9742 } else {
9743 type = type->castAs<BlockPointerType>()->getPointeeType();
9744 kind = FK_BlockPointer;
9745 }
9746 const FunctionType *fnType = type->castAs<FunctionType>();
9747
9748 // Verify that this is a legal result type of a function.
9749 if (DestType->isArrayType() || DestType->isFunctionType()) {
9750 unsigned diagID = diag::err_func_returning_array_function;
9751 if (kind == FK_BlockPointer)
9752 diagID = diag::err_block_returning_array_function;
9753
9754 S.Diag(call->getExprLoc(), diagID)
9755 << DestType->isFunctionType() << DestType;
9756 return ExprError();
9757 }
9758
9759 // Otherwise, go ahead and set DestType as the call's result.
9760 call->setType(DestType.getNonLValueExprType(S.Context));
9761 call->setValueKind(Expr::getValueKindForType(DestType));
9762 assert(call->getObjectKind() == OK_Ordinary);
9763
9764 // Rebuild the function type, replacing the result type with DestType.
9765 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9766 DestType = S.Context.getFunctionType(DestType,
9767 proto->arg_type_begin(),
9768 proto->getNumArgs(),
9769 proto->getExtProtoInfo());
9770 else
9771 DestType = S.Context.getFunctionNoProtoType(DestType,
9772 fnType->getExtInfo());
9773
9774 // Rebuild the appropriate pointer-to-function type.
9775 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009776 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009777 // Nothing to do.
9778 break;
9779
9780 case FK_FunctionPointer:
9781 DestType = S.Context.getPointerType(DestType);
9782 break;
9783
9784 case FK_BlockPointer:
9785 DestType = S.Context.getBlockPointerType(DestType);
9786 break;
9787 }
9788
9789 // Finally, we can recurse.
9790 ExprResult calleeResult = Visit(callee);
9791 if (!calleeResult.isUsable()) return ExprError();
9792 call->setCallee(calleeResult.take());
9793
9794 // Bind a temporary if necessary.
9795 return S.MaybeBindToTemporary(call);
9796}
9797
9798ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009799 // Verify that this is a legal result type of a call.
9800 if (DestType->isArrayType() || DestType->isFunctionType()) {
9801 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9802 << DestType->isFunctionType() << DestType;
9803 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009804 }
9805
John McCall3f4138c2011-07-13 17:56:40 +00009806 // Rewrite the method result type if available.
9807 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9808 assert(method->getResultType() == S.Context.UnknownAnyTy);
9809 method->setResultType(DestType);
9810 }
John McCall2979fe02011-04-12 00:42:48 +00009811
John McCall2d2e8702011-04-11 07:02:50 +00009812 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009813 msg->setType(DestType.getNonReferenceType());
9814 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009815
John McCall2979fe02011-04-12 00:42:48 +00009816 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009817}
9818
9819ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009820 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009821 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009822 assert(ice->getValueKind() == VK_RValue);
9823 assert(ice->getObjectKind() == OK_Ordinary);
9824
John McCall2979fe02011-04-12 00:42:48 +00009825 ice->setType(DestType);
9826
John McCall2d2e8702011-04-11 07:02:50 +00009827 // Rebuild the sub-expression as the pointee (function) type.
9828 DestType = DestType->castAs<PointerType>()->getPointeeType();
9829
9830 ExprResult result = Visit(ice->getSubExpr());
9831 if (!result.isUsable()) return ExprError();
9832
9833 ice->setSubExpr(result.take());
9834 return S.Owned(ice);
9835}
9836
John McCall2979fe02011-04-12 00:42:48 +00009837ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009838 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009839 QualType type = DestType;
9840
9841 // We know how to make this work for certain kinds of decls:
9842
9843 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009844 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall9a877fe2011-08-10 04:12:23 +00009845 if (const PointerType *ptr = type->getAs<PointerType>()) {
9846 DestType = ptr->getPointeeType();
9847 ExprResult result = resolveDecl(expr, decl);
9848 if (result.isInvalid()) return ExprError();
9849 return S.ImpCastExprToType(result.take(), type,
9850 CK_FunctionToPointerDecay, VK_RValue);
9851 }
9852
9853 if (!type->isFunctionType()) {
9854 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9855 << decl << expr->getSourceRange();
9856 return ExprError();
9857 }
John McCall2d2e8702011-04-11 07:02:50 +00009858
John McCall4adb38c2011-04-27 00:36:17 +00009859 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9860 if (method->isInstance()) {
9861 valueKind = VK_RValue;
9862 type = S.Context.BoundMemberTy;
9863 }
9864
John McCall2d2e8702011-04-11 07:02:50 +00009865 // Function references aren't l-values in C.
9866 if (!S.getLangOptions().CPlusPlus)
9867 valueKind = VK_RValue;
9868
9869 // - variables
9870 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009871 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9872 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009873 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009874 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9875 << decl << expr->getSourceRange();
9876 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009877 }
9878
9879 // - nothing else
9880 } else {
9881 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9882 << decl << expr->getSourceRange();
9883 return ExprError();
9884 }
9885
John McCall2979fe02011-04-12 00:42:48 +00009886 decl->setType(DestType);
9887 expr->setType(type);
9888 expr->setValueKind(valueKind);
9889 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009890}
9891
John McCall31996342011-04-07 08:22:57 +00009892/// Check a cast of an unknown-any type. We intentionally only
9893/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009894ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9895 Expr *castExpr, CastKind &castKind,
9896 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009897 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009898 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9899 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009900
John McCall39439732011-04-09 22:50:59 +00009901 castExpr = result.take();
9902 VK = castExpr->getValueKind();
9903 castKind = CK_NoOp;
9904
9905 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009906}
9907
9908static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9909 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009910 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009911 while (true) {
9912 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009913 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009914 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009915 diagID = diag::err_uncasted_call_of_unknown_any;
9916 } else {
John McCall31996342011-04-07 08:22:57 +00009917 break;
John McCall2d2e8702011-04-11 07:02:50 +00009918 }
John McCall31996342011-04-07 08:22:57 +00009919 }
9920
John McCall2d2e8702011-04-11 07:02:50 +00009921 SourceLocation loc;
9922 NamedDecl *d;
9923 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9924 loc = ref->getLocation();
9925 d = ref->getDecl();
9926 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9927 loc = mem->getMemberLoc();
9928 d = mem->getMemberDecl();
9929 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9930 diagID = diag::err_uncasted_call_of_unknown_any;
9931 loc = msg->getSelectorLoc();
9932 d = msg->getMethodDecl();
9933 assert(d && "unknown method returning __unknown_any?");
9934 } else {
9935 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9936 << e->getSourceRange();
9937 return ExprError();
9938 }
9939
9940 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009941
9942 // Never recoverable.
9943 return ExprError();
9944}
9945
John McCall36e7fe32010-10-12 00:20:44 +00009946/// Check for operands with placeholder types and complain if found.
9947/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009948ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009949 // Placeholder types are always *exactly* the appropriate builtin type.
9950 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009951
John McCall31996342011-04-07 08:22:57 +00009952 // Overloaded expressions.
9953 if (type == Context.OverloadTy)
9954 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009955 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009956 QualType(),
9957 diag::err_ovl_unresolvable);
9958
John McCall0009fcc2011-04-26 20:42:42 +00009959 // Bound member functions.
9960 if (type == Context.BoundMemberTy) {
9961 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9962 << E->getSourceRange();
9963 return ExprError();
9964 }
9965
John McCall31996342011-04-07 08:22:57 +00009966 // Expressions of unknown type.
9967 if (type == Context.UnknownAnyTy)
9968 return diagnoseUnknownAnyExpr(*this, E);
9969
9970 assert(!type->isPlaceholderType());
9971 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009972}
Richard Trieu2c850c02011-04-21 21:44:26 +00009973
9974bool Sema::CheckCaseExpression(Expr *expr) {
9975 if (expr->isTypeDependent())
9976 return true;
9977 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9978 return expr->getType()->isIntegralOrEnumerationType();
9979 return false;
9980}