blob: 28ec97f6522893aabbcd72a07422d41c9e39ea1a [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
446 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000447}
448
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000449/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
450/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000451/// interfaces passed by value.
452ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000453 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000454 ExprResult ExprRes = CheckPlaceholderExpr(E);
455 if (ExprRes.isInvalid())
456 return ExprError();
457
458 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000459 if (ExprRes.isInvalid())
460 return ExprError();
461 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000462
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000463 // __builtin_va_start takes the second argument as a "varargs" argument, but
464 // it doesn't actually do anything with it. It doesn't need to be non-pod
465 // etc.
466 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000467 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000468
Douglas Gregor347e0f22011-05-21 19:26:31 +0000469 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000470 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000471 DiagRuntimeBehavior(E->getLocStart(), 0,
472 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
473 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000474 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000475
John McCall31168b02011-06-15 23:02:42 +0000476 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000477 // C++0x [expr.call]p7:
478 // Passing a potentially-evaluated argument of class type (Clause 9)
479 // having a non-trivial copy constructor, a non-trivial move constructor,
480 // or a non-trivial destructor, with no corresponding parameter,
481 // is conditionally-supported with implementation-defined semantics.
482 bool TrivialEnough = false;
483 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
484 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
485 if (Record->hasTrivialCopyConstructor() &&
486 Record->hasTrivialMoveConstructor() &&
487 Record->hasTrivialDestructor())
488 TrivialEnough = true;
489 }
490 }
John McCall31168b02011-06-15 23:02:42 +0000491
492 if (!TrivialEnough &&
493 getLangOptions().ObjCAutoRefCount &&
494 E->getType()->isObjCLifetimeType())
495 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000496
497 if (TrivialEnough) {
498 // Nothing to diagnose. This is okay.
499 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000500 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000501 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000502 << CT)) {
503 // Turn this into a trap.
504 CXXScopeSpec SS;
505 UnqualifiedId Name;
506 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
507 E->getLocStart());
508 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
509 if (TrapFn.isInvalid())
510 return ExprError();
511
512 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
513 MultiExprArg(), E->getLocEnd());
514 if (Call.isInvalid())
515 return ExprError();
516
517 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
518 Call.get(), E);
519 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000520 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000521 E = Comma.get();
John McCall1cd60a22011-08-26 18:41:18 +0000522
523 // Use that to initialize a temporary, or else we might get an
524 // l-value in a varargs position.
525 ExprResult Temp = PerformCopyInitialization(
526 InitializedEntity::InitializeTemporary(E->getType()),
527 E->getLocStart(),
528 Owned(E));
529 if (Temp.isInvalid())
530 return ExprError();
531 E = Temp.get();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000532 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000533 }
534
John Wiegley01296292011-04-08 18:41:53 +0000535 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000536}
537
Chris Lattner513165e2008-07-25 21:10:04 +0000538/// UsualArithmeticConversions - Performs various conversions that are common to
539/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000540/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000541/// responsible for emitting appropriate error diagnostics.
542/// FIXME: verify the conversion rules for "complex int" are consistent with
543/// GCC.
Richard Trieucfc491d2011-08-02 04:35:43 +0000544QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
545 ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000546 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000547 if (!isCompAssign) {
548 lhsExpr = UsualUnaryConversions(lhsExpr.take());
549 if (lhsExpr.isInvalid())
550 return QualType();
551 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000552
John Wiegley01296292011-04-08 18:41:53 +0000553 rhsExpr = UsualUnaryConversions(rhsExpr.take());
554 if (rhsExpr.isInvalid())
555 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000556
Mike Stump11289f42009-09-09 15:08:12 +0000557 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000558 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000559 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000560 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000561 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000562 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000563
564 // If both types are identical, no conversion is needed.
565 if (lhs == rhs)
566 return lhs;
567
568 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
569 // The caller can deal with this (e.g. pointer + int).
570 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
571 return lhs;
572
John McCalld005ac92010-11-13 08:17:45 +0000573 // Apply unary and bitfield promotions to the LHS's type.
574 QualType lhs_unpromoted = lhs;
575 if (lhs->isPromotableIntegerType())
576 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000577 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000578 if (!LHSBitfieldPromoteTy.isNull())
579 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000580 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000581 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000582
John McCalld005ac92010-11-13 08:17:45 +0000583 // If both types are identical, no conversion is needed.
584 if (lhs == rhs)
585 return lhs;
586
587 // At this point, we have two different arithmetic types.
588
589 // Handle complex types first (C99 6.3.1.8p1).
590 bool LHSComplexFloat = lhs->isComplexType();
591 bool RHSComplexFloat = rhs->isComplexType();
592 if (LHSComplexFloat || RHSComplexFloat) {
593 // if we have an integer operand, the result is the complex type.
594
John McCallc5e62b42010-11-13 09:02:35 +0000595 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
596 if (rhs->isIntegerType()) {
597 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000598 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieucfc491d2011-08-02 04:35:43 +0000599 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
600 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000601 } else {
602 assert(rhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000603 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
604 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000605 }
John McCalld005ac92010-11-13 08:17:45 +0000606 return lhs;
607 }
608
John McCallc5e62b42010-11-13 09:02:35 +0000609 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
610 if (!isCompAssign) {
611 // int -> float -> _Complex float
612 if (lhs->isIntegerType()) {
613 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieucfc491d2011-08-02 04:35:43 +0000614 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
615 CK_IntegralToFloating);
616 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
617 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000618 } else {
619 assert(lhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000620 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
621 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000622 }
623 }
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626
627 // This handles complex/complex, complex/float, or float/complex.
628 // When both operands are complex, the shorter operand is converted to the
629 // type of the longer, and that is the type of the result. This corresponds
630 // to what is done when combining two real floating-point operands.
631 // The fun begins when size promotion occur across type domains.
632 // From H&S 6.3.4: When one operand is complex and the other is a real
633 // floating-point type, the less precise type is converted, within it's
634 // real or complex domain, to the precision of the other type. For example,
635 // when combining a "long double" with a "double _Complex", the
636 // "double _Complex" is promoted to "long double _Complex".
637 int order = Context.getFloatingTypeOrder(lhs, rhs);
638
639 // If both are complex, just cast to the more precise type.
640 if (LHSComplexFloat && RHSComplexFloat) {
641 if (order > 0) {
642 // _Complex float -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000643 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
644 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000645 return lhs;
646
647 } else if (order < 0) {
648 // _Complex float -> _Complex double
649 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000650 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
651 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000652 return rhs;
653 }
654 return lhs;
655 }
656
657 // If just the LHS is complex, the RHS needs to be converted,
658 // and the LHS might need to be promoted.
659 if (LHSComplexFloat) {
660 if (order > 0) { // LHS is wider
661 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000662 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000663 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000664 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
665 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000666 return lhs;
667 }
668
669 // RHS is at least as wide. Find its corresponding complex type.
670 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
671
672 // double -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000673 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
674 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000675
676 // _Complex float -> _Complex double
677 if (!isCompAssign && order < 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000678 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
679 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000680
681 return result;
682 }
683
684 // Just the RHS is complex, so the LHS needs to be converted
685 // and the RHS might need to be promoted.
686 assert(RHSComplexFloat);
687
688 if (order < 0) { // RHS is wider
689 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000690 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000691 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000692 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000693 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
694 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000695 }
John McCalld005ac92010-11-13 08:17:45 +0000696 return rhs;
697 }
698
699 // LHS is at least as wide. Find its corresponding complex type.
700 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
701
702 // double -> _Complex double
703 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000704 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
705 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000706
707 // _Complex float -> _Complex double
708 if (order > 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000709 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
710 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000711
712 return result;
713 }
714
715 // Now handle "real" floating types (i.e. float, double, long double).
716 bool LHSFloat = lhs->isRealFloatingType();
717 bool RHSFloat = rhs->isRealFloatingType();
718 if (LHSFloat || RHSFloat) {
719 // If we have two real floating types, convert the smaller operand
720 // to the bigger result.
721 if (LHSFloat && RHSFloat) {
722 int order = Context.getFloatingTypeOrder(lhs, rhs);
723 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000724 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000725 return lhs;
726 }
727
728 assert(order < 0 && "illegal float comparison");
729 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000730 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000731 return rhs;
732 }
733
734 // If we have an integer operand, the result is the real floating type.
735 if (LHSFloat) {
736 if (rhs->isIntegerType()) {
737 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000739 return lhs;
740 }
741
742 // Convert both sides to the appropriate complex float.
743 assert(rhs->isComplexIntegerType());
744 QualType result = Context.getComplexType(lhs);
745
746 // _Complex int -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000747 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
748 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000749
750 // float -> _Complex float
751 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000752 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
753 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000754
755 return result;
756 }
757
758 assert(RHSFloat);
759 if (lhs->isIntegerType()) {
760 // Convert lhs to the rhs floating point type.
761 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000762 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000763 return rhs;
764 }
765
766 // Convert both sides to the appropriate complex float.
767 assert(lhs->isComplexIntegerType());
768 QualType result = Context.getComplexType(rhs);
769
770 // _Complex int -> _Complex float
771 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000772 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
773 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000774
775 // float -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000776 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
777 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000778
779 return result;
780 }
781
782 // Handle GCC complex int extension.
783 // FIXME: if the operands are (int, _Complex long), we currently
784 // don't promote the complex. Also, signedness?
785 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
786 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
787 if (lhsComplexInt && rhsComplexInt) {
788 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
789 rhsComplexInt->getElementType());
790 assert(order && "inequal types with equal element ordering");
791 if (order > 0) {
792 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000793 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000794 return lhs;
795 }
796
797 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000798 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000799 return rhs;
800 } else if (lhsComplexInt) {
801 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000802 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000803 return lhs;
804 } else if (rhsComplexInt) {
805 // int -> _Complex int
806 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000807 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
808 CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000809 return rhs;
810 }
811
812 // Finally, we have two differing integer types.
813 // The rules for this case are in C99 6.3.1.8
814 int compare = Context.getIntegerTypeOrder(lhs, rhs);
815 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
816 rhsSigned = rhs->hasSignedIntegerRepresentation();
817 if (lhsSigned == rhsSigned) {
818 // Same signedness; use the higher-ranked type
819 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000820 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000821 return lhs;
822 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000823 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000824 return rhs;
825 } else if (compare != (lhsSigned ? 1 : -1)) {
826 // The unsigned type has greater than or equal rank to the
827 // signed type, so use the unsigned type
828 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000829 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000830 return lhs;
831 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000832 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000833 return rhs;
834 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
835 // The two types are different widths; if we are here, that
836 // means the signed type is larger than the unsigned type, so
837 // use the signed type.
838 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000839 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000840 return lhs;
841 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000842 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000843 return rhs;
844 } else {
845 // The signed type is higher-ranked than the unsigned type,
846 // but isn't actually any bigger (like unsigned int and long
847 // on most 32-bit systems). Use the unsigned type corresponding
848 // to the signed type.
849 QualType result =
850 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000851 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000852 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000853 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000854 return result;
855 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000856}
857
Chris Lattner513165e2008-07-25 21:10:04 +0000858//===----------------------------------------------------------------------===//
859// Semantic Analysis for various Expression Types
860//===----------------------------------------------------------------------===//
861
862
Peter Collingbourne91147592011-04-15 00:35:48 +0000863ExprResult
864Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
865 SourceLocation DefaultLoc,
866 SourceLocation RParenLoc,
867 Expr *ControllingExpr,
868 MultiTypeArg types,
869 MultiExprArg exprs) {
870 unsigned NumAssocs = types.size();
871 assert(NumAssocs == exprs.size());
872
873 ParsedType *ParsedTypes = types.release();
874 Expr **Exprs = exprs.release();
875
876 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
877 for (unsigned i = 0; i < NumAssocs; ++i) {
878 if (ParsedTypes[i])
879 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
880 else
881 Types[i] = 0;
882 }
883
884 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
885 ControllingExpr, Types, Exprs,
886 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000887 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000888 return ER;
889}
890
891ExprResult
892Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
893 SourceLocation DefaultLoc,
894 SourceLocation RParenLoc,
895 Expr *ControllingExpr,
896 TypeSourceInfo **Types,
897 Expr **Exprs,
898 unsigned NumAssocs) {
899 bool TypeErrorFound = false,
900 IsResultDependent = ControllingExpr->isTypeDependent(),
901 ContainsUnexpandedParameterPack
902 = ControllingExpr->containsUnexpandedParameterPack();
903
904 for (unsigned i = 0; i < NumAssocs; ++i) {
905 if (Exprs[i]->containsUnexpandedParameterPack())
906 ContainsUnexpandedParameterPack = true;
907
908 if (Types[i]) {
909 if (Types[i]->getType()->containsUnexpandedParameterPack())
910 ContainsUnexpandedParameterPack = true;
911
912 if (Types[i]->getType()->isDependentType()) {
913 IsResultDependent = true;
914 } else {
915 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
916 // complete object type other than a variably modified type."
917 unsigned D = 0;
918 if (Types[i]->getType()->isIncompleteType())
919 D = diag::err_assoc_type_incomplete;
920 else if (!Types[i]->getType()->isObjectType())
921 D = diag::err_assoc_type_nonobject;
922 else if (Types[i]->getType()->isVariablyModifiedType())
923 D = diag::err_assoc_type_variably_modified;
924
925 if (D != 0) {
926 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
927 << Types[i]->getTypeLoc().getSourceRange()
928 << Types[i]->getType();
929 TypeErrorFound = true;
930 }
931
932 // C1X 6.5.1.1p2 "No two generic associations in the same generic
933 // selection shall specify compatible types."
934 for (unsigned j = i+1; j < NumAssocs; ++j)
935 if (Types[j] && !Types[j]->getType()->isDependentType() &&
936 Context.typesAreCompatible(Types[i]->getType(),
937 Types[j]->getType())) {
938 Diag(Types[j]->getTypeLoc().getBeginLoc(),
939 diag::err_assoc_compatible_types)
940 << Types[j]->getTypeLoc().getSourceRange()
941 << Types[j]->getType()
942 << Types[i]->getType();
943 Diag(Types[i]->getTypeLoc().getBeginLoc(),
944 diag::note_compat_assoc)
945 << Types[i]->getTypeLoc().getSourceRange()
946 << Types[i]->getType();
947 TypeErrorFound = true;
948 }
949 }
950 }
951 }
952 if (TypeErrorFound)
953 return ExprError();
954
955 // If we determined that the generic selection is result-dependent, don't
956 // try to compute the result expression.
957 if (IsResultDependent)
958 return Owned(new (Context) GenericSelectionExpr(
959 Context, KeyLoc, ControllingExpr,
960 Types, Exprs, NumAssocs, DefaultLoc,
961 RParenLoc, ContainsUnexpandedParameterPack));
962
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000963 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000964 unsigned DefaultIndex = -1U;
965 for (unsigned i = 0; i < NumAssocs; ++i) {
966 if (!Types[i])
967 DefaultIndex = i;
968 else if (Context.typesAreCompatible(ControllingExpr->getType(),
969 Types[i]->getType()))
970 CompatIndices.push_back(i);
971 }
972
973 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
974 // type compatible with at most one of the types named in its generic
975 // association list."
976 if (CompatIndices.size() > 1) {
977 // We strip parens here because the controlling expression is typically
978 // parenthesized in macro definitions.
979 ControllingExpr = ControllingExpr->IgnoreParens();
980 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
981 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
982 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000983 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000984 E = CompatIndices.end(); I != E; ++I) {
985 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
986 diag::note_compat_assoc)
987 << Types[*I]->getTypeLoc().getSourceRange()
988 << Types[*I]->getType();
989 }
990 return ExprError();
991 }
992
993 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
994 // its controlling expression shall have type compatible with exactly one of
995 // the types named in its generic association list."
996 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
997 // We strip parens here because the controlling expression is typically
998 // parenthesized in macro definitions.
999 ControllingExpr = ControllingExpr->IgnoreParens();
1000 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1001 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1002 return ExprError();
1003 }
1004
1005 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1006 // type name that is compatible with the type of the controlling expression,
1007 // then the result expression of the generic selection is the expression
1008 // in that generic association. Otherwise, the result expression of the
1009 // generic selection is the expression in the default generic association."
1010 unsigned ResultIndex =
1011 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1012
1013 return Owned(new (Context) GenericSelectionExpr(
1014 Context, KeyLoc, ControllingExpr,
1015 Types, Exprs, NumAssocs, DefaultLoc,
1016 RParenLoc, ContainsUnexpandedParameterPack,
1017 ResultIndex));
1018}
1019
Steve Naroff83895f72007-09-16 03:34:24 +00001020/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001021/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1022/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1023/// multiple tokens. However, the common case is that StringToks points to one
1024/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001025///
John McCalldadc5752010-08-24 06:29:42 +00001026ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001027Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001028 assert(NumStringToks && "Must have at least one string!");
1029
Chris Lattner8a24e582009-01-16 18:51:42 +00001030 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001031 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001032 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001033
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001034 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001035 for (unsigned i = 0; i != NumStringToks; ++i)
1036 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001037
Chris Lattner36fc8792008-02-11 00:02:17 +00001038 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001039 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001040 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001041 else if (Literal.isUTF16())
1042 StrTy = Context.Char16Ty;
1043 else if (Literal.isUTF32())
1044 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001045 else if (Literal.Pascal)
1046 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001047
Douglas Gregorfb65e592011-07-27 05:40:30 +00001048 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1049 if (Literal.isWide())
1050 Kind = StringLiteral::Wide;
1051 else if (Literal.isUTF8())
1052 Kind = StringLiteral::UTF8;
1053 else if (Literal.isUTF16())
1054 Kind = StringLiteral::UTF16;
1055 else if (Literal.isUTF32())
1056 Kind = StringLiteral::UTF32;
1057
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001058 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001059 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001060 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001061
Chris Lattner36fc8792008-02-11 00:02:17 +00001062 // Get an array type for the string, according to C99 6.4.5. This includes
1063 // the nul terminator character as well as the string length for pascal
1064 // strings.
1065 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001066 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001067 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattner5b183d82006-11-10 05:03:26 +00001069 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001070 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001071 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001072 &StringTokLocs[0],
1073 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001074}
1075
John McCallc63de662011-02-02 13:00:07 +00001076enum CaptureResult {
1077 /// No capture is required.
1078 CR_NoCapture,
1079
1080 /// A capture is required.
1081 CR_Capture,
1082
John McCall351762c2011-02-07 10:33:21 +00001083 /// A by-ref capture is required.
1084 CR_CaptureByRef,
1085
John McCallc63de662011-02-02 13:00:07 +00001086 /// An error occurred when trying to capture the given variable.
1087 CR_Error
1088};
1089
1090/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001091///
John McCallc63de662011-02-02 13:00:07 +00001092/// \param var - the variable referenced
1093/// \param DC - the context which we couldn't capture through
1094static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001095diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001096 VarDecl *var, DeclContext *DC) {
1097 switch (S.ExprEvalContexts.back().Context) {
1098 case Sema::Unevaluated:
1099 // The argument will never be evaluated, so don't complain.
1100 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001101
John McCallc63de662011-02-02 13:00:07 +00001102 case Sema::PotentiallyEvaluated:
1103 case Sema::PotentiallyEvaluatedIfUsed:
1104 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001105
John McCallc63de662011-02-02 13:00:07 +00001106 case Sema::PotentiallyPotentiallyEvaluated:
1107 // FIXME: delay these!
1108 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001109 }
Mike Stump11289f42009-09-09 15:08:12 +00001110
John McCallc63de662011-02-02 13:00:07 +00001111 // Don't diagnose about capture if we're not actually in code right
1112 // now; in general, there are more appropriate places that will
1113 // diagnose this.
1114 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1115
John McCall92d627e2011-03-22 23:15:50 +00001116 // Certain madnesses can happen with parameter declarations, which
1117 // we want to ignore.
1118 if (isa<ParmVarDecl>(var)) {
1119 // - If the parameter still belongs to the translation unit, then
1120 // we're actually just using one parameter in the declaration of
1121 // the next. This is useful in e.g. VLAs.
1122 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1123 return CR_NoCapture;
1124
1125 // - This particular madness can happen in ill-formed default
1126 // arguments; claim it's okay and let downstream code handle it.
1127 if (S.CurContext == var->getDeclContext()->getParent())
1128 return CR_NoCapture;
1129 }
John McCallc63de662011-02-02 13:00:07 +00001130
1131 DeclarationName functionName;
1132 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1133 functionName = fn->getDeclName();
1134 // FIXME: variable from enclosing block that we couldn't capture from!
1135
1136 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1137 << var->getIdentifier() << functionName;
1138 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1139 << var->getIdentifier();
1140
1141 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001142}
1143
John McCall351762c2011-02-07 10:33:21 +00001144/// There is a well-formed capture at a particular scope level;
1145/// propagate it through all the nested blocks.
1146static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1147 const BlockDecl::Capture &capture) {
1148 VarDecl *var = capture.getVariable();
1149
1150 // Update all the inner blocks with the capture information.
1151 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1152 i != e; ++i) {
1153 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1154 innerBlock->Captures.push_back(
1155 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1156 /*nested*/ true, capture.getCopyExpr()));
1157 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1158 }
1159
1160 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1161}
1162
1163/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001164/// given value in the current context requires a variable capture.
1165///
1166/// This also keeps the captures set in the BlockScopeInfo records
1167/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001168static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001169 ValueDecl *value) {
1170 // Only variables ever require capture.
1171 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001172 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001173
1174 // Fast path: variables from the current context never require capture.
1175 DeclContext *DC = S.CurContext;
1176 if (var->getDeclContext() == DC) return CR_NoCapture;
1177
1178 // Only variables with local storage require capture.
1179 // FIXME: What about 'const' variables in C++?
1180 if (!var->hasLocalStorage()) return CR_NoCapture;
1181
1182 // Otherwise, we need to capture.
1183
1184 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001185 do {
1186 // Only blocks (and eventually C++0x closures) can capture; other
1187 // scopes don't work.
1188 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001189 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001190
1191 BlockScopeInfo *blockScope =
1192 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1193 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1194
John McCall351762c2011-02-07 10:33:21 +00001195 // Check whether we've already captured it in this block. If so,
1196 // we're done.
1197 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1198 return propagateCapture(S, functionScopesIndex,
1199 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001200
1201 functionScopesIndex--;
1202 DC = cast<BlockDecl>(DC)->getDeclContext();
1203 } while (var->getDeclContext() != DC);
1204
John McCall351762c2011-02-07 10:33:21 +00001205 // Okay, we descended all the way to the block that defines the variable.
1206 // Actually try to capture it.
1207 QualType type = var->getType();
1208
1209 // Prohibit variably-modified types.
1210 if (type->isVariablyModifiedType()) {
1211 S.Diag(loc, diag::err_ref_vm_type);
1212 S.Diag(var->getLocation(), diag::note_declared_at);
1213 return CR_Error;
1214 }
1215
1216 // Prohibit arrays, even in __block variables, but not references to
1217 // them.
1218 if (type->isArrayType()) {
1219 S.Diag(loc, diag::err_ref_array_type);
1220 S.Diag(var->getLocation(), diag::note_declared_at);
1221 return CR_Error;
1222 }
1223
1224 S.MarkDeclarationReferenced(loc, var);
1225
1226 // The BlocksAttr indicates the variable is bound by-reference.
1227 bool byRef = var->hasAttr<BlocksAttr>();
1228
1229 // Build a copy expression.
1230 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001231 const RecordType *rtype;
1232 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1233 (rtype = type->getAs<RecordType>())) {
1234
1235 // The capture logic needs the destructor, so make sure we mark it.
1236 // Usually this is unnecessary because most local variables have
1237 // their destructors marked at declaration time, but parameters are
1238 // an exception because it's technically only the call site that
1239 // actually requires the destructor.
1240 if (isa<ParmVarDecl>(var))
1241 S.FinalizeVarWithDestructor(var, rtype);
1242
John McCall351762c2011-02-07 10:33:21 +00001243 // According to the blocks spec, the capture of a variable from
1244 // the stack requires a const copy constructor. This is not true
1245 // of the copy/move done to move a __block variable to the heap.
1246 type.addConst();
1247
1248 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1249 ExprResult result =
1250 S.PerformCopyInitialization(
1251 InitializedEntity::InitializeBlock(var->getLocation(),
1252 type, false),
1253 loc, S.Owned(declRef));
1254
1255 // Build a full-expression copy expression if initialization
1256 // succeeded and used a non-trivial constructor. Recover from
1257 // errors by pretending that the copy isn't necessary.
1258 if (!result.isInvalid() &&
1259 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1260 result = S.MaybeCreateExprWithCleanups(result);
1261 copyExpr = result.take();
1262 }
1263 }
1264
1265 // We're currently at the declarer; go back to the closure.
1266 functionScopesIndex++;
1267 BlockScopeInfo *blockScope =
1268 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1269
1270 // Build a valid capture in this scope.
1271 blockScope->Captures.push_back(
1272 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1273 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1274
1275 // Propagate that to inner captures if necessary.
1276 return propagateCapture(S, functionScopesIndex,
1277 blockScope->Captures.back());
1278}
1279
1280static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1281 const DeclarationNameInfo &NameInfo,
1282 bool byRef) {
1283 assert(isa<VarDecl>(vd) && "capturing non-variable");
1284
1285 VarDecl *var = cast<VarDecl>(vd);
1286 assert(var->hasLocalStorage() && "capturing non-local");
1287 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1288
1289 QualType exprType = var->getType().getNonReferenceType();
1290
1291 BlockDeclRefExpr *BDRE;
1292 if (!byRef) {
1293 // The variable will be bound by copy; make it const within the
1294 // closure, but record that this was done in the expression.
1295 bool constAdded = !exprType.isConstQualified();
1296 exprType.addConst();
1297
1298 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1299 NameInfo.getLoc(), false,
1300 constAdded);
1301 } else {
1302 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1303 NameInfo.getLoc(), true);
1304 }
1305
1306 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001307}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001308
John McCalldadc5752010-08-24 06:29:42 +00001309ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001310Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001311 SourceLocation Loc,
1312 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001313 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001314 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001315}
1316
John McCallf4cd4f92011-02-09 01:13:10 +00001317/// BuildDeclRefExpr - Build an expression that references a
1318/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001319ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001320Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001321 const DeclarationNameInfo &NameInfo,
1322 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001323 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001324
John McCall086a4642010-11-24 05:12:34 +00001325 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001326 SS? SS->getWithLocInContext(Context)
1327 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001328 D, NameInfo, Ty, VK);
1329
1330 // Just in case we're building an illegal pointer-to-member.
1331 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1332 E->setObjectKind(OK_BitField);
1333
1334 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001335}
1336
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001337/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001338/// possibly a list of template arguments.
1339///
1340/// If this produces template arguments, it is permitted to call
1341/// DecomposeTemplateName.
1342///
1343/// This actually loses a lot of source location information for
1344/// non-standard name kinds; we should consider preserving that in
1345/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001346void
1347Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1348 TemplateArgumentListInfo &Buffer,
1349 DeclarationNameInfo &NameInfo,
1350 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001351 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1352 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1353 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1354
Douglas Gregor5476205b2011-06-23 00:49:38 +00001355 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001356 Id.TemplateId->getTemplateArgs(),
1357 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001358 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001359 TemplateArgsPtr.release();
1360
John McCall3e56fd42010-08-23 07:28:44 +00001361 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001362 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001363 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001364 TemplateArgs = &Buffer;
1365 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001366 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001367 TemplateArgs = 0;
1368 }
1369}
1370
John McCalld681c392009-12-16 08:11:27 +00001371/// Diagnose an empty lookup.
1372///
1373/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001374bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001375 CorrectTypoContext CTC,
1376 TemplateArgumentListInfo *ExplicitTemplateArgs,
1377 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001378 DeclarationName Name = R.getLookupName();
1379
John McCalld681c392009-12-16 08:11:27 +00001380 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001381 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001382 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1383 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001384 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001385 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001386 diagnostic_suggest = diag::err_undeclared_use_suggest;
1387 }
John McCalld681c392009-12-16 08:11:27 +00001388
Douglas Gregor598b08f2009-12-31 05:20:13 +00001389 // If the original lookup was an unqualified lookup, fake an
1390 // unqualified lookup. This is useful when (for example) the
1391 // original lookup would not have found something because it was a
1392 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001393 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001394 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001395 if (isa<CXXRecordDecl>(DC)) {
1396 LookupQualifiedName(R, DC);
1397
1398 if (!R.empty()) {
1399 // Don't give errors about ambiguities in this lookup.
1400 R.suppressDiagnostics();
1401
1402 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1403 bool isInstance = CurMethod &&
1404 CurMethod->isInstance() &&
1405 DC == CurMethod->getParent();
1406
1407 // Give a code modification hint to insert 'this->'.
1408 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1409 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001410 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001411 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1412 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001413 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001414 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001415 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001416 Diag(R.getNameLoc(), diagnostic) << Name
1417 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1418 QualType DepThisType = DepMethod->getThisType(Context);
1419 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1420 R.getNameLoc(), DepThisType, false);
1421 TemplateArgumentListInfo TList;
1422 if (ULE->hasExplicitTemplateArgs())
1423 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001424
Douglas Gregore16af532011-02-28 18:50:33 +00001425 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001426 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001427 CXXDependentScopeMemberExpr *DepExpr =
1428 CXXDependentScopeMemberExpr::Create(
1429 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001430 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001431 R.getLookupNameInfo(), &TList);
1432 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001433 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001434 // FIXME: we should be able to handle this case too. It is correct
1435 // to add this-> here. This is a workaround for PR7947.
1436 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001437 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001438 } else {
John McCalld681c392009-12-16 08:11:27 +00001439 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001440 }
John McCalld681c392009-12-16 08:11:27 +00001441
1442 // Do we really want to note all of these?
1443 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1444 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1445
1446 // Tell the callee to try to recover.
1447 return false;
1448 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001449
1450 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001451 }
1452 }
1453
Douglas Gregor598b08f2009-12-31 05:20:13 +00001454 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001455 TypoCorrection Corrected;
1456 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1457 S, &SS, NULL, false, CTC))) {
1458 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1459 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1460 R.setLookupName(Corrected.getCorrection());
1461
Hans Wennborg38198de2011-07-12 08:45:31 +00001462 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001463 if (Corrected.isOverloaded()) {
1464 OverloadCandidateSet OCS(R.getNameLoc());
1465 OverloadCandidateSet::iterator Best;
1466 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1467 CDEnd = Corrected.end();
1468 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001469 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001470 dyn_cast<FunctionTemplateDecl>(*CD))
1471 AddTemplateOverloadCandidate(
1472 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1473 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001474 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1475 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1476 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1477 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001478 }
1479 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1480 case OR_Success:
1481 ND = Best->Function;
1482 break;
1483 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001484 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001485 }
1486 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001487 R.addDecl(ND);
1488 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001489 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001490 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1491 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001492 else
1493 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001494 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001495 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001496 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1497 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001498 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001499 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001500
1501 // Tell the callee to try to recover.
1502 return false;
1503 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001504
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001505 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001506 // FIXME: If we ended up with a typo for a type name or
1507 // Objective-C class name, we're in trouble because the parser
1508 // is in the wrong place to recover. Suggest the typo
1509 // correction, but don't make it a fix-it since we're not going
1510 // to recover well anyway.
1511 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001512 Diag(R.getNameLoc(), diagnostic_suggest)
1513 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001514 else
1515 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001516 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001517 << SS.getRange();
1518
1519 // Don't try to recover; it won't work.
1520 return true;
1521 }
1522 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001523 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001524 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001525 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001526 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001527 else
Douglas Gregor25363982010-01-01 00:15:04 +00001528 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001529 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001530 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001531 return true;
1532 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001533 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001534 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001535
1536 // Emit a special diagnostic for failed member lookups.
1537 // FIXME: computing the declaration context might fail here (?)
1538 if (!SS.isEmpty()) {
1539 Diag(R.getNameLoc(), diag::err_no_member)
1540 << Name << computeDeclContext(SS, false)
1541 << SS.getRange();
1542 return true;
1543 }
1544
John McCalld681c392009-12-16 08:11:27 +00001545 // Give up, we can't recover.
1546 Diag(R.getNameLoc(), diagnostic) << Name;
1547 return true;
1548}
1549
Douglas Gregor05fcf842010-11-02 20:36:02 +00001550ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1551 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001552 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1553 if (!IDecl)
1554 return 0;
1555 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1556 if (!ClassImpDecl)
1557 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001558 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001559 if (!property)
1560 return 0;
1561 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001562 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1563 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001564 return 0;
1565 return property;
1566}
1567
Douglas Gregor05fcf842010-11-02 20:36:02 +00001568bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1569 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1570 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1571 if (!IDecl)
1572 return false;
1573 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1574 if (!ClassImpDecl)
1575 return false;
1576 if (ObjCPropertyImplDecl *PIDecl
1577 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1578 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1579 PIDecl->getPropertyIvarDecl())
1580 return false;
1581
1582 return true;
1583}
1584
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001585ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1586 IdentifierInfo *II,
1587 SourceLocation NameLoc) {
1588 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001589 bool LookForIvars;
1590 if (Lookup.empty())
1591 LookForIvars = true;
1592 else if (CurMeth->isClassMethod())
1593 LookForIvars = false;
1594 else
1595 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001596 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1597 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001598 if (!LookForIvars)
1599 return 0;
1600
Fariborz Jahanian18722982010-07-17 00:59:30 +00001601 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1602 if (!IDecl)
1603 return 0;
1604 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001605 if (!ClassImpDecl)
1606 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001607 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001608 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001609 if (!property)
1610 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001611 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001612 DynamicImplSeen =
1613 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001614 // property implementation has a designated ivar. No need to assume a new
1615 // one.
1616 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1617 return 0;
1618 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001619 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001620 QualType PropType = Context.getCanonicalType(property->getType());
1621 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001622 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001623 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001624 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001625 (Expr *)0, true);
1626 ClassImpDecl->addDecl(Ivar);
1627 IDecl->makeDeclVisibleInContext(Ivar, false);
1628 property->setPropertyIvarDecl(Ivar);
1629 return Ivar;
1630 }
1631 return 0;
1632}
1633
John McCalldadc5752010-08-24 06:29:42 +00001634ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001635 CXXScopeSpec &SS,
1636 UnqualifiedId &Id,
1637 bool HasTrailingLParen,
1638 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001639 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1640 "cannot be direct & operand and have a trailing lparen");
1641
1642 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001643 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001644
John McCall10eae182009-11-30 22:42:35 +00001645 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001646
1647 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001648 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001649 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001650 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001651
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001652 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001653 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001654 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001655
John McCalle66edc12009-11-24 19:00:30 +00001656 // C++ [temp.dep.expr]p3:
1657 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001658 // -- an identifier that was declared with a dependent type,
1659 // (note: handled after lookup)
1660 // -- a template-id that is dependent,
1661 // (note: handled in BuildTemplateIdExpr)
1662 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001663 // -- a nested-name-specifier that contains a class-name that
1664 // names a dependent type.
1665 // Determine whether this is a member of an unknown specialization;
1666 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001667 bool DependentID = false;
1668 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1669 Name.getCXXNameType()->isDependentType()) {
1670 DependentID = true;
1671 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001672 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001673 if (RequireCompleteDeclContext(SS, DC))
1674 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001675 } else {
1676 DependentID = true;
1677 }
1678 }
1679
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001680 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001681 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001682 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001683
Fariborz Jahanian86151342010-07-22 23:33:21 +00001684 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001685 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001686 LookupResult R(*this, NameInfo,
1687 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1688 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001689 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001690 // Lookup the template name again to correctly establish the context in
1691 // which it was found. This is really unfortunate as we already did the
1692 // lookup to determine that it was a template name in the first place. If
1693 // this becomes a performance hit, we can work harder to preserve those
1694 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001695 bool MemberOfUnknownSpecialization;
1696 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1697 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001698
1699 if (MemberOfUnknownSpecialization ||
1700 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1701 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1702 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001703 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001704 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001705 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregora5226932011-02-04 13:35:07 +00001707 // If the result might be in a dependent base class, this is a dependent
1708 // id-expression.
1709 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1710 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1711 TemplateArgs);
1712
John McCalle66edc12009-11-24 19:00:30 +00001713 // If this reference is in an Objective-C method, then we need to do
1714 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001715 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001716 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001717 if (E.isInvalid())
1718 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001719
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001720 if (Expr *Ex = E.takeAs<Expr>())
1721 return Owned(Ex);
1722
1723 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001724 if (getLangOptions().ObjCDefaultSynthProperties &&
1725 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001726 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001727 if (const ObjCPropertyDecl *Property =
1728 canSynthesizeProvisionalIvar(II)) {
1729 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1730 Diag(Property->getLocation(), diag::note_property_declare);
1731 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001732 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1733 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001734 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001735 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001736 // for further use, this must be set to false if in class method.
1737 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001738 }
Chris Lattner59a25942008-03-31 00:36:02 +00001739 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001740
John McCalle66edc12009-11-24 19:00:30 +00001741 if (R.isAmbiguous())
1742 return ExprError();
1743
Douglas Gregor171c45a2009-02-18 21:56:37 +00001744 // Determine whether this name might be a candidate for
1745 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001746 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001747
John McCalle66edc12009-11-24 19:00:30 +00001748 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001749 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001750 // in C90, extension in C99, forbidden in C++).
1751 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1752 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1753 if (D) R.addDecl(D);
1754 }
1755
1756 // If this name wasn't predeclared and if this is not a function
1757 // call, diagnose the problem.
1758 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001759 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001760 return ExprError();
1761
1762 assert(!R.empty() &&
1763 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001764
1765 // If we found an Objective-C instance variable, let
1766 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001767 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001768 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1769 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001770 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001771 assert(E.isInvalid() || E.get());
1772 return move(E);
1773 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001774 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001775 }
Mike Stump11289f42009-09-09 15:08:12 +00001776
John McCalle66edc12009-11-24 19:00:30 +00001777 // This is guaranteed from this point on.
1778 assert(!R.empty() || ADL);
1779
John McCall2d74de92009-12-01 22:10:20 +00001780 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001781 // C++ [class.mfct.non-static]p3:
1782 // When an id-expression that is not part of a class member access
1783 // syntax and not used to form a pointer to member is used in the
1784 // body of a non-static member function of class X, if name lookup
1785 // resolves the name in the id-expression to a non-static non-type
1786 // member of some class C, the id-expression is transformed into a
1787 // class member access expression using (*this) as the
1788 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001789 //
1790 // But we don't actually need to do this for '&' operands if R
1791 // resolved to a function or overloaded function set, because the
1792 // expression is ill-formed if it actually works out to be a
1793 // non-static member function:
1794 //
1795 // C++ [expr.ref]p4:
1796 // Otherwise, if E1.E2 refers to a non-static member function. . .
1797 // [t]he expression can be used only as the left-hand operand of a
1798 // member function call.
1799 //
1800 // There are other safeguards against such uses, but it's important
1801 // to get this right here so that we don't end up making a
1802 // spuriously dependent expression if we're inside a dependent
1803 // instance method.
John McCall57500772009-12-16 12:17:52 +00001804 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001805 bool MightBeImplicitMember;
1806 if (!isAddressOfOperand)
1807 MightBeImplicitMember = true;
1808 else if (!SS.isEmpty())
1809 MightBeImplicitMember = false;
1810 else if (R.isOverloadedResult())
1811 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001812 else if (R.isUnresolvableResult())
1813 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001814 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001815 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1816 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001817
1818 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001819 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001820 }
1821
John McCalle66edc12009-11-24 19:00:30 +00001822 if (TemplateArgs)
1823 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001824
John McCalle66edc12009-11-24 19:00:30 +00001825 return BuildDeclarationNameExpr(SS, R, ADL);
1826}
1827
John McCall10eae182009-11-30 22:42:35 +00001828/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1829/// declaration name, generally during template instantiation.
1830/// There's a large number of things which don't need to be done along
1831/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001832ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001833Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001834 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001835 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001836 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001837 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001838
John McCall0b66eb32010-05-01 00:40:08 +00001839 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001840 return ExprError();
1841
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001842 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001843 LookupQualifiedName(R, DC);
1844
1845 if (R.isAmbiguous())
1846 return ExprError();
1847
1848 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001849 Diag(NameInfo.getLoc(), diag::err_no_member)
1850 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001851 return ExprError();
1852 }
1853
1854 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1855}
1856
1857/// LookupInObjCMethod - The parser has read a name in, and Sema has
1858/// detected that we're currently inside an ObjC method. Perform some
1859/// additional lookup.
1860///
1861/// Ideally, most of this would be done by lookup, but there's
1862/// actually quite a lot of extra work involved.
1863///
1864/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001865ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001866Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001867 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001868 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001869 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001870
John McCalle66edc12009-11-24 19:00:30 +00001871 // There are two cases to handle here. 1) scoped lookup could have failed,
1872 // in which case we should look for an ivar. 2) scoped lookup could have
1873 // found a decl, but that decl is outside the current instance method (i.e.
1874 // a global variable). In these two cases, we do a lookup for an ivar with
1875 // this name, if the lookup sucedes, we replace it our current decl.
1876
1877 // If we're in a class method, we don't normally want to look for
1878 // ivars. But if we don't find anything else, and there's an
1879 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001880 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001881
1882 bool LookForIvars;
1883 if (Lookup.empty())
1884 LookForIvars = true;
1885 else if (IsClassMethod)
1886 LookForIvars = false;
1887 else
1888 LookForIvars = (Lookup.isSingleResult() &&
1889 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001890 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001891 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001892 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001893 ObjCInterfaceDecl *ClassDeclared;
1894 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1895 // Diagnose using an ivar in a class method.
1896 if (IsClassMethod)
1897 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1898 << IV->getDeclName());
1899
1900 // If we're referencing an invalid decl, just return this as a silent
1901 // error node. The error diagnostic was already emitted on the decl.
1902 if (IV->isInvalidDecl())
1903 return ExprError();
1904
1905 // Check if referencing a field with __attribute__((deprecated)).
1906 if (DiagnoseUseOfDecl(IV, Loc))
1907 return ExprError();
1908
1909 // Diagnose the use of an ivar outside of the declaring class.
1910 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1911 ClassDeclared != IFace)
1912 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1913
1914 // FIXME: This should use a new expr for a direct reference, don't
1915 // turn this into Self->ivar, just return a BareIVarExpr or something.
1916 IdentifierInfo &II = Context.Idents.get("self");
1917 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001918 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001919 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001920 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001921 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001922 SelfName, false, false);
1923 if (SelfExpr.isInvalid())
1924 return ExprError();
1925
John Wiegley01296292011-04-08 18:41:53 +00001926 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1927 if (SelfExpr.isInvalid())
1928 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001929
John McCalle66edc12009-11-24 19:00:30 +00001930 MarkDeclarationReferenced(Loc, IV);
1931 return Owned(new (Context)
1932 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001933 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001934 }
Chris Lattner87313662010-04-12 05:10:17 +00001935 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001936 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001937 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001938 ObjCInterfaceDecl *ClassDeclared;
1939 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1940 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1941 IFace == ClassDeclared)
1942 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1943 }
1944 }
1945
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001946 if (Lookup.empty() && II && AllowBuiltinCreation) {
1947 // FIXME. Consolidate this with similar code in LookupName.
1948 if (unsigned BuiltinID = II->getBuiltinID()) {
1949 if (!(getLangOptions().CPlusPlus &&
1950 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1951 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1952 S, Lookup.isForRedeclaration(),
1953 Lookup.getNameLoc());
1954 if (D) Lookup.addDecl(D);
1955 }
1956 }
1957 }
John McCalle66edc12009-11-24 19:00:30 +00001958 // Sentinel value saying that we didn't do anything special.
1959 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001960}
John McCalld14a8642009-11-21 08:51:07 +00001961
John McCall16df1e52010-03-30 21:47:33 +00001962/// \brief Cast a base object to a member's actual type.
1963///
1964/// Logically this happens in three phases:
1965///
1966/// * First we cast from the base type to the naming class.
1967/// The naming class is the class into which we were looking
1968/// when we found the member; it's the qualifier type if a
1969/// qualifier was provided, and otherwise it's the base type.
1970///
1971/// * Next we cast from the naming class to the declaring class.
1972/// If the member we found was brought into a class's scope by
1973/// a using declaration, this is that class; otherwise it's
1974/// the class declaring the member.
1975///
1976/// * Finally we cast from the declaring class to the "true"
1977/// declaring class of the member. This conversion does not
1978/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001979ExprResult
1980Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001981 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001982 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 NamedDecl *Member) {
1984 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1985 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001986 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001987
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001988 QualType DestRecordType;
1989 QualType DestType;
1990 QualType FromRecordType;
1991 QualType FromType = From->getType();
1992 bool PointerConversions = false;
1993 if (isa<FieldDecl>(Member)) {
1994 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001995
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001996 if (FromType->getAs<PointerType>()) {
1997 DestType = Context.getPointerType(DestRecordType);
1998 FromRecordType = FromType->getPointeeType();
1999 PointerConversions = true;
2000 } else {
2001 DestType = DestRecordType;
2002 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002003 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002004 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2005 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002006 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002007
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002008 DestType = Method->getThisType(Context);
2009 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002010
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002011 if (FromType->getAs<PointerType>()) {
2012 FromRecordType = FromType->getPointeeType();
2013 PointerConversions = true;
2014 } else {
2015 FromRecordType = FromType;
2016 DestType = DestRecordType;
2017 }
2018 } else {
2019 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002020 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002021 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002022
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002023 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002024 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002025
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002026 // If the unqualified types are the same, no conversion is necessary.
2027 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002028 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002029
John McCall16df1e52010-03-30 21:47:33 +00002030 SourceRange FromRange = From->getSourceRange();
2031 SourceLocation FromLoc = FromRange.getBegin();
2032
John McCall2536c6d2010-08-25 10:28:54 +00002033 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002034
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002035 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002036 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002037 // class name.
2038 //
2039 // If the member was a qualified name and the qualified referred to a
2040 // specific base subobject type, we'll cast to that intermediate type
2041 // first and then to the object in which the member is declared. That allows
2042 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2043 //
2044 // class Base { public: int x; };
2045 // class Derived1 : public Base { };
2046 // class Derived2 : public Base { };
2047 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2048 //
2049 // void VeryDerived::f() {
2050 // x = 17; // error: ambiguous base subobjects
2051 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2052 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002053 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002054 QualType QType = QualType(Qualifier->getAsType(), 0);
2055 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2056 assert(QType->isRecordType() && "lookup done with non-record type");
2057
2058 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2059
2060 // In C++98, the qualifier type doesn't actually have to be a base
2061 // type of the object type, in which case we just ignore it.
2062 // Otherwise build the appropriate casts.
2063 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002064 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002065 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002066 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002067 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002068
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002069 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002070 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002071 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2072 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002073
2074 FromType = QType;
2075 FromRecordType = QRecordType;
2076
2077 // If the qualifier type was the same as the destination type,
2078 // we're done.
2079 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002080 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002081 }
2082 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002083
John McCall16df1e52010-03-30 21:47:33 +00002084 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002085
John McCall16df1e52010-03-30 21:47:33 +00002086 // If we actually found the member through a using declaration, cast
2087 // down to the using declaration's type.
2088 //
2089 // Pointer equality is fine here because only one declaration of a
2090 // class ever has member declarations.
2091 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2092 assert(isa<UsingShadowDecl>(FoundDecl));
2093 QualType URecordType = Context.getTypeDeclType(
2094 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2095
2096 // We only need to do this if the naming-class to declaring-class
2097 // conversion is non-trivial.
2098 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2099 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002100 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002101 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002102 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002103 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002104
John McCall16df1e52010-03-30 21:47:33 +00002105 QualType UType = URecordType;
2106 if (PointerConversions)
2107 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002108 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2109 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002110 FromType = UType;
2111 FromRecordType = URecordType;
2112 }
2113
2114 // We don't do access control for the conversion from the
2115 // declaring class to the true declaring class.
2116 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002118
John McCallcf142162010-08-07 06:22:56 +00002119 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002120 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2121 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002122 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002123 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002124
John Wiegley01296292011-04-08 18:41:53 +00002125 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2126 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002127}
Douglas Gregor3256d042009-06-30 15:47:41 +00002128
John McCalle66edc12009-11-24 19:00:30 +00002129bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002130 const LookupResult &R,
2131 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002132 // Only when used directly as the postfix-expression of a call.
2133 if (!HasTrailingLParen)
2134 return false;
2135
2136 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002137 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002138 return false;
2139
2140 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002141 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002142 return false;
2143
2144 // Turn off ADL when we find certain kinds of declarations during
2145 // normal lookup:
2146 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2147 NamedDecl *D = *I;
2148
2149 // C++0x [basic.lookup.argdep]p3:
2150 // -- a declaration of a class member
2151 // Since using decls preserve this property, we check this on the
2152 // original decl.
John McCall57500772009-12-16 12:17:52 +00002153 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002154 return false;
2155
2156 // C++0x [basic.lookup.argdep]p3:
2157 // -- a block-scope function declaration that is not a
2158 // using-declaration
2159 // NOTE: we also trigger this for function templates (in fact, we
2160 // don't check the decl type at all, since all other decl types
2161 // turn off ADL anyway).
2162 if (isa<UsingShadowDecl>(D))
2163 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2164 else if (D->getDeclContext()->isFunctionOrMethod())
2165 return false;
2166
2167 // C++0x [basic.lookup.argdep]p3:
2168 // -- a declaration that is neither a function or a function
2169 // template
2170 // And also for builtin functions.
2171 if (isa<FunctionDecl>(D)) {
2172 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2173
2174 // But also builtin functions.
2175 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2176 return false;
2177 } else if (!isa<FunctionTemplateDecl>(D))
2178 return false;
2179 }
2180
2181 return true;
2182}
2183
2184
John McCalld14a8642009-11-21 08:51:07 +00002185/// Diagnoses obvious problems with the use of the given declaration
2186/// as an expression. This is only actually called for lookups that
2187/// were not overloaded, and it doesn't promise that the declaration
2188/// will in fact be used.
2189static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002190 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002191 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2192 return true;
2193 }
2194
2195 if (isa<ObjCInterfaceDecl>(D)) {
2196 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2197 return true;
2198 }
2199
2200 if (isa<NamespaceDecl>(D)) {
2201 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2202 return true;
2203 }
2204
2205 return false;
2206}
2207
John McCalldadc5752010-08-24 06:29:42 +00002208ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002209Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002210 LookupResult &R,
2211 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002212 // If this is a single, fully-resolved result and we don't need ADL,
2213 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002214 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002215 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2216 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002217
2218 // We only need to check the declaration if there's exactly one
2219 // result, because in the overloaded case the results can only be
2220 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002221 if (R.isSingleResult() &&
2222 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002223 return ExprError();
2224
John McCall58cc69d2010-01-27 01:50:18 +00002225 // Otherwise, just build an unresolved lookup expression. Suppress
2226 // any lookup-related diagnostics; we'll hash these out later, when
2227 // we've picked a target.
2228 R.suppressDiagnostics();
2229
John McCalld14a8642009-11-21 08:51:07 +00002230 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002231 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002232 SS.getWithLocInContext(Context),
2233 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002234 NeedsADL, R.isOverloadedResult(),
2235 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002236
2237 return Owned(ULE);
2238}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002239
John McCalld14a8642009-11-21 08:51:07 +00002240/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002241ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002242Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002243 const DeclarationNameInfo &NameInfo,
2244 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002245 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002246 assert(!isa<FunctionTemplateDecl>(D) &&
2247 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002248
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002249 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002250 if (CheckDeclInExpr(*this, Loc, D))
2251 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002252
Douglas Gregore7488b92009-12-01 16:58:18 +00002253 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2254 // Specifically diagnose references to class templates that are missing
2255 // a template argument list.
2256 Diag(Loc, diag::err_template_decl_ref)
2257 << Template << SS.getRange();
2258 Diag(Template->getLocation(), diag::note_template_decl_here);
2259 return ExprError();
2260 }
2261
2262 // Make sure that we're referring to a value.
2263 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2264 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002265 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002266 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002267 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002268 return ExprError();
2269 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002270
Douglas Gregor171c45a2009-02-18 21:56:37 +00002271 // Check whether this declaration can be used. Note that we suppress
2272 // this check when we're going to perform argument-dependent lookup
2273 // on this function name, because this might not be the function
2274 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002275 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002276 return ExprError();
2277
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002278 // Only create DeclRefExpr's for valid Decl's.
2279 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002280 return ExprError();
2281
John McCallf3a88602011-02-03 08:15:49 +00002282 // Handle members of anonymous structs and unions. If we got here,
2283 // and the reference is to a class member indirect field, then this
2284 // must be the subject of a pointer-to-member expression.
2285 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2286 if (!indirectField->isCXXClassMember())
2287 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2288 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002289
Chris Lattner2a9d9892008-10-20 05:16:36 +00002290 // If the identifier reference is inside a block, and it refers to a value
2291 // that is outside the block, create a BlockDeclRefExpr instead of a
2292 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2293 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002294 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002295 // We do not do this for things like enum constants, global variables, etc,
2296 // as they do not get snapshotted.
2297 //
John McCall351762c2011-02-07 10:33:21 +00002298 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002299 case CR_Error:
2300 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002301
John McCallc63de662011-02-02 13:00:07 +00002302 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002303 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2304 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2305
2306 case CR_CaptureByRef:
2307 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2308 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002309
2310 case CR_NoCapture: {
2311 // If this reference is not in a block or if the referenced
2312 // variable is within the block, create a normal DeclRefExpr.
2313
2314 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002315 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002316
2317 switch (D->getKind()) {
2318 // Ignore all the non-ValueDecl kinds.
2319#define ABSTRACT_DECL(kind)
2320#define VALUE(type, base)
2321#define DECL(type, base) \
2322 case Decl::type:
2323#include "clang/AST/DeclNodes.inc"
2324 llvm_unreachable("invalid value decl kind");
2325 return ExprError();
2326
2327 // These shouldn't make it here.
2328 case Decl::ObjCAtDefsField:
2329 case Decl::ObjCIvar:
2330 llvm_unreachable("forming non-member reference to ivar?");
2331 return ExprError();
2332
2333 // Enum constants are always r-values and never references.
2334 // Unresolved using declarations are dependent.
2335 case Decl::EnumConstant:
2336 case Decl::UnresolvedUsingValue:
2337 valueKind = VK_RValue;
2338 break;
2339
2340 // Fields and indirect fields that got here must be for
2341 // pointer-to-member expressions; we just call them l-values for
2342 // internal consistency, because this subexpression doesn't really
2343 // exist in the high-level semantics.
2344 case Decl::Field:
2345 case Decl::IndirectField:
2346 assert(getLangOptions().CPlusPlus &&
2347 "building reference to field in C?");
2348
2349 // These can't have reference type in well-formed programs, but
2350 // for internal consistency we do this anyway.
2351 type = type.getNonReferenceType();
2352 valueKind = VK_LValue;
2353 break;
2354
2355 // Non-type template parameters are either l-values or r-values
2356 // depending on the type.
2357 case Decl::NonTypeTemplateParm: {
2358 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2359 type = reftype->getPointeeType();
2360 valueKind = VK_LValue; // even if the parameter is an r-value reference
2361 break;
2362 }
2363
2364 // For non-references, we need to strip qualifiers just in case
2365 // the template parameter was declared as 'const int' or whatever.
2366 valueKind = VK_RValue;
2367 type = type.getUnqualifiedType();
2368 break;
2369 }
2370
2371 case Decl::Var:
2372 // In C, "extern void blah;" is valid and is an r-value.
2373 if (!getLangOptions().CPlusPlus &&
2374 !type.hasQualifiers() &&
2375 type->isVoidType()) {
2376 valueKind = VK_RValue;
2377 break;
2378 }
2379 // fallthrough
2380
2381 case Decl::ImplicitParam:
2382 case Decl::ParmVar:
2383 // These are always l-values.
2384 valueKind = VK_LValue;
2385 type = type.getNonReferenceType();
2386 break;
2387
2388 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002389 const FunctionType *fty = type->castAs<FunctionType>();
2390
2391 // If we're referring to a function with an __unknown_anytype
2392 // result type, make the entire expression __unknown_anytype.
2393 if (fty->getResultType() == Context.UnknownAnyTy) {
2394 type = Context.UnknownAnyTy;
2395 valueKind = VK_RValue;
2396 break;
2397 }
2398
John McCallf4cd4f92011-02-09 01:13:10 +00002399 // Functions are l-values in C++.
2400 if (getLangOptions().CPlusPlus) {
2401 valueKind = VK_LValue;
2402 break;
2403 }
2404
2405 // C99 DR 316 says that, if a function type comes from a
2406 // function definition (without a prototype), that type is only
2407 // used for checking compatibility. Therefore, when referencing
2408 // the function, we pretend that we don't have the full function
2409 // type.
John McCall2979fe02011-04-12 00:42:48 +00002410 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2411 isa<FunctionProtoType>(fty))
2412 type = Context.getFunctionNoProtoType(fty->getResultType(),
2413 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002414
2415 // Functions are r-values in C.
2416 valueKind = VK_RValue;
2417 break;
2418 }
2419
2420 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002421 // If we're referring to a method with an __unknown_anytype
2422 // result type, make the entire expression __unknown_anytype.
2423 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002424 if (const FunctionProtoType *proto
2425 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002426 if (proto->getResultType() == Context.UnknownAnyTy) {
2427 type = Context.UnknownAnyTy;
2428 valueKind = VK_RValue;
2429 break;
2430 }
2431
John McCallf4cd4f92011-02-09 01:13:10 +00002432 // C++ methods are l-values if static, r-values if non-static.
2433 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2434 valueKind = VK_LValue;
2435 break;
2436 }
2437 // fallthrough
2438
2439 case Decl::CXXConversion:
2440 case Decl::CXXDestructor:
2441 case Decl::CXXConstructor:
2442 valueKind = VK_RValue;
2443 break;
2444 }
2445
2446 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2447 }
2448
John McCallc63de662011-02-02 13:00:07 +00002449 }
John McCall7decc9e2010-11-18 06:31:45 +00002450
John McCall351762c2011-02-07 10:33:21 +00002451 llvm_unreachable("unknown capture result");
2452 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002453}
Chris Lattnere168f762006-11-10 05:29:30 +00002454
John McCall2979fe02011-04-12 00:42:48 +00002455ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002456 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002457
Chris Lattnere168f762006-11-10 05:29:30 +00002458 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002459 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002460 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2461 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2462 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002463 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002464
Chris Lattnera81a0272008-01-12 08:14:25 +00002465 // Pre-defined identifiers are of type char[x], where x is the length of the
2466 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002467
Anders Carlsson2fb08242009-09-08 18:24:21 +00002468 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002469 if (!currentDecl && getCurBlock())
2470 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002471 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002472 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002473 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002474 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002475
Anders Carlsson0b209a82009-09-11 01:22:35 +00002476 QualType ResTy;
2477 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2478 ResTy = Context.DependentTy;
2479 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002480 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002481
Anders Carlsson0b209a82009-09-11 01:22:35 +00002482 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002483 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002484 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2485 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002486 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002487}
2488
John McCalldadc5752010-08-24 06:29:42 +00002489ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002490 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002491 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002492 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002493 if (Invalid)
2494 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002495
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002496 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002497 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002498 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002499 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002500
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002501 QualType Ty;
2502 if (!getLangOptions().CPlusPlus)
2503 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2504 else if (Literal.isWide())
2505 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002506 else if (Literal.isUTF16())
2507 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2508 else if (Literal.isUTF32())
2509 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002510 else if (Literal.isMultiChar())
2511 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002512 else
2513 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002514
Douglas Gregorfb65e592011-07-27 05:40:30 +00002515 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2516 if (Literal.isWide())
2517 Kind = CharacterLiteral::Wide;
2518 else if (Literal.isUTF16())
2519 Kind = CharacterLiteral::UTF16;
2520 else if (Literal.isUTF32())
2521 Kind = CharacterLiteral::UTF32;
2522
2523 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2524 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002525}
2526
John McCalldadc5752010-08-24 06:29:42 +00002527ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002528 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002529 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2530 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002531 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002532 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002533 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002534 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002535 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002536
Chris Lattner23b7eb62007-06-15 23:05:46 +00002537 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002538 // Add padding so that NumericLiteralParser can overread by one character.
2539 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002540 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002541
Chris Lattner67ca9252007-05-21 01:08:44 +00002542 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002543 bool Invalid = false;
2544 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2545 if (Invalid)
2546 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002547
Mike Stump11289f42009-09-09 15:08:12 +00002548 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002549 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002550 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002551 return ExprError();
2552
Chris Lattner1c20a172007-08-26 03:42:43 +00002553 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002554
Chris Lattner1c20a172007-08-26 03:42:43 +00002555 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002556 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002557 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002558 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002559 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002560 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002561 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002562 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002563
2564 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2565
John McCall53b93a02009-12-24 09:08:04 +00002566 using llvm::APFloat;
2567 APFloat Val(Format);
2568
2569 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002570
2571 // Overflow is always an error, but underflow is only an error if
2572 // we underflowed to zero (APFloat reports denormals as underflow).
2573 if ((result & APFloat::opOverflow) ||
2574 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002575 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002576 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002577 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002578 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002579 APFloat::getLargest(Format).toString(buffer);
2580 } else {
John McCall62abc942010-02-26 23:35:57 +00002581 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002582 APFloat::getSmallest(Format).toString(buffer);
2583 }
2584
2585 Diag(Tok.getLocation(), diagnostic)
2586 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002587 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002588 }
2589
2590 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002591 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002592
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002593 if (Ty == Context.DoubleTy) {
2594 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002595 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002596 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2597 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002598 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002599 }
2600 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002601 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002602 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002603 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002604 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002605
Neil Boothac582c52007-08-29 22:00:19 +00002606 // long long is a C99 feature.
2607 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002608 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002609 Diag(Tok.getLocation(), diag::ext_longlong);
2610
Chris Lattner67ca9252007-05-21 01:08:44 +00002611 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002612 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002613
Chris Lattner67ca9252007-05-21 01:08:44 +00002614 if (Literal.GetIntegerValue(ResultVal)) {
2615 // If this value didn't fit into uintmax_t, warn and force to ull.
2616 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002617 Ty = Context.UnsignedLongLongTy;
2618 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002619 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002620 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 // If this value fits into a ULL, try to figure out what else it fits into
2622 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002623
Chris Lattner67ca9252007-05-21 01:08:44 +00002624 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2625 // be an unsigned int.
2626 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2627
2628 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002629 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002630 if (!Literal.isLong && !Literal.isLongLong) {
2631 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002632 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002633
Chris Lattner67ca9252007-05-21 01:08:44 +00002634 // Does it fit in a unsigned int?
2635 if (ResultVal.isIntN(IntSize)) {
2636 // Does it fit in a signed int?
2637 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002638 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002640 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002641 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002643 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002644
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002646 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002647 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002648
Chris Lattner67ca9252007-05-21 01:08:44 +00002649 // Does it fit in a unsigned long?
2650 if (ResultVal.isIntN(LongSize)) {
2651 // Does it fit in a signed long?
2652 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002653 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002654 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002655 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002656 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002657 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002658 }
2659
Chris Lattner67ca9252007-05-21 01:08:44 +00002660 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002661 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002662 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002663
Chris Lattner67ca9252007-05-21 01:08:44 +00002664 // Does it fit in a unsigned long long?
2665 if (ResultVal.isIntN(LongLongSize)) {
2666 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002667 // To be compatible with MSVC, hex integer literals ending with the
2668 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002669 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2670 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002671 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002672 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002673 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002674 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002675 }
2676 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // If we still couldn't decide a type, we probably have something that
2679 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002680 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002681 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002683 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002684 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002685
Chris Lattner55258cf2008-05-09 05:59:00 +00002686 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002687 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002688 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002689 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002690 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002691
Chris Lattner1c20a172007-08-26 03:42:43 +00002692 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2693 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002694 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002695 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002696
2697 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002698}
2699
John McCalldadc5752010-08-24 06:29:42 +00002700ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002701 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002702 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002703 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002704}
2705
Chandler Carruth62da79c2011-05-26 08:53:12 +00002706static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2707 SourceLocation Loc,
2708 SourceRange ArgRange) {
2709 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2710 // scalar or vector data type argument..."
2711 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2712 // type (C99 6.2.5p18) or void.
2713 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2714 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2715 << T << ArgRange;
2716 return true;
2717 }
2718
2719 assert((T->isVoidType() || !T->isIncompleteType()) &&
2720 "Scalar types should always be complete");
2721 return false;
2722}
2723
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002724static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2725 SourceLocation Loc,
2726 SourceRange ArgRange,
2727 UnaryExprOrTypeTrait TraitKind) {
2728 // C99 6.5.3.4p1:
2729 if (T->isFunctionType()) {
2730 // alignof(function) is allowed as an extension.
2731 if (TraitKind == UETT_SizeOf)
2732 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2733 return false;
2734 }
2735
2736 // Allow sizeof(void)/alignof(void) as an extension.
2737 if (T->isVoidType()) {
2738 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2739 return false;
2740 }
2741
2742 return true;
2743}
2744
2745static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2746 SourceLocation Loc,
2747 SourceRange ArgRange,
2748 UnaryExprOrTypeTrait TraitKind) {
2749 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2750 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2751 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2752 << T << (TraitKind == UETT_SizeOf)
2753 << ArgRange;
2754 return true;
2755 }
2756
2757 return false;
2758}
2759
Chandler Carruth14502c22011-05-26 08:53:10 +00002760/// \brief Check the constrains on expression operands to unary type expression
2761/// and type traits.
2762///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002763/// Completes any types necessary and validates the constraints on the operand
2764/// expression. The logic mostly mirrors the type-based overload, but may modify
2765/// the expression as it completes the type for that expression through template
2766/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002767bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2768 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002769 QualType ExprTy = Op->getType();
2770
2771 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2772 // the result is the size of the referenced type."
2773 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2774 // result shall be the alignment of the referenced type."
2775 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2776 ExprTy = Ref->getPointeeType();
2777
2778 if (ExprKind == UETT_VecStep)
2779 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2780 Op->getSourceRange());
2781
2782 // Whitelist some types as extensions
2783 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2784 Op->getSourceRange(), ExprKind))
2785 return false;
2786
2787 if (RequireCompleteExprType(Op,
2788 PDiag(diag::err_sizeof_alignof_incomplete_type)
2789 << ExprKind << Op->getSourceRange(),
2790 std::make_pair(SourceLocation(), PDiag(0))))
2791 return true;
2792
2793 // Completeing the expression's type may have changed it.
2794 ExprTy = Op->getType();
2795 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2796 ExprTy = Ref->getPointeeType();
2797
2798 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2799 Op->getSourceRange(), ExprKind))
2800 return true;
2801
Nico Weber0870deb2011-06-15 02:47:03 +00002802 if (ExprKind == UETT_SizeOf) {
2803 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2804 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2805 QualType OType = PVD->getOriginalType();
2806 QualType Type = PVD->getType();
2807 if (Type->isPointerType() && OType->isArrayType()) {
2808 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2809 << Type << OType;
2810 Diag(PVD->getLocation(), diag::note_declared_at);
2811 }
2812 }
2813 }
2814 }
2815
Chandler Carruth7c430c02011-05-27 01:33:31 +00002816 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002817}
2818
2819/// \brief Check the constraints on operands to unary expression and type
2820/// traits.
2821///
2822/// This will complete any types necessary, and validate the various constraints
2823/// on those operands.
2824///
Steve Naroff71b59a92007-06-04 22:22:31 +00002825/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002826/// C99 6.3.2.1p[2-4] all state:
2827/// Except when it is the operand of the sizeof operator ...
2828///
2829/// C++ [expr.sizeof]p4
2830/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2831/// standard conversions are not applied to the operand of sizeof.
2832///
2833/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002834bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2835 SourceLocation OpLoc,
2836 SourceRange ExprRange,
2837 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002838 if (exprType->isDependentType())
2839 return false;
2840
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002841 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2842 // the result is the size of the referenced type."
2843 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2844 // result shall be the alignment of the referenced type."
2845 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2846 exprType = Ref->getPointeeType();
2847
Chandler Carruth62da79c2011-05-26 08:53:12 +00002848 if (ExprKind == UETT_VecStep)
2849 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002850
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002851 // Whitelist some types as extensions
2852 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2853 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002854 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002855
Chris Lattner62975a72009-04-24 00:30:45 +00002856 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002857 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002858 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002859 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002860
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002861 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2862 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002863 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002864
Chris Lattner62975a72009-04-24 00:30:45 +00002865 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002866}
2867
Chandler Carruth14502c22011-05-26 08:53:10 +00002868static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002869 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002870
Mike Stump11289f42009-09-09 15:08:12 +00002871 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002872 if (isa<DeclRefExpr>(E))
2873 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002874
2875 // Cannot know anything else if the expression is dependent.
2876 if (E->isTypeDependent())
2877 return false;
2878
Douglas Gregor71235ec2009-05-02 02:18:30 +00002879 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002880 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2881 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002882 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002883 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002884
2885 // Alignment of a field access is always okay, so long as it isn't a
2886 // bit-field.
2887 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002888 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002889 return false;
2890
Chandler Carruth14502c22011-05-26 08:53:10 +00002891 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002892}
2893
Chandler Carruth14502c22011-05-26 08:53:10 +00002894bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002895 E = E->IgnoreParens();
2896
2897 // Cannot know anything else if the expression is dependent.
2898 if (E->isTypeDependent())
2899 return false;
2900
Chandler Carruth14502c22011-05-26 08:53:10 +00002901 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002902}
2903
Douglas Gregor0950e412009-03-13 21:01:28 +00002904/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002905ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002906Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2907 SourceLocation OpLoc,
2908 UnaryExprOrTypeTrait ExprKind,
2909 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002910 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002911 return ExprError();
2912
John McCallbcd03502009-12-07 02:54:59 +00002913 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002914
Douglas Gregor0950e412009-03-13 21:01:28 +00002915 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002916 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002917 return ExprError();
2918
2919 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002920 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2921 Context.getSizeType(),
2922 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002923}
2924
2925/// \brief Build a sizeof or alignof expression given an expression
2926/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002927ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002928Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2929 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002930 ExprResult PE = CheckPlaceholderExpr(E);
2931 if (PE.isInvalid())
2932 return ExprError();
2933
2934 E = PE.get();
2935
Douglas Gregor0950e412009-03-13 21:01:28 +00002936 // Verify that the operand is valid.
2937 bool isInvalid = false;
2938 if (E->isTypeDependent()) {
2939 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002940 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002941 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002942 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002943 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002944 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002945 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002946 isInvalid = true;
2947 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002948 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002949 }
2950
2951 if (isInvalid)
2952 return ExprError();
2953
2954 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002955 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002956 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002957 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002958}
2959
Peter Collingbournee190dee2011-03-11 19:24:49 +00002960/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2961/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002962/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002963ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002964Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2965 UnaryExprOrTypeTrait ExprKind, bool isType,
2966 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002967 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002969
Sebastian Redl6f282892008-11-11 17:56:53 +00002970 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002971 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002972 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002973 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002974 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002975
Douglas Gregor0950e412009-03-13 21:01:28 +00002976 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002977 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002978 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002979}
2980
John Wiegley01296292011-04-08 18:41:53 +00002981static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002982 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002983 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002984 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002985
John McCall34376a62010-12-04 03:47:34 +00002986 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002987 if (V.get()->getObjectKind() != OK_Ordinary) {
2988 V = S.DefaultLvalueConversion(V.take());
2989 if (V.isInvalid())
2990 return QualType();
2991 }
John McCall34376a62010-12-04 03:47:34 +00002992
Chris Lattnere267f5d2007-08-26 05:39:26 +00002993 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002994 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002995 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002996
Chris Lattnere267f5d2007-08-26 05:39:26 +00002997 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002998 if (V.get()->getType()->isArithmeticType())
2999 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003000
John McCall36226622010-10-12 02:09:17 +00003001 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003002 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003003 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003004 if (PR.get() != V.get()) {
3005 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003006 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003007 }
3008
Chris Lattnere267f5d2007-08-26 05:39:26 +00003009 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003010 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003011 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003012 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003013}
3014
3015
Chris Lattnere168f762006-11-10 05:29:30 +00003016
John McCalldadc5752010-08-24 06:29:42 +00003017ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003018Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003019 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003020 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003021 switch (Kind) {
3022 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003023 case tok::plusplus: Opc = UO_PostInc; break;
3024 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003025 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026
John McCallb268a282010-08-23 23:25:46 +00003027 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003028}
3029
John McCalldadc5752010-08-24 06:29:42 +00003030ExprResult
John McCallb268a282010-08-23 23:25:46 +00003031Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3032 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003033 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003034 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003035 if (Result.isInvalid()) return ExprError();
3036 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003037
John McCallb268a282010-08-23 23:25:46 +00003038 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003039
Douglas Gregor40412ac2008-11-19 17:17:41 +00003040 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003041 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003042 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003043 Context.DependentTy,
3044 VK_LValue, OK_Ordinary,
3045 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003046 }
3047
Mike Stump11289f42009-09-09 15:08:12 +00003048 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003049 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003050 LHSExp->getType()->isEnumeralType() ||
3051 RHSExp->getType()->isRecordType() ||
3052 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003053 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003054 }
3055
John McCallb268a282010-08-23 23:25:46 +00003056 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003057}
3058
3059
John McCalldadc5752010-08-24 06:29:42 +00003060ExprResult
John McCallb268a282010-08-23 23:25:46 +00003061Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3062 Expr *Idx, SourceLocation RLoc) {
3063 Expr *LHSExp = Base;
3064 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003065
Chris Lattner36d572b2007-07-16 00:14:47 +00003066 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003067 if (!LHSExp->getType()->getAs<VectorType>()) {
3068 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3069 if (Result.isInvalid())
3070 return ExprError();
3071 LHSExp = Result.take();
3072 }
3073 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3074 if (Result.isInvalid())
3075 return ExprError();
3076 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003077
Chris Lattner36d572b2007-07-16 00:14:47 +00003078 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003079 ExprValueKind VK = VK_LValue;
3080 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003081
Steve Naroffc1aadb12007-03-28 21:49:40 +00003082 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003083 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003084 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003085 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003086 Expr *BaseExpr, *IndexExpr;
3087 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003088 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3089 BaseExpr = LHSExp;
3090 IndexExpr = RHSExp;
3091 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003092 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003093 BaseExpr = LHSExp;
3094 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003095 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003096 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003097 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003098 BaseExpr = RHSExp;
3099 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003100 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003101 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003102 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003103 BaseExpr = LHSExp;
3104 IndexExpr = RHSExp;
3105 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003106 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003107 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003108 // Handle the uncommon case of "123[Ptr]".
3109 BaseExpr = RHSExp;
3110 IndexExpr = LHSExp;
3111 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003112 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003113 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003114 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003115 VK = LHSExp->getValueKind();
3116 if (VK != VK_RValue)
3117 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003118
Chris Lattner36d572b2007-07-16 00:14:47 +00003119 // FIXME: need to deal with const...
3120 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003121 } else if (LHSTy->isArrayType()) {
3122 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003123 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003124 // wasn't promoted because of the C90 rule that doesn't
3125 // allow promoting non-lvalue arrays. Warn, then
3126 // force the promotion here.
3127 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3128 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003129 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3130 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003131 LHSTy = LHSExp->getType();
3132
3133 BaseExpr = LHSExp;
3134 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003135 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003136 } else if (RHSTy->isArrayType()) {
3137 // Same as previous, except for 123[f().a] case
3138 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3139 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003140 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3141 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003142 RHSTy = RHSExp->getType();
3143
3144 BaseExpr = RHSExp;
3145 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003146 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003147 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003148 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3149 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003150 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003151 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003152 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003153 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3154 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003155
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003156 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003157 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3158 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003159 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3160
Douglas Gregorac1fb652009-03-24 19:52:54 +00003161 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003162 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3163 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003164 // incomplete types are not object types.
3165 if (ResultType->isFunctionType()) {
3166 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3167 << ResultType << BaseExpr->getSourceRange();
3168 return ExprError();
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003171 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3172 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003173 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3174 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003175
3176 // C forbids expressions of unqualified void type from being l-values.
3177 // See IsCForbiddenLValueType.
3178 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003179 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003180 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003181 PDiag(diag::err_subscript_incomplete_type)
3182 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003183 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattner62975a72009-04-24 00:30:45 +00003185 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003186 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003187 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3188 << ResultType << BaseExpr->getSourceRange();
3189 return ExprError();
3190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
John McCall4bc41ae2010-11-18 19:01:18 +00003192 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003193 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003194
Mike Stump4e1f26a2009-02-19 03:04:26 +00003195 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003196 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003197}
3198
John McCalldadc5752010-08-24 06:29:42 +00003199ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003200 FunctionDecl *FD,
3201 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003202 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003203 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003204 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003205 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003206 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003207 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003208 return ExprError();
3209 }
3210
3211 if (Param->hasUninstantiatedDefaultArg()) {
3212 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003213
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003214 // Instantiate the expression.
3215 MultiLevelTemplateArgumentList ArgList
3216 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003217
Nico Weber44887f62010-11-29 18:19:25 +00003218 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003219 = ArgList.getInnermost();
3220 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3221 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003222
Nico Weber44887f62010-11-29 18:19:25 +00003223 ExprResult Result;
3224 {
3225 // C++ [dcl.fct.default]p5:
3226 // The names in the [default argument] expression are bound, and
3227 // the semantic constraints are checked, at the point where the
3228 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003229 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003230 Result = SubstExpr(UninstExpr, ArgList);
3231 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003232 if (Result.isInvalid())
3233 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003234
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003235 // Check the expression as an initializer for the parameter.
3236 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003237 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003238 InitializationKind Kind
3239 = InitializationKind::CreateCopy(Param->getLocation(),
3240 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3241 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003242
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003243 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3244 Result = InitSeq.Perform(*this, Entity, Kind,
3245 MultiExprArg(*this, &ResultE, 1));
3246 if (Result.isInvalid())
3247 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003248
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003249 // Build the default argument expression.
3250 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3251 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003252 }
3253
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003254 // If the default expression creates temporaries, we need to
3255 // push them to the current stack of expression temporaries so they'll
3256 // be properly destroyed.
3257 // FIXME: We should really be rebuilding the default argument with new
3258 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003259 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3260 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3261 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3262 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3263 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003264 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003265 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003266
3267 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003268 // Just mark all of the declarations in this potentially-evaluated expression
3269 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003270 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003271 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003272}
3273
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003274/// ConvertArgumentsForCall - Converts the arguments specified in
3275/// Args/NumArgs to the parameter types of the function FDecl with
3276/// function prototype Proto. Call is the call expression itself, and
3277/// Fn is the function expression. For a C++ member function, this
3278/// routine does not attempt to convert the object argument. Returns
3279/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003280bool
3281Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003282 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003283 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003284 Expr **Args, unsigned NumArgs,
3285 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003286 // Bail out early if calling a builtin with custom typechecking.
3287 // We don't need to do this in the
3288 if (FDecl)
3289 if (unsigned ID = FDecl->getBuiltinID())
3290 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3291 return false;
3292
Mike Stump4e1f26a2009-02-19 03:04:26 +00003293 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003294 // assignment, to the types of the corresponding parameter, ...
3295 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003296 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003297
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003298 // If too few arguments are available (and we don't have default
3299 // arguments for the remaining parameters), don't make the call.
3300 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003301 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3302 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003303 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003304 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003305
3306 // Emit the location of the prototype.
3307 if (FDecl && !FDecl->getBuiltinID())
3308 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3309 << FDecl;
3310
3311 return true;
3312 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003313 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003314 }
3315
3316 // If too many are passed and not variadic, error on the extras and drop
3317 // them.
3318 if (NumArgs > NumArgsInProto) {
3319 if (!Proto->isVariadic()) {
3320 Diag(Args[NumArgsInProto]->getLocStart(),
3321 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003322 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003323 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003324 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3325 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003326
3327 // Emit the location of the prototype.
3328 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003329 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3330 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003331
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003332 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003333 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003334 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003335 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003336 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003337 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003338 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003339 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3340 if (Fn->getType()->isBlockPointerType())
3341 CallType = VariadicBlock; // Block
3342 else if (isa<MemberExpr>(Fn))
3343 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003344 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003345 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003346 if (Invalid)
3347 return true;
3348 unsigned TotalNumArgs = AllArgs.size();
3349 for (unsigned i = 0; i < TotalNumArgs; ++i)
3350 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003351
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003352 return false;
3353}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003354
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003355bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3356 FunctionDecl *FDecl,
3357 const FunctionProtoType *Proto,
3358 unsigned FirstProtoArg,
3359 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003360 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003361 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003362 unsigned NumArgsInProto = Proto->getNumArgs();
3363 unsigned NumArgsToCheck = NumArgs;
3364 bool Invalid = false;
3365 if (NumArgs != NumArgsInProto)
3366 // Use default arguments for missing arguments
3367 NumArgsToCheck = NumArgsInProto;
3368 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003369 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003370 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003371 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003372
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003373 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003374 if (ArgIx < NumArgs) {
3375 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003376
Eli Friedman3164fb12009-03-22 22:00:50 +00003377 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3378 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003379 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003380 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003381 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003382
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003383 // Pass the argument
3384 ParmVarDecl *Param = 0;
3385 if (FDecl && i < FDecl->getNumParams())
3386 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003387
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003388 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003389 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003390 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3391 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003392 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003393 SourceLocation(),
3394 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003395 if (ArgE.isInvalid())
3396 return true;
3397
3398 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003399 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003400 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003401
John McCalldadc5752010-08-24 06:29:42 +00003402 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003403 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003404 if (ArgExpr.isInvalid())
3405 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003406
Anders Carlsson355933d2009-08-25 03:49:14 +00003407 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003408 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003409
3410 // Check for array bounds violations for each argument to the call. This
3411 // check only triggers warnings when the argument isn't a more complex Expr
3412 // with its own checking, such as a BinaryOperator.
3413 CheckArrayAccess(Arg);
3414
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003415 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003416 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003417
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003418 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003419 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003420
3421 // Assume that extern "C" functions with variadic arguments that
3422 // return __unknown_anytype aren't *really* variadic.
3423 if (Proto->getResultType() == Context.UnknownAnyTy &&
3424 FDecl && FDecl->isExternC()) {
3425 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3426 ExprResult arg;
3427 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3428 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3429 else
3430 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3431 Invalid |= arg.isInvalid();
3432 AllArgs.push_back(arg.take());
3433 }
3434
3435 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3436 } else {
3437 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003438 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3439 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003440 Invalid |= Arg.isInvalid();
3441 AllArgs.push_back(Arg.take());
3442 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003443 }
3444 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003445 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003446}
3447
John McCall2979fe02011-04-12 00:42:48 +00003448/// Given a function expression of unknown-any type, try to rebuild it
3449/// to have a function type.
3450static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3451
Steve Naroff83895f72007-09-16 03:34:24 +00003452/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003453/// This provides the location of the left/right parens and a list of comma
3454/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003455ExprResult
John McCallb268a282010-08-23 23:25:46 +00003456Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003457 MultiExprArg args, SourceLocation RParenLoc,
3458 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003459 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003460
3461 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003462 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003463 if (Result.isInvalid()) return ExprError();
3464 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003465
John McCallb268a282010-08-23 23:25:46 +00003466 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003467
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003468 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003469 // If this is a pseudo-destructor expression, build the call immediately.
3470 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3471 if (NumArgs > 0) {
3472 // Pseudo-destructor calls should not have any arguments.
3473 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003474 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003475 SourceRange(Args[0]->getLocStart(),
3476 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregorad8a3362009-09-04 17:36:40 +00003478 NumArgs = 0;
3479 }
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregorad8a3362009-09-04 17:36:40 +00003481 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003482 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003483 }
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003485 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003486 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003487 // FIXME: Will need to cache the results of name lookup (including ADL) in
3488 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003489 bool Dependent = false;
3490 if (Fn->isTypeDependent())
3491 Dependent = true;
3492 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3493 Dependent = true;
3494
Peter Collingbourne41f85462011-02-09 21:07:24 +00003495 if (Dependent) {
3496 if (ExecConfig) {
3497 return Owned(new (Context) CUDAKernelCallExpr(
3498 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3499 Context.DependentTy, VK_RValue, RParenLoc));
3500 } else {
3501 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3502 Context.DependentTy, VK_RValue,
3503 RParenLoc));
3504 }
3505 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003506
3507 // Determine whether this is a call to an object (C++ [over.call.object]).
3508 if (Fn->getType()->isRecordType())
3509 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003510 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003511
John McCall2979fe02011-04-12 00:42:48 +00003512 if (Fn->getType() == Context.UnknownAnyTy) {
3513 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3514 if (result.isInvalid()) return ExprError();
3515 Fn = result.take();
3516 }
3517
John McCall0009fcc2011-04-26 20:42:42 +00003518 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003519 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003520 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003521 }
John McCall0009fcc2011-04-26 20:42:42 +00003522 }
John McCall10eae182009-11-30 22:42:35 +00003523
John McCall0009fcc2011-04-26 20:42:42 +00003524 // Check for overloaded calls. This can happen even in C due to extensions.
3525 if (Fn->getType() == Context.OverloadTy) {
3526 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3527
3528 // We aren't supposed to apply this logic if there's an '&' involved.
3529 if (!find.IsAddressOfOperand) {
3530 OverloadExpr *ovl = find.Expression;
3531 if (isa<UnresolvedLookupExpr>(ovl)) {
3532 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3533 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3534 RParenLoc, ExecConfig);
3535 } else {
John McCall2d74de92009-12-01 22:10:20 +00003536 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003537 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003538 }
3539 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003540 }
3541
Douglas Gregore254f902009-02-04 00:32:51 +00003542 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003543
Eli Friedmane14b1992009-12-26 03:35:45 +00003544 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003545
John McCall57500772009-12-16 12:17:52 +00003546 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003547 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3548 if (UnOp->getOpcode() == UO_AddrOf)
3549 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3550
John McCall57500772009-12-16 12:17:52 +00003551 if (isa<DeclRefExpr>(NakedFn))
3552 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003553 else if (isa<MemberExpr>(NakedFn))
3554 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003555
Peter Collingbourne41f85462011-02-09 21:07:24 +00003556 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3557 ExecConfig);
3558}
3559
3560ExprResult
3561Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3562 MultiExprArg execConfig, SourceLocation GGGLoc) {
3563 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3564 if (!ConfigDecl)
3565 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3566 << "cudaConfigureCall");
3567 QualType ConfigQTy = ConfigDecl->getType();
3568
3569 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3570 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3571
3572 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003573}
3574
Tanya Lattner55808c12011-06-04 00:47:47 +00003575/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3576///
3577/// __builtin_astype( value, dst type )
3578///
3579ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3580 SourceLocation BuiltinLoc,
3581 SourceLocation RParenLoc) {
3582 ExprValueKind VK = VK_RValue;
3583 ExprObjectKind OK = OK_Ordinary;
3584 QualType DstTy = GetTypeFromParser(destty);
3585 QualType SrcTy = expr->getType();
3586 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3587 return ExprError(Diag(BuiltinLoc,
3588 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003589 << DstTy
3590 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003591 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003592 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3593 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003594}
3595
John McCall57500772009-12-16 12:17:52 +00003596/// BuildResolvedCallExpr - Build a call to a resolved expression,
3597/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003598/// unary-convert to an expression of function-pointer or
3599/// block-pointer type.
3600///
3601/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003602ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003603Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3604 SourceLocation LParenLoc,
3605 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003606 SourceLocation RParenLoc,
3607 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003608 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3609
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003610 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003611 ExprResult Result = UsualUnaryConversions(Fn);
3612 if (Result.isInvalid())
3613 return ExprError();
3614 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003615
Chris Lattner08464942007-12-28 05:29:59 +00003616 // Make the call expr early, before semantic checks. This guarantees cleanup
3617 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003618 CallExpr *TheCall;
3619 if (Config) {
3620 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3621 cast<CallExpr>(Config),
3622 Args, NumArgs,
3623 Context.BoolTy,
3624 VK_RValue,
3625 RParenLoc);
3626 } else {
3627 TheCall = new (Context) CallExpr(Context, Fn,
3628 Args, NumArgs,
3629 Context.BoolTy,
3630 VK_RValue,
3631 RParenLoc);
3632 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003633
John McCallbebede42011-02-26 05:39:39 +00003634 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3635
3636 // Bail out early if calling a builtin with custom typechecking.
3637 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3638 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3639
John McCall31996342011-04-07 08:22:57 +00003640 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003641 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003642 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003643 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3644 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003645 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003646 if (FuncT == 0)
3647 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3648 << Fn->getType() << Fn->getSourceRange());
3649 } else if (const BlockPointerType *BPT =
3650 Fn->getType()->getAs<BlockPointerType>()) {
3651 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3652 } else {
John McCall31996342011-04-07 08:22:57 +00003653 // Handle calls to expressions of unknown-any type.
3654 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003655 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003656 if (rewrite.isInvalid()) return ExprError();
3657 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003658 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003659 goto retry;
3660 }
3661
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003662 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3663 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003664 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003665
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003666 if (getLangOptions().CUDA) {
3667 if (Config) {
3668 // CUDA: Kernel calls must be to global functions
3669 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3670 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3671 << FDecl->getName() << Fn->getSourceRange());
3672
3673 // CUDA: Kernel function must have 'void' return type
3674 if (!FuncT->getResultType()->isVoidType())
3675 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3676 << Fn->getType() << Fn->getSourceRange());
3677 }
3678 }
3679
Eli Friedman3164fb12009-03-22 22:00:50 +00003680 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003681 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003682 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003683 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003684 return ExprError();
3685
Chris Lattner08464942007-12-28 05:29:59 +00003686 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003687 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003688 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003689
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003690 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003691 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003692 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003693 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003694 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003695 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003696
Douglas Gregord8e97de2009-04-02 15:37:10 +00003697 if (FDecl) {
3698 // Check if we have too few/too many template arguments, based
3699 // on our knowledge of the function definition.
3700 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003701 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003702 const FunctionProtoType *Proto
3703 = Def->getType()->getAs<FunctionProtoType>();
3704 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003705 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3706 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003707 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003708
3709 // If the function we're calling isn't a function prototype, but we have
3710 // a function prototype from a prior declaratiom, use that prototype.
3711 if (!FDecl->hasPrototype())
3712 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003713 }
3714
Steve Naroff0b661582007-08-28 23:30:39 +00003715 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003716 for (unsigned i = 0; i != NumArgs; i++) {
3717 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003718
3719 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003720 InitializedEntity Entity
3721 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003722 Proto->getArgType(i),
3723 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003724 ExprResult ArgE = PerformCopyInitialization(Entity,
3725 SourceLocation(),
3726 Owned(Arg));
3727 if (ArgE.isInvalid())
3728 return true;
3729
3730 Arg = ArgE.takeAs<Expr>();
3731
3732 } else {
John Wiegley01296292011-04-08 18:41:53 +00003733 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3734
3735 if (ArgE.isInvalid())
3736 return true;
3737
3738 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003739 }
3740
Douglas Gregor83025412010-10-26 05:45:40 +00003741 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3742 Arg->getType(),
3743 PDiag(diag::err_call_incomplete_argument)
3744 << Arg->getSourceRange()))
3745 return ExprError();
3746
Chris Lattner08464942007-12-28 05:29:59 +00003747 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003748 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003749 }
Chris Lattner08464942007-12-28 05:29:59 +00003750
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003751 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3752 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003753 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3754 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003755
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003756 // Check for sentinels
3757 if (NDecl)
3758 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003759
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003760 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003761 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003762 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003763 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003764
John McCallbebede42011-02-26 05:39:39 +00003765 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003766 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003767 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003768 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003769 return ExprError();
3770 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003771
John McCallb268a282010-08-23 23:25:46 +00003772 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003773}
3774
John McCalldadc5752010-08-24 06:29:42 +00003775ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003776Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003777 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003778 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003779 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003780 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003781
3782 TypeSourceInfo *TInfo;
3783 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3784 if (!TInfo)
3785 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3786
John McCallb268a282010-08-23 23:25:46 +00003787 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003788}
3789
John McCalldadc5752010-08-24 06:29:42 +00003790ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003791Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003792 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003793 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003794
Eli Friedman37a186d2008-05-20 05:22:08 +00003795 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003796 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3797 PDiag(diag::err_illegal_decl_array_incomplete_type)
3798 << SourceRange(LParenLoc,
3799 literalExpr->getSourceRange().getEnd())))
3800 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003801 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003802 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3803 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003804 } else if (!literalType->isDependentType() &&
3805 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003806 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003807 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003808 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003809 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003810
Douglas Gregor85dabae2009-12-16 01:38:02 +00003811 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003812 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003813 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003814 = InitializationKind::CreateCStyleCast(LParenLoc,
3815 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003816 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003817 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003818 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003819 &literalType);
3820 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003821 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003822 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003823
Chris Lattner79413952008-12-04 23:50:19 +00003824 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003825 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003826 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003827 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003828 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003829
John McCall7decc9e2010-11-18 06:31:45 +00003830 // In C, compound literals are l-values for some reason.
3831 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3832
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003833 return MaybeBindToTemporary(
3834 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3835 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003836}
3837
John McCalldadc5752010-08-24 06:29:42 +00003838ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003839Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003840 SourceLocation RBraceLoc) {
3841 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003842 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003843
Steve Naroff30d242c2007-09-15 18:49:24 +00003844 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003845 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003846
Ted Kremenekac034612010-04-13 23:39:13 +00003847 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3848 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003849 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003850 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003851}
3852
John McCalld7646252010-11-14 08:17:51 +00003853/// Prepares for a scalar cast, performing all the necessary stages
3854/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003855static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003856 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3857 // Also, callers should have filtered out the invalid cases with
3858 // pointers. Everything else should be possible.
3859
John Wiegley01296292011-04-08 18:41:53 +00003860 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003861 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003862 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003863
John McCall8cb679e2010-11-15 09:13:47 +00003864 switch (SrcTy->getScalarTypeKind()) {
3865 case Type::STK_MemberPointer:
3866 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003867
John McCall8cb679e2010-11-15 09:13:47 +00003868 case Type::STK_Pointer:
3869 switch (DestTy->getScalarTypeKind()) {
3870 case Type::STK_Pointer:
3871 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003872 CK_AnyPointerToObjCPointerCast :
3873 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003874 case Type::STK_Bool:
3875 return CK_PointerToBoolean;
3876 case Type::STK_Integral:
3877 return CK_PointerToIntegral;
3878 case Type::STK_Floating:
3879 case Type::STK_FloatingComplex:
3880 case Type::STK_IntegralComplex:
3881 case Type::STK_MemberPointer:
3882 llvm_unreachable("illegal cast from pointer");
3883 }
3884 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003885
John McCall8cb679e2010-11-15 09:13:47 +00003886 case Type::STK_Bool: // casting from bool is like casting from an integer
3887 case Type::STK_Integral:
3888 switch (DestTy->getScalarTypeKind()) {
3889 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003890 if (Src.get()->isNullPointerConstant(S.Context,
3891 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003892 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003893 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003894 case Type::STK_Bool:
3895 return CK_IntegralToBoolean;
3896 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003897 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003898 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003899 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003900 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003901 Src = S.ImpCastExprToType(Src.take(),
3902 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003903 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003904 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003905 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003906 Src = S.ImpCastExprToType(Src.take(),
3907 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003908 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003909 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003910 case Type::STK_MemberPointer:
3911 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003912 }
3913 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003914
John McCall8cb679e2010-11-15 09:13:47 +00003915 case Type::STK_Floating:
3916 switch (DestTy->getScalarTypeKind()) {
3917 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003918 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003919 case Type::STK_Bool:
3920 return CK_FloatingToBoolean;
3921 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003922 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003923 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003924 Src = S.ImpCastExprToType(Src.take(),
3925 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003926 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003927 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003928 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003929 Src = S.ImpCastExprToType(Src.take(),
3930 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003931 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003932 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003933 case Type::STK_Pointer:
3934 llvm_unreachable("valid float->pointer cast?");
3935 case Type::STK_MemberPointer:
3936 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003937 }
3938 break;
3939
John McCall8cb679e2010-11-15 09:13:47 +00003940 case Type::STK_FloatingComplex:
3941 switch (DestTy->getScalarTypeKind()) {
3942 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003943 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003944 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003945 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003946 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003947 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003948 if (S.Context.hasSameType(ET, DestTy))
3949 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003950 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003951 return CK_FloatingCast;
3952 }
John McCall8cb679e2010-11-15 09:13:47 +00003953 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003954 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003955 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003956 Src = S.ImpCastExprToType(Src.take(),
3957 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003958 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003959 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003960 case Type::STK_Pointer:
3961 llvm_unreachable("valid complex float->pointer cast?");
3962 case Type::STK_MemberPointer:
3963 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003964 }
3965 break;
3966
John McCall8cb679e2010-11-15 09:13:47 +00003967 case Type::STK_IntegralComplex:
3968 switch (DestTy->getScalarTypeKind()) {
3969 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003970 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003971 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003972 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003973 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003974 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003975 if (S.Context.hasSameType(ET, DestTy))
3976 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003977 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003978 return CK_IntegralCast;
3979 }
John McCall8cb679e2010-11-15 09:13:47 +00003980 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003981 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003982 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003983 Src = S.ImpCastExprToType(Src.take(),
3984 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003985 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003986 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003987 case Type::STK_Pointer:
3988 llvm_unreachable("valid complex int->pointer cast?");
3989 case Type::STK_MemberPointer:
3990 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003991 }
3992 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003993 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003994
John McCalld7646252010-11-14 08:17:51 +00003995 llvm_unreachable("Unhandled scalar cast");
3996 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003997}
3998
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003999/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00004000ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
4001 QualType castType, Expr *castExpr,
4002 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00004003 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00004004 if (castExpr->getType() == Context.UnknownAnyTy)
4005 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
4006
Sebastian Redl9f831db2009-07-25 15:41:38 +00004007 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004008 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00004009 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004010 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004011 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004012
John McCall3aef3d82011-04-10 19:13:55 +00004013 assert(!castExpr->getType()->isPlaceholderType());
4014
John McCall7decc9e2010-11-18 06:31:45 +00004015 // We only support r-value casts in C.
4016 VK = VK_RValue;
4017
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004018 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4019 // type needs to be scalar.
4020 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004021 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00004022 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4023 if (castExprRes.isInvalid())
4024 return ExprError();
4025 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004026
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004027 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004028 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00004029 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004030 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004031
John Wiegley01296292011-04-08 18:41:53 +00004032 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4033 if (castExprRes.isInvalid())
4034 return ExprError();
4035 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004036
Eli Friedmane98194d2010-07-17 20:43:49 +00004037 if (RequireCompleteType(TyR.getBegin(), castType,
4038 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004039 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004040
Anders Carlssonef918ac2009-10-16 02:35:04 +00004041 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004042 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004043 (castType->isStructureType() || castType->isUnionType())) {
4044 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004045 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004046 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4047 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004048 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00004049 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004050 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004051
Anders Carlsson525b76b2009-10-16 02:48:28 +00004052 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004053 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004054 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004055 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004056 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004057 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004058 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004059 castExpr->getType()) &&
4060 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004061 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4062 << castExpr->getSourceRange();
4063 break;
4064 }
4065 }
John Wiegley01296292011-04-08 18:41:53 +00004066 if (Field == FieldEnd) {
4067 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004068 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004069 return ExprError();
4070 }
John McCalle3027922010-08-25 11:45:40 +00004071 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004072 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004073 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004074
Anders Carlsson525b76b2009-10-16 02:48:28 +00004075 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004076 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004077 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004078 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004079 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004080
John McCalld7646252010-11-14 08:17:51 +00004081 // The type we're casting to is known to be a scalar or vector.
4082
4083 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004084 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004085 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004086 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004087 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004088 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004089 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004090 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004091
4092 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004093 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004094
Anton Yartsev28ccef72011-03-27 09:32:40 +00004095 if (castType->isVectorType()) {
4096 if (castType->getAs<VectorType>()->getVectorKind() ==
4097 VectorType::AltiVecVector &&
4098 (castExpr->getType()->isIntegerType() ||
4099 castExpr->getType()->isFloatingType())) {
4100 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004101 return Owned(castExpr);
4102 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4103 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004104 } else
John Wiegley01296292011-04-08 18:41:53 +00004105 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004106 }
John Wiegley01296292011-04-08 18:41:53 +00004107 if (castExpr->getType()->isVectorType()) {
4108 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4109 return ExprError();
4110 else
4111 return Owned(castExpr);
4112 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004113
John McCalld7646252010-11-14 08:17:51 +00004114 // The source and target types are both scalars, i.e.
4115 // - arithmetic types (fundamental, enum, and complex)
4116 // - all kinds of pointers
4117 // Note that member pointers were filtered out with C++, above.
4118
John Wiegley01296292011-04-08 18:41:53 +00004119 if (isa<ObjCSelectorExpr>(castExpr)) {
4120 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4121 return ExprError();
4122 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004123
John McCalld7646252010-11-14 08:17:51 +00004124 // If either type is a pointer, the other type has to be either an
4125 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004126 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004127 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004128 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004129 castExprType->isArithmeticType()) {
4130 Diag(castExpr->getLocStart(),
4131 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004132 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004133 return ExprError();
4134 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004135 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004136 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4137 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004138 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004139 return ExprError();
4140 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004141 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004142
John McCall31168b02011-06-15 23:02:42 +00004143 if (getLangOptions().ObjCAutoRefCount) {
4144 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4145 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4146 castType, castExpr, CCK_CStyleCast);
4147
4148 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4149 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4150 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4151 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4152 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4153 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4154 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4155 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004156 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004157 << castExprType << castType << AA_Casting
4158 << castExpr->getSourceRange();
4159
4160 return ExprError();
4161 }
4162 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004163 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004164 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4165 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004166 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004167 << castExprType << castType
4168 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004169 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004170 }
4171 }
4172
John Wiegley01296292011-04-08 18:41:53 +00004173 castExprRes = Owned(castExpr);
4174 Kind = PrepareScalarCast(*this, castExprRes, castType);
4175 if (castExprRes.isInvalid())
4176 return ExprError();
4177 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004178
John McCalld7646252010-11-14 08:17:51 +00004179 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004180 CheckCastAlign(castExpr, castType, TyR);
4181
John Wiegley01296292011-04-08 18:41:53 +00004182 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004183}
4184
Anders Carlsson525b76b2009-10-16 02:48:28 +00004185bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004186 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004187 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004188
Anders Carlssonde71adf2007-11-27 05:51:55 +00004189 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004190 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004191 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004192 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004193 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004194 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004195 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004196 } else
4197 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004198 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004199 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004200
John McCalle3027922010-08-25 11:45:40 +00004201 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004202 return false;
4203}
4204
John Wiegley01296292011-04-08 18:41:53 +00004205ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4206 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004207 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004208
Anders Carlsson43d70f82009-10-16 05:23:41 +00004209 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004210
Nate Begemanc8961a42009-06-27 22:05:55 +00004211 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4212 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004213 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004214 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4215 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004216 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004217 return ExprError();
4218 }
John McCalle3027922010-08-25 11:45:40 +00004219 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004220 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004221 }
4222
Nate Begemanbd956c42009-06-28 02:36:38 +00004223 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004224 // conversion will take place first from scalar to elt type, and then
4225 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004226 if (SrcTy->isPointerType())
4227 return Diag(R.getBegin(),
4228 diag::err_invalid_conversion_between_vector_and_scalar)
4229 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004230
4231 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004232 ExprResult CastExprRes = Owned(CastExpr);
4233 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4234 if (CastExprRes.isInvalid())
4235 return ExprError();
4236 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004237
John McCalle3027922010-08-25 11:45:40 +00004238 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004239 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004240}
4241
John McCalldadc5752010-08-24 06:29:42 +00004242ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004243Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4244 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004245 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004246 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004247 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004248
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004249 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4250 if (D.isInvalidType())
4251 return ExprError();
4252
4253 if (getLangOptions().CPlusPlus) {
4254 // Check that there are no default arguments (C++ only).
4255 CheckExtraCXXDefaultArguments(D);
4256 }
4257
4258 QualType castType = castTInfo->getType();
4259 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004260
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004261 bool isVectorLiteral = false;
4262
4263 // Check for an altivec or OpenCL literal,
4264 // i.e. all the elements are integer constants.
4265 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4266 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4267 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4268 if (PLE && PLE->getNumExprs() == 0) {
4269 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4270 return ExprError();
4271 }
4272 if (PE || PLE->getNumExprs() == 1) {
4273 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4274 if (!E->getType()->isVectorType())
4275 isVectorLiteral = true;
4276 }
4277 else
4278 isVectorLiteral = true;
4279 }
4280
4281 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4282 // then handle it as such.
4283 if (isVectorLiteral)
4284 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4285
Nate Begeman5ec4b312009-08-10 23:49:36 +00004286 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004287 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4288 // sequence of BinOp comma operators.
4289 if (isa<ParenListExpr>(castExpr)) {
4290 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4291 if (Result.isInvalid()) return ExprError();
4292 castExpr = Result.take();
4293 }
John McCallebe54742010-01-15 18:56:44 +00004294
John McCallb268a282010-08-23 23:25:46 +00004295 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004296}
4297
John McCalldadc5752010-08-24 06:29:42 +00004298ExprResult
John McCallebe54742010-01-15 18:56:44 +00004299Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004300 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004301 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004302 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004303 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004304 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004305 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4306 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004307 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004308 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004309 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004310
Richard Trieucfc491d2011-08-02 04:35:43 +00004311 return Owned(CStyleCastExpr::Create(
4312 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4313 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004314}
4315
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004316ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4317 SourceLocation RParenLoc, Expr *E,
4318 TypeSourceInfo *TInfo) {
4319 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4320 "Expected paren or paren list expression");
4321
4322 Expr **exprs;
4323 unsigned numExprs;
4324 Expr *subExpr;
4325 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4326 exprs = PE->getExprs();
4327 numExprs = PE->getNumExprs();
4328 } else {
4329 subExpr = cast<ParenExpr>(E)->getSubExpr();
4330 exprs = &subExpr;
4331 numExprs = 1;
4332 }
4333
4334 QualType Ty = TInfo->getType();
4335 assert(Ty->isVectorType() && "Expected vector type");
4336
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004337 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004338 const VectorType *VTy = Ty->getAs<VectorType>();
4339 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4340
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004341 // '(...)' form of vector initialization in AltiVec: the number of
4342 // initializers must be one or must match the size of the vector.
4343 // If a single value is specified in the initializer then it will be
4344 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004345 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004346 // The number of initializers must be one or must match the size of the
4347 // vector. If a single value is specified in the initializer then it will
4348 // be replicated to all the components of the vector
4349 if (numExprs == 1) {
4350 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4351 ExprResult Literal = Owned(exprs[0]);
4352 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4353 PrepareScalarCast(*this, Literal, ElemTy));
4354 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4355 }
4356 else if (numExprs < numElems) {
4357 Diag(E->getExprLoc(),
4358 diag::err_incorrect_number_of_vector_initializers);
4359 return ExprError();
4360 }
4361 else
4362 for (unsigned i = 0, e = numExprs; i != e; ++i)
4363 initExprs.push_back(exprs[i]);
4364 }
Tanya Lattner83559382011-07-15 23:07:01 +00004365 else {
4366 // For OpenCL, when the number of initializers is a single value,
4367 // it will be replicated to all components of the vector.
4368 if (getLangOptions().OpenCL &&
4369 VTy->getVectorKind() == VectorType::GenericVector &&
4370 numExprs == 1) {
4371 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4372 ExprResult Literal = Owned(exprs[0]);
4373 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4374 PrepareScalarCast(*this, Literal, ElemTy));
4375 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4376 }
4377
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004378 for (unsigned i = 0, e = numExprs; i != e; ++i)
4379 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004380 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004381 // FIXME: This means that pretty-printing the final AST will produce curly
4382 // braces instead of the original commas.
4383 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4384 &initExprs[0],
4385 initExprs.size(), RParenLoc);
4386 initE->setType(Ty);
4387 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4388}
4389
Nate Begeman5ec4b312009-08-10 23:49:36 +00004390/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4391/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004392ExprResult
John McCallb268a282010-08-23 23:25:46 +00004393Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004394 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4395 if (!E)
4396 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004397
John McCalldadc5752010-08-24 06:29:42 +00004398 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004399
Nate Begeman5ec4b312009-08-10 23:49:36 +00004400 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004401 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4402 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004403
John McCallb268a282010-08-23 23:25:46 +00004404 if (Result.isInvalid()) return ExprError();
4405
4406 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004407}
4408
John McCalldadc5752010-08-24 06:29:42 +00004409ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004410 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004411 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004412 unsigned nexprs = Val.size();
4413 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004414 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4415 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004416 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004417 expr = new (Context) ParenExpr(L, R, exprs[0]);
4418 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004419 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4420 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004421 return Owned(expr);
4422}
4423
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004424/// \brief Emit a specialized diagnostic when one expression is a null pointer
4425/// constant and the other is not a pointer.
4426bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4427 SourceLocation QuestionLoc) {
4428 Expr *NullExpr = LHS;
4429 Expr *NonPointerExpr = RHS;
4430 Expr::NullPointerConstantKind NullKind =
4431 NullExpr->isNullPointerConstant(Context,
4432 Expr::NPC_ValueDependentIsNotNull);
4433
4434 if (NullKind == Expr::NPCK_NotNull) {
4435 NullExpr = RHS;
4436 NonPointerExpr = LHS;
4437 NullKind =
4438 NullExpr->isNullPointerConstant(Context,
4439 Expr::NPC_ValueDependentIsNotNull);
4440 }
4441
4442 if (NullKind == Expr::NPCK_NotNull)
4443 return false;
4444
4445 if (NullKind == Expr::NPCK_ZeroInteger) {
4446 // In this case, check to make sure that we got here from a "NULL"
4447 // string in the source code.
4448 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004449 SourceLocation loc = NullExpr->getExprLoc();
4450 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004451 return false;
4452 }
4453
4454 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4455 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4456 << NonPointerExpr->getType() << DiagType
4457 << NonPointerExpr->getSourceRange();
4458 return true;
4459}
4460
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004461/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4462/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004463/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004464QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4465 ExprResult &RHS, ExprValueKind &VK,
4466 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004467 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004468
John McCall3aef3d82011-04-10 19:13:55 +00004469 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004470 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004471 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004472
John McCall3aef3d82011-04-10 19:13:55 +00004473 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004474 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004475 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004476
Sebastian Redl1a99f442009-04-16 17:51:27 +00004477 // C++ is sufficiently different to merit its own checker.
4478 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004479 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004480
4481 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004482 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004483
John Wiegley01296292011-04-08 18:41:53 +00004484 Cond = UsualUnaryConversions(Cond.take());
4485 if (Cond.isInvalid())
4486 return QualType();
4487 LHS = UsualUnaryConversions(LHS.take());
4488 if (LHS.isInvalid())
4489 return QualType();
4490 RHS = UsualUnaryConversions(RHS.take());
4491 if (RHS.isInvalid())
4492 return QualType();
4493
4494 QualType CondTy = Cond.get()->getType();
4495 QualType LHSTy = LHS.get()->getType();
4496 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004497
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004498 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004499 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004500 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4501 // Throw an error if its not either.
4502 if (getLangOptions().OpenCL) {
4503 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004504 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004505 diag::err_typecheck_cond_expect_scalar_or_vector)
4506 << CondTy;
4507 return QualType();
4508 }
4509 }
4510 else {
John Wiegley01296292011-04-08 18:41:53 +00004511 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004512 << CondTy;
4513 return QualType();
4514 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004515 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004516
Chris Lattnere2949f42008-01-06 22:42:25 +00004517 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004518 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004519 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004520
Nate Begemanabb5a732010-09-20 22:41:17 +00004521 // OpenCL: If the condition is a vector, and both operands are scalar,
4522 // attempt to implicity convert them to the vector type to act like the
4523 // built in select.
4524 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4525 // Both operands should be of scalar type.
4526 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004527 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004528 << CondTy;
4529 return QualType();
4530 }
4531 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004532 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004533 << CondTy;
4534 return QualType();
4535 }
4536 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004537 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4538 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004539 }
4540
Chris Lattnere2949f42008-01-06 22:42:25 +00004541 // If both operands have arithmetic type, do the usual arithmetic conversions
4542 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004543 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4544 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004545 if (LHS.isInvalid() || RHS.isInvalid())
4546 return QualType();
4547 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004549
Chris Lattnere2949f42008-01-06 22:42:25 +00004550 // If both operands are the same structure or union type, the result is that
4551 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004552 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4553 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004554 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004555 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004556 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004557 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004558 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004559 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004560
Chris Lattnere2949f42008-01-06 22:42:25 +00004561 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004562 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004563 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4564 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004565 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4566 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004567 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004568 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4569 << LHS.get()->getSourceRange();
4570 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4571 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004572 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004573 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004574 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4575 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004576 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004577 RHS.get()->isNullPointerConstant(Context,
4578 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004579 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004580 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004581 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004582 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004583 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004584 LHS.get()->isNullPointerConstant(Context,
4585 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00004586 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004587 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004588 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004589
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004590 // All objective-c pointer type analysis is done here.
4591 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4592 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004593 if (LHS.isInvalid() || RHS.isInvalid())
4594 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004595 if (!compositeType.isNull())
4596 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004597
4598
Steve Naroff05efa972009-07-01 14:36:47 +00004599 // Handle block pointer types.
4600 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4601 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4602 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4603 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004604 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4605 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004606 return destType;
4607 }
4608 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004609 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4610 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004611 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004612 }
Steve Naroff05efa972009-07-01 14:36:47 +00004613 // We have 2 block pointer types.
4614 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4615 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004616 return LHSTy;
4617 }
Steve Naroff05efa972009-07-01 14:36:47 +00004618 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4620 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004621
Steve Naroff05efa972009-07-01 14:36:47 +00004622 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4623 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004624 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004625 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4626 << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004627 // In this situation, we assume void* type. No especially good
4628 // reason, but this is what gcc does, and we do have to pick
4629 // to get a consistent AST.
4630 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004631 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4632 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004633 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004634 }
Steve Naroff05efa972009-07-01 14:36:47 +00004635 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004636 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4637 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004638 return LHSTy;
4639 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004640
Steve Naroff05efa972009-07-01 14:36:47 +00004641 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4642 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4643 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004644 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4645 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004646
4647 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4648 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4649 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004650 QualType destPointee
4651 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004652 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004653 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004654 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004655 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004656 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004657 return destType;
4658 }
4659 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004660 QualType destPointee
4661 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004662 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004663 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004664 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004665 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004666 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004667 return destType;
4668 }
4669
4670 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4671 // Two identical pointer types are always compatible.
4672 return LHSTy;
4673 }
4674 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4675 rhptee.getUnqualifiedType())) {
4676 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004677 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4678 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004679 // In this situation, we assume void* type. No especially good
4680 // reason, but this is what gcc does, and we do have to pick
4681 // to get a consistent AST.
4682 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004683 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4684 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004685 return incompatTy;
4686 }
4687 // The pointer types are compatible.
4688 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4689 // differently qualified versions of compatible types, the result type is
4690 // a pointer to an appropriately qualified version of the *composite*
4691 // type.
4692 // FIXME: Need to calculate the composite type.
4693 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004694 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4695 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004696 return LHSTy;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
John McCalle84af4e2010-11-13 01:35:44 +00004699 // GCC compatibility: soften pointer/integer mismatch. Note that
4700 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004701 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4702 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004703 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4704 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004705 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004706 return RHSTy;
4707 }
4708 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4709 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004710 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4711 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004712 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004713 return LHSTy;
4714 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004715
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004716 // Emit a better diagnostic if one of the expressions is a null pointer
4717 // constant and the other is not a pointer type. In this case, the user most
4718 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004719 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004720 return QualType();
4721
Chris Lattnere2949f42008-01-06 22:42:25 +00004722 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004723 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004724 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4725 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004726 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004727}
4728
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004729/// FindCompositeObjCPointerType - Helper method to find composite type of
4730/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004731QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004732 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004733 QualType LHSTy = LHS.get()->getType();
4734 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004735
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004736 // Handle things like Class and struct objc_class*. Here we case the result
4737 // to the pseudo-builtin, because that will be implicitly cast back to the
4738 // redefinition type if an attempt is made to access its fields.
4739 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004740 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004741 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004742 return LHSTy;
4743 }
4744 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004745 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004746 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004747 return RHSTy;
4748 }
4749 // And the same for struct objc_object* / id
4750 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004751 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004752 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004753 return LHSTy;
4754 }
4755 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004756 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004757 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004758 return RHSTy;
4759 }
4760 // And the same for struct objc_selector* / SEL
4761 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004762 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004763 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004764 return LHSTy;
4765 }
4766 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004767 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004768 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004769 return RHSTy;
4770 }
4771 // Check constraints for Objective-C object pointers types.
4772 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004773
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004774 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4775 // Two identical object pointer types are always compatible.
4776 return LHSTy;
4777 }
4778 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4779 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4780 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004781
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004782 // If both operands are interfaces and either operand can be
4783 // assigned to the other, use that type as the composite
4784 // type. This allows
4785 // xxx ? (A*) a : (B*) b
4786 // where B is a subclass of A.
4787 //
4788 // Additionally, as for assignment, if either type is 'id'
4789 // allow silent coercion. Finally, if the types are
4790 // incompatible then make sure to use 'id' as the composite
4791 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004792
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004793 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4794 // It could return the composite type.
4795 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4796 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4797 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4798 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4799 } else if ((LHSTy->isObjCQualifiedIdType() ||
4800 RHSTy->isObjCQualifiedIdType()) &&
4801 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4802 // Need to handle "id<xx>" explicitly.
4803 // GCC allows qualified id and any Objective-C type to devolve to
4804 // id. Currently localizing to here until clear this should be
4805 // part of ObjCQualifiedIdTypesAreCompatible.
4806 compositeType = Context.getObjCIdType();
4807 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4808 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004809 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004810 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4811 ;
4812 else {
4813 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4814 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004816 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004817 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4818 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004819 return incompatTy;
4820 }
4821 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004822 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4823 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004824 return compositeType;
4825 }
4826 // Check Objective-C object pointer types and 'void *'
4827 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4828 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4829 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4830 QualType destPointee
4831 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4832 QualType destType = Context.getPointerType(destPointee);
4833 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004834 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004835 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004836 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004837 return destType;
4838 }
4839 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4840 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4841 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4842 QualType destPointee
4843 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4844 QualType destType = Context.getPointerType(destPointee);
4845 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004846 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004847 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004848 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 return destType;
4850 }
4851 return QualType();
4852}
4853
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004854/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004855/// ParenRange in parentheses.
4856static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004857 const PartialDiagnostic &Note,
4858 SourceRange ParenRange) {
4859 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4860 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4861 EndLoc.isValid()) {
4862 Self.Diag(Loc, Note)
4863 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4864 << FixItHint::CreateInsertion(EndLoc, ")");
4865 } else {
4866 // We can't display the parentheses, so just show the bare note.
4867 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004868 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004869}
4870
4871static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4872 return Opc >= BO_Mul && Opc <= BO_Shr;
4873}
4874
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004875/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4876/// expression, either using a built-in or overloaded operator,
4877/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4878static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4879 Expr **RHS) {
4880 E = E->IgnoreParenImpCasts();
4881 E = E->IgnoreConversionOperator();
4882 E = E->IgnoreParenImpCasts();
4883
4884 // Built-in binary operator.
4885 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4886 if (IsArithmeticOp(OP->getOpcode())) {
4887 *Opcode = OP->getOpcode();
4888 *RHS = OP->getRHS();
4889 return true;
4890 }
4891 }
4892
4893 // Overloaded operator.
4894 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4895 if (Call->getNumArgs() != 2)
4896 return false;
4897
4898 // Make sure this is really a binary operator that is safe to pass into
4899 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4900 OverloadedOperatorKind OO = Call->getOperator();
4901 if (OO < OO_Plus || OO > OO_Arrow)
4902 return false;
4903
4904 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4905 if (IsArithmeticOp(OpKind)) {
4906 *Opcode = OpKind;
4907 *RHS = Call->getArg(1);
4908 return true;
4909 }
4910 }
4911
4912 return false;
4913}
4914
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004915static bool IsLogicOp(BinaryOperatorKind Opc) {
4916 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4917}
4918
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004919/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4920/// or is a logical expression such as (x==y) which has int type, but is
4921/// commonly interpreted as boolean.
4922static bool ExprLooksBoolean(Expr *E) {
4923 E = E->IgnoreParenImpCasts();
4924
4925 if (E->getType()->isBooleanType())
4926 return true;
4927 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4928 return IsLogicOp(OP->getOpcode());
4929 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4930 return OP->getOpcode() == UO_LNot;
4931
4932 return false;
4933}
4934
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004935/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4936/// and binary operator are mixed in a way that suggests the programmer assumed
4937/// the conditional operator has higher precedence, for example:
4938/// "int x = a + someBinaryCondition ? 1 : 2".
4939static void DiagnoseConditionalPrecedence(Sema &Self,
4940 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004941 Expr *Condition,
4942 Expr *LHS,
4943 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004944 BinaryOperatorKind CondOpcode;
4945 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004946
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004947 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004948 return;
4949 if (!ExprLooksBoolean(CondRHS))
4950 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004951
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004952 // The condition is an arithmetic binary expression, with a right-
4953 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004954
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004955 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004956 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004957 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004958
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004959 SuggestParentheses(Self, OpLoc,
4960 Self.PDiag(diag::note_precedence_conditional_silence)
4961 << BinaryOperator::getOpcodeStr(CondOpcode),
4962 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004963
4964 SuggestParentheses(Self, OpLoc,
4965 Self.PDiag(diag::note_precedence_conditional_first),
4966 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004967}
4968
Steve Naroff83895f72007-09-16 03:34:24 +00004969/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004970/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004971ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004972 SourceLocation ColonLoc,
4973 Expr *CondExpr, Expr *LHSExpr,
4974 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004975 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4976 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004977 OpaqueValueExpr *opaqueValue = 0;
4978 Expr *commonExpr = 0;
4979 if (LHSExpr == 0) {
4980 commonExpr = CondExpr;
4981
4982 // We usually want to apply unary conversions *before* saving, except
4983 // in the special case of a C++ l-value conditional.
4984 if (!(getLangOptions().CPlusPlus
4985 && !commonExpr->isTypeDependent()
4986 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4987 && commonExpr->isGLValue()
4988 && commonExpr->isOrdinaryOrBitFieldObject()
4989 && RHSExpr->isOrdinaryOrBitFieldObject()
4990 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004991 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4992 if (commonRes.isInvalid())
4993 return ExprError();
4994 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004995 }
4996
4997 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4998 commonExpr->getType(),
4999 commonExpr->getValueKind(),
5000 commonExpr->getObjectKind());
5001 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005002 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005003
John McCall7decc9e2010-11-18 06:31:45 +00005004 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005005 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005006 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5007 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005008 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005009 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5010 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005011 return ExprError();
5012
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005013 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5014 RHS.get());
5015
John McCallc07a0c72011-02-17 10:25:35 +00005016 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005017 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5018 LHS.take(), ColonLoc,
5019 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005020
5021 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005022 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005023 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5024 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005025}
5026
John McCallaba90822011-01-31 23:13:11 +00005027// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005028// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005029// routine is it effectively iqnores the qualifiers on the top level pointee.
5030// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5031// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005032static Sema::AssignConvertType
5033checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5034 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5035 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005036
Steve Naroff1f4d7272007-05-11 04:00:31 +00005037 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005038 const Type *lhptee, *rhptee;
5039 Qualifiers lhq, rhq;
5040 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5041 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005042
John McCallaba90822011-01-31 23:13:11 +00005043 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044
5045 // C99 6.5.16.1p1: This following citation is common to constraints
5046 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5047 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005048 Qualifiers lq;
5049
John McCall31168b02011-06-15 23:02:42 +00005050 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5051 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5052 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5053 // Ignore lifetime for further calculation.
5054 lhq.removeObjCLifetime();
5055 rhq.removeObjCLifetime();
5056 }
5057
John McCall4fff8f62011-02-01 00:10:29 +00005058 if (!lhq.compatiblyIncludes(rhq)) {
5059 // Treat address-space mismatches as fatal. TODO: address subspaces
5060 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5061 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5062
John McCall31168b02011-06-15 23:02:42 +00005063 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005064 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005065 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5066 .compatiblyIncludes(
5067 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005068 && (lhptee->isVoidType() || rhptee->isVoidType()))
5069 ; // keep old
5070
John McCall31168b02011-06-15 23:02:42 +00005071 // Treat lifetime mismatches as fatal.
5072 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5073 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5074
John McCall4fff8f62011-02-01 00:10:29 +00005075 // For GCC compatibility, other qualifier mismatches are treated
5076 // as still compatible in C.
5077 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5078 }
Steve Naroff3f597292007-05-11 22:18:03 +00005079
Mike Stump4e1f26a2009-02-19 03:04:26 +00005080 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5081 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005082 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005083 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005084 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005085 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005086
Chris Lattner0a788432008-01-03 22:56:36 +00005087 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005088 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005089 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005090 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005091
Chris Lattner0a788432008-01-03 22:56:36 +00005092 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005093 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005094 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005095
5096 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005097 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005098 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005099 }
John McCall4fff8f62011-02-01 00:10:29 +00005100
Mike Stump4e1f26a2009-02-19 03:04:26 +00005101 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005102 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005103 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5104 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005105 // Check if the pointee types are compatible ignoring the sign.
5106 // We explicitly check for char so that we catch "char" vs
5107 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005108 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005109 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005110 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005111 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005112
Chris Lattnerec3a1562009-10-17 20:33:28 +00005113 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005114 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005115 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005116 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005117
John McCall4fff8f62011-02-01 00:10:29 +00005118 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005119 // Types are compatible ignoring the sign. Qualifier incompatibility
5120 // takes priority over sign incompatibility because the sign
5121 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005122 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005123 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005124
John McCallaba90822011-01-31 23:13:11 +00005125 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005126 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005127
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005128 // If we are a multi-level pointer, it's possible that our issue is simply
5129 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5130 // the eventual target type is the same and the pointers have the same
5131 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005132 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005133 do {
John McCall4fff8f62011-02-01 00:10:29 +00005134 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5135 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005136 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005137
John McCall4fff8f62011-02-01 00:10:29 +00005138 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005139 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005140 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005141
Eli Friedman80160bd2009-03-22 23:59:44 +00005142 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005143 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005144 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005145 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005146}
5147
John McCallaba90822011-01-31 23:13:11 +00005148/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005149/// block pointer types are compatible or whether a block and normal pointer
5150/// are compatible. It is more restrict than comparing two function pointer
5151// types.
John McCallaba90822011-01-31 23:13:11 +00005152static Sema::AssignConvertType
5153checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5154 QualType rhsType) {
5155 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5156 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5157
Steve Naroff081c7422008-09-04 15:10:53 +00005158 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005159
Steve Naroff081c7422008-09-04 15:10:53 +00005160 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005161 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5162 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163
John McCallaba90822011-01-31 23:13:11 +00005164 // In C++, the types have to match exactly.
5165 if (S.getLangOptions().CPlusPlus)
5166 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005167
John McCallaba90822011-01-31 23:13:11 +00005168 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005169
Steve Naroff081c7422008-09-04 15:10:53 +00005170 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005171 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5172 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005173
John McCallaba90822011-01-31 23:13:11 +00005174 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5175 return Sema::IncompatibleBlockPointer;
5176
Steve Naroff081c7422008-09-04 15:10:53 +00005177 return ConvTy;
5178}
5179
John McCallaba90822011-01-31 23:13:11 +00005180/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005181/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005182static Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005183checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5184 QualType rhsType) {
John McCallaba90822011-01-31 23:13:11 +00005185 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5186 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5187
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005188 if (lhsType->isObjCBuiltinType()) {
5189 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005190 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5191 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005192 return Sema::IncompatiblePointer;
5193 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005194 }
5195 if (rhsType->isObjCBuiltinType()) {
5196 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005197 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5198 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005199 return Sema::IncompatiblePointer;
5200 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005201 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005202 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005203 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005204 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005205 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005206
John McCallaba90822011-01-31 23:13:11 +00005207 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5208 return Sema::CompatiblePointerDiscardsQualifiers;
5209
5210 if (S.Context.typesAreCompatible(lhsType, rhsType))
5211 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005212 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005213 return Sema::IncompatibleObjCQualifiedId;
5214 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005215}
5216
John McCall29600e12010-11-16 02:32:08 +00005217Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005218Sema::CheckAssignmentConstraints(SourceLocation Loc,
5219 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005220 // Fake up an opaque expression. We don't actually care about what
5221 // cast operations are required, so if CheckAssignmentConstraints
5222 // adds casts to this they'll be wasted, but fortunately that doesn't
5223 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005224 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005225 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005226 CastKind K = CK_Invalid;
5227
5228 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5229}
5230
Mike Stump4e1f26a2009-02-19 03:04:26 +00005231/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5232/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005233/// pointers. Here are some objectionable examples that GCC considers warnings:
5234///
5235/// int a, *pint;
5236/// short *pshort;
5237/// struct foo *pfoo;
5238///
5239/// pint = pshort; // warning: assignment from incompatible pointer type
5240/// a = pint; // warning: assignment makes integer from pointer without a cast
5241/// pint = a; // warning: assignment makes pointer from integer without a cast
5242/// pint = pfoo; // warning: assignment from incompatible pointer type
5243///
5244/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005245/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005246///
John McCall8cb679e2010-11-15 09:13:47 +00005247/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005248Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005249Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005250 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005251 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005252 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005253
Chris Lattnera52c2f22008-01-04 23:18:45 +00005254 // Get canonical types. We're not formatting these types, just comparing
5255 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005256 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5257 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005258
John McCalle5255932011-01-31 22:28:28 +00005259 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005260 if (lhsType == rhsType) {
5261 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005262 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005263 }
5264
Douglas Gregor6b754842008-10-28 00:22:11 +00005265 // If the left-hand side is a reference type, then we are in a
5266 // (rare!) case where we've allowed the use of references in C,
5267 // e.g., as a parameter type in a built-in function. In this case,
5268 // just make sure that the type referenced is compatible with the
5269 // right-hand side type. The caller is responsible for adjusting
5270 // lhsType so that the resulting expression does not have reference
5271 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005272 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005273 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5274 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005275 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005276 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005277 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005278 }
John McCalle5255932011-01-31 22:28:28 +00005279
Nate Begemanbd956c42009-06-28 02:36:38 +00005280 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5281 // to the same ExtVector type.
5282 if (lhsType->isExtVectorType()) {
5283 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005284 return Incompatible;
5285 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005286 // CK_VectorSplat does T -> vector T, so first cast to the
5287 // element type.
5288 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5289 if (elType != rhsType) {
5290 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005291 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005292 }
5293 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005294 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005295 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005296 }
Mike Stump11289f42009-09-09 15:08:12 +00005297
John McCalle5255932011-01-31 22:28:28 +00005298 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005299 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005300 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005301 // Allow assignments of an AltiVec vector type to an equivalent GCC
5302 // vector type and vice versa
5303 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5304 Kind = CK_BitCast;
5305 return Compatible;
5306 }
5307
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005308 // If we are allowing lax vector conversions, and LHS and RHS are both
5309 // vectors, the total size only needs to be the same. This is a bitcast;
5310 // no bits are changed but the result type is different.
5311 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005312 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005313 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005314 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005315 }
Chris Lattner881a2122008-01-04 23:32:24 +00005316 }
5317 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005318 }
Eli Friedman3360d892008-05-30 18:07:22 +00005319
John McCalle5255932011-01-31 22:28:28 +00005320 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005321 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005322 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005323 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005324 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005325 }
Eli Friedman3360d892008-05-30 18:07:22 +00005326
John McCalle5255932011-01-31 22:28:28 +00005327 // Conversions to normal pointers.
5328 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5329 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005330 if (isa<PointerType>(rhsType)) {
5331 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005332 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005333 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005334
John McCalle5255932011-01-31 22:28:28 +00005335 // int -> T*
5336 if (rhsType->isIntegerType()) {
5337 Kind = CK_IntegralToPointer; // FIXME: null?
5338 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005339 }
John McCalle5255932011-01-31 22:28:28 +00005340
5341 // C pointers are not compatible with ObjC object pointers,
5342 // with two exceptions:
5343 if (isa<ObjCObjectPointerType>(rhsType)) {
5344 // - conversions to void*
5345 if (lhsPointer->getPointeeType()->isVoidType()) {
5346 Kind = CK_AnyPointerToObjCPointerCast;
5347 return Compatible;
5348 }
5349
5350 // - conversions from 'Class' to the redefinition type
5351 if (rhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005352 Context.hasSameType(lhsType,
5353 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005354 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005355 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005356 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005357
John McCalle5255932011-01-31 22:28:28 +00005358 Kind = CK_BitCast;
5359 return IncompatiblePointer;
5360 }
5361
5362 // U^ -> void*
5363 if (rhsType->getAs<BlockPointerType>()) {
5364 if (lhsPointer->getPointeeType()->isVoidType()) {
5365 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005366 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005367 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005368 }
John McCalle5255932011-01-31 22:28:28 +00005369
Steve Naroff081c7422008-09-04 15:10:53 +00005370 return Incompatible;
5371 }
5372
John McCalle5255932011-01-31 22:28:28 +00005373 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005374 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005375 // U^ -> T^
5376 if (rhsType->isBlockPointerType()) {
5377 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005378 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005379 }
5380
5381 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005382 if (rhsType->isIntegerType()) {
5383 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005384 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005385 }
5386
John McCalle5255932011-01-31 22:28:28 +00005387 // id -> T^
5388 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5389 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005390 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005391 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005392
John McCalle5255932011-01-31 22:28:28 +00005393 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005394 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005395 if (RHSPT->getPointeeType()->isVoidType()) {
5396 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005397 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005398 }
John McCall8cb679e2010-11-15 09:13:47 +00005399
Chris Lattnera52c2f22008-01-04 23:18:45 +00005400 return Incompatible;
5401 }
5402
John McCalle5255932011-01-31 22:28:28 +00005403 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005404 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005405 // A* -> B*
5406 if (rhsType->isObjCObjectPointerType()) {
5407 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005408 Sema::AssignConvertType result =
5409 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5410 if (getLangOptions().ObjCAutoRefCount &&
5411 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005412 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5413 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005414 return result;
John McCalle5255932011-01-31 22:28:28 +00005415 }
5416
5417 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005418 if (rhsType->isIntegerType()) {
5419 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005420 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005421 }
5422
John McCalle5255932011-01-31 22:28:28 +00005423 // In general, C pointers are not compatible with ObjC object pointers,
5424 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005425 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005426 // - conversions from 'void*'
5427 if (rhsType->isVoidPointerType()) {
5428 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005429 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005430 }
5431
5432 // - conversions to 'Class' from its redefinition type
5433 if (lhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005434 Context.hasSameType(rhsType,
5435 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005436 Kind = CK_BitCast;
5437 return Compatible;
5438 }
5439
5440 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005441 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005442 }
John McCalle5255932011-01-31 22:28:28 +00005443
5444 // T^ -> A*
5445 if (rhsType->isBlockPointerType()) {
5446 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005447 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005448 }
5449
Steve Naroff7cae42b2009-07-10 23:34:53 +00005450 return Incompatible;
5451 }
John McCalle5255932011-01-31 22:28:28 +00005452
5453 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005454 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005455 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005456 if (lhsType == Context.BoolTy) {
5457 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005458 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005459 }
Eli Friedman3360d892008-05-30 18:07:22 +00005460
John McCalle5255932011-01-31 22:28:28 +00005461 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005462 if (lhsType->isIntegerType()) {
5463 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005464 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005465 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005466
Chris Lattnera52c2f22008-01-04 23:18:45 +00005467 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005468 }
John McCalle5255932011-01-31 22:28:28 +00005469
5470 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005471 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005472 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005473 if (lhsType == Context.BoolTy) {
5474 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005476 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005477
John McCalle5255932011-01-31 22:28:28 +00005478 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005479 if (lhsType->isIntegerType()) {
5480 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005481 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005482 }
5483
Steve Naroff7cae42b2009-07-10 23:34:53 +00005484 return Incompatible;
5485 }
Eli Friedman3360d892008-05-30 18:07:22 +00005486
John McCalle5255932011-01-31 22:28:28 +00005487 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005488 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005489 if (Context.typesAreCompatible(lhsType, rhsType)) {
5490 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005491 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005492 }
Bill Wendling216423b2007-05-30 06:30:29 +00005493 }
John McCalle5255932011-01-31 22:28:28 +00005494
Steve Naroff98cf3e92007-06-06 18:38:38 +00005495 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005496}
5497
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005498/// \brief Constructs a transparent union from an expression that is
5499/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005500static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5501 ExprResult &EResult, QualType UnionType,
5502 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005503 // Build an initializer list that designates the appropriate member
5504 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005505 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005506 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005507 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005508 SourceLocation());
5509 Initializer->setType(UnionType);
5510 Initializer->setInitializedFieldInUnion(Field);
5511
5512 // Build a compound literal constructing a value of the transparent
5513 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005514 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005515 EResult = S.Owned(
5516 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5517 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005518}
5519
5520Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005521Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5522 ExprResult &rExpr) {
John Wiegley01296292011-04-08 18:41:53 +00005523 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005524
Mike Stump11289f42009-09-09 15:08:12 +00005525 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005526 // transparent_union GCC extension.
5527 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005528 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005529 return Incompatible;
5530
5531 // The field to initialize within the transparent union.
5532 RecordDecl *UD = UT->getDecl();
5533 FieldDecl *InitField = 0;
5534 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005535 for (RecordDecl::field_iterator it = UD->field_begin(),
5536 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005537 it != itend; ++it) {
5538 if (it->getType()->isPointerType()) {
5539 // If the transparent union contains a pointer type, we allow:
5540 // 1) void pointer
5541 // 2) null pointer constant
5542 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005543 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005544 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005545 InitField = *it;
5546 break;
5547 }
Mike Stump11289f42009-09-09 15:08:12 +00005548
John Wiegley01296292011-04-08 18:41:53 +00005549 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005550 Expr::NPC_ValueDependentIsNull)) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005551 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5552 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005553 InitField = *it;
5554 break;
5555 }
5556 }
5557
John McCall8cb679e2010-11-15 09:13:47 +00005558 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005559 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005560 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005561 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005562 InitField = *it;
5563 break;
5564 }
5565 }
5566
5567 if (!InitField)
5568 return Incompatible;
5569
John Wiegley01296292011-04-08 18:41:53 +00005570 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005571 return Compatible;
5572}
5573
Chris Lattner9bad62c2008-01-04 18:04:52 +00005574Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005575Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005576 if (getLangOptions().CPlusPlus) {
5577 if (!lhsType->isRecordType()) {
5578 // C++ 5.17p3: If the left operand is not of class type, the
5579 // expression is implicitly converted (C++ 4) to the
5580 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005581 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5582 lhsType.getUnqualifiedType(),
5583 AA_Assigning);
5584 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005585 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005586 Sema::AssignConvertType result = Compatible;
5587 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005588 !CheckObjCARCUnavailableWeakConversion(lhsType,
5589 rExpr.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005590 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005591 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005592 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005593 }
5594
5595 // FIXME: Currently, we fall through and treat C++ classes like C
5596 // structures.
John McCall34376a62010-12-04 03:47:34 +00005597 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005598
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005599 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5600 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005601 if ((lhsType->isPointerType() ||
5602 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005603 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005604 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005605 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005606 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005607 return Compatible;
5608 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005609
Chris Lattnere6dcd502007-10-16 02:55:40 +00005610 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005611 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005612 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005613 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005614 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005615 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005616 if (!lhsType->isReferenceType()) {
5617 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5618 if (rExpr.isInvalid())
5619 return Incompatible;
5620 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005621
John McCall8cb679e2010-11-15 09:13:47 +00005622 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005623 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005624 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005625
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005626 // C99 6.5.16.1p2: The value of the right operand is converted to the
5627 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005628 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5629 // so that we can use references in built-in functions even in C.
5630 // The getNonReferenceType() call makes sure that the resulting expression
5631 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005632 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieucfc491d2011-08-02 04:35:43 +00005633 rExpr = ImpCastExprToType(rExpr.take(),
5634 lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005635 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005636}
5637
Richard Trieucfc491d2011-08-02 04:35:43 +00005638QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5639 ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005640 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005641 << lex.get()->getType() << rex.get()->getType()
5642 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005643 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005644}
5645
Eli Friedman1408bc92011-06-23 18:10:35 +00005646QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5647 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005648 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005649 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005650 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005651 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005652 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005653 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005654
Nate Begeman191a6b12008-07-14 18:02:46 +00005655 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005656 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005657 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005658
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005659 // Handle the case of equivalent AltiVec and GCC vector types
5660 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5661 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005662 if (lhsType->isExtVectorType()) {
5663 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5664 return lhsType;
5665 }
5666
5667 if (!isCompAssign)
5668 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005669 return rhsType;
5670 }
5671
Eli Friedman1408bc92011-06-23 18:10:35 +00005672 if (getLangOptions().LaxVectorConversions &&
5673 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5674 // If we are allowing lax vector conversions, and LHS and RHS are both
5675 // vectors, the total size only needs to be the same. This is a
5676 // bitcast; no bits are changed but the result type is different.
5677 // FIXME: Should we really be allowing this?
5678 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5679 return lhsType;
5680 }
5681
Nate Begemanbd956c42009-06-28 02:36:38 +00005682 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5683 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5684 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005685 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005686 swapped = true;
5687 std::swap(rex, lex);
5688 std::swap(rhsType, lhsType);
5689 }
Mike Stump11289f42009-09-09 15:08:12 +00005690
Nate Begeman886448d2009-06-28 19:12:57 +00005691 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005692 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005693 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005694 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005695 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5696 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005697 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005698 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005699 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005700 if (swapped) std::swap(rex, lex);
5701 return lhsType;
5702 }
5703 }
5704 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5705 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005706 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5707 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005708 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005709 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005710 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005711 if (swapped) std::swap(rex, lex);
5712 return lhsType;
5713 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005714 }
5715 }
Mike Stump11289f42009-09-09 15:08:12 +00005716
Nate Begeman886448d2009-06-28 19:12:57 +00005717 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005718 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005719 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005720 << lex.get()->getType() << rex.get()->getType()
5721 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005722 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005723}
5724
Richard Trieucfc491d2011-08-02 04:35:43 +00005725QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5726 SourceLocation Loc,
5727 bool isCompAssign, bool isDiv) {
5728 if (lex.get()->getType()->isVectorType() ||
5729 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005730 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005731
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005732 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005733 if (lex.isInvalid() || rex.isInvalid())
5734 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005735
John Wiegley01296292011-04-08 18:41:53 +00005736 if (!lex.get()->getType()->isArithmeticType() ||
5737 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005738 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005739
Chris Lattnerfaa54172010-01-12 21:23:57 +00005740 // Check for division by zero.
5741 if (isDiv &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005742 rex.get()->isNullPointerConstant(Context,
5743 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005744 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieucfc491d2011-08-02 04:35:43 +00005745 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005746
Chris Lattnerfaa54172010-01-12 21:23:57 +00005747 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005748}
5749
Chris Lattnerfaa54172010-01-12 21:23:57 +00005750QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005751 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005752 if (lex.get()->getType()->isVectorType() ||
5753 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005754 if (lex.get()->getType()->hasIntegerRepresentation() &&
5755 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005756 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005757 return InvalidOperands(Loc, lex, rex);
5758 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005759
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005760 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005761 if (lex.isInvalid() || rex.isInvalid())
5762 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005763
Richard Trieucfc491d2011-08-02 04:35:43 +00005764 if (!lex.get()->getType()->isIntegerType() ||
5765 !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005766 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005767
Chris Lattnerfaa54172010-01-12 21:23:57 +00005768 // Check for remainder by zero.
Richard Trieucfc491d2011-08-02 04:35:43 +00005769 if (rex.get()->isNullPointerConstant(Context,
5770 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005771 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5772 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005773
Chris Lattnerfaa54172010-01-12 21:23:57 +00005774 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005775}
5776
Chandler Carruthc9332212011-06-27 08:02:19 +00005777/// \brief Diagnose invalid arithmetic on two void pointers.
5778static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5779 Expr *LHS, Expr *RHS) {
5780 S.Diag(Loc, S.getLangOptions().CPlusPlus
5781 ? diag::err_typecheck_pointer_arith_void_type
5782 : diag::ext_gnu_void_ptr)
5783 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5784}
5785
5786/// \brief Diagnose invalid arithmetic on a void pointer.
5787static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5788 Expr *Pointer) {
5789 S.Diag(Loc, S.getLangOptions().CPlusPlus
5790 ? diag::err_typecheck_pointer_arith_void_type
5791 : diag::ext_gnu_void_ptr)
5792 << 0 /* one pointer */ << Pointer->getSourceRange();
5793}
5794
5795/// \brief Diagnose invalid arithmetic on two function pointers.
5796static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5797 Expr *LHS, Expr *RHS) {
5798 assert(LHS->getType()->isAnyPointerType());
5799 assert(RHS->getType()->isAnyPointerType());
5800 S.Diag(Loc, S.getLangOptions().CPlusPlus
5801 ? diag::err_typecheck_pointer_arith_function_type
5802 : diag::ext_gnu_ptr_func_arith)
5803 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5804 // We only show the second type if it differs from the first.
5805 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5806 RHS->getType())
5807 << RHS->getType()->getPointeeType()
5808 << LHS->getSourceRange() << RHS->getSourceRange();
5809}
5810
5811/// \brief Diagnose invalid arithmetic on a function pointer.
5812static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5813 Expr *Pointer) {
5814 assert(Pointer->getType()->isAnyPointerType());
5815 S.Diag(Loc, S.getLangOptions().CPlusPlus
5816 ? diag::err_typecheck_pointer_arith_function_type
5817 : diag::ext_gnu_ptr_func_arith)
5818 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5819 << 0 /* one pointer, so only one type */
5820 << Pointer->getSourceRange();
5821}
5822
5823/// \brief Check the validity of an arithmetic pointer operand.
5824///
5825/// If the operand has pointer type, this code will check for pointer types
5826/// which are invalid in arithmetic operations. These will be diagnosed
5827/// appropriately, including whether or not the use is supported as an
5828/// extension.
5829///
5830/// \returns True when the operand is valid to use (even if as an extension).
5831static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5832 Expr *Operand) {
5833 if (!Operand->getType()->isAnyPointerType()) return true;
5834
5835 QualType PointeeTy = Operand->getType()->getPointeeType();
5836 if (PointeeTy->isVoidType()) {
5837 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5838 return !S.getLangOptions().CPlusPlus;
5839 }
5840 if (PointeeTy->isFunctionType()) {
5841 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5842 return !S.getLangOptions().CPlusPlus;
5843 }
5844
5845 if ((Operand->getType()->isPointerType() &&
5846 !Operand->getType()->isDependentType()) ||
5847 Operand->getType()->isObjCObjectPointerType()) {
5848 QualType PointeeTy = Operand->getType()->getPointeeType();
5849 if (S.RequireCompleteType(
5850 Loc, PointeeTy,
5851 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5852 << PointeeTy << Operand->getSourceRange()))
5853 return false;
5854 }
5855
5856 return true;
5857}
5858
5859/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5860/// operands.
5861///
5862/// This routine will diagnose any invalid arithmetic on pointer operands much
5863/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5864/// for emitting a single diagnostic even for operations where both LHS and RHS
5865/// are (potentially problematic) pointers.
5866///
5867/// \returns True when the operand is valid to use (even if as an extension).
5868static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5869 Expr *LHS, Expr *RHS) {
5870 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5871 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5872 if (!isLHSPointer && !isRHSPointer) return true;
5873
5874 QualType LHSPointeeTy, RHSPointeeTy;
5875 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5876 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5877
5878 // Check for arithmetic on pointers to incomplete types.
5879 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5880 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5881 if (isLHSVoidPtr || isRHSVoidPtr) {
5882 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5883 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5884 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5885
5886 return !S.getLangOptions().CPlusPlus;
5887 }
5888
5889 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5890 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5891 if (isLHSFuncPtr || isRHSFuncPtr) {
5892 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5893 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5894 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5895
5896 return !S.getLangOptions().CPlusPlus;
5897 }
5898
5899 Expr *Operands[] = { LHS, RHS };
5900 for (unsigned i = 0; i < 2; ++i) {
5901 Expr *Operand = Operands[i];
5902 if ((Operand->getType()->isPointerType() &&
5903 !Operand->getType()->isDependentType()) ||
5904 Operand->getType()->isObjCObjectPointerType()) {
5905 QualType PointeeTy = Operand->getType()->getPointeeType();
5906 if (S.RequireCompleteType(
5907 Loc, PointeeTy,
5908 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5909 << PointeeTy << Operand->getSourceRange()))
5910 return false;
5911 }
5912 }
5913 return true;
5914}
5915
Chris Lattnerfaa54172010-01-12 21:23:57 +00005916QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005917 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005918 if (lex.get()->getType()->isVectorType() ||
5919 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005920 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005921 if (CompLHSTy) *CompLHSTy = compType;
5922 return compType;
5923 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005924
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005925 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005926 if (lex.isInvalid() || rex.isInvalid())
5927 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005928
Steve Naroffe4718892007-04-27 18:30:00 +00005929 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005930 if (lex.get()->getType()->isArithmeticType() &&
5931 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005932 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005933 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005934 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005935
Eli Friedman8e122982008-05-18 18:08:51 +00005936 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005937 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005938 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005939 std::swap(PExp, IExp);
5940
Steve Naroff6b712a72009-07-14 18:25:06 +00005941 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005942 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005943 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5944 return QualType();
5945
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005946 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005947
Chris Lattner12bdebb2009-04-24 23:50:08 +00005948 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005949 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005950 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5951 << PointeeTy << PExp->getSourceRange();
5952 return QualType();
5953 }
Mike Stump11289f42009-09-09 15:08:12 +00005954
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005955 // Check array bounds for pointer arithemtic
5956 CheckArrayAccess(PExp, IExp);
5957
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005958 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005959 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005960 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005961 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005962 if (LHSTy->isPromotableIntegerType())
5963 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005964 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005965 *CompLHSTy = LHSTy;
5966 }
Eli Friedman8e122982008-05-18 18:08:51 +00005967 return PExp->getType();
5968 }
5969 }
5970
Chris Lattner326f7572008-11-18 01:30:42 +00005971 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005972}
5973
Chris Lattner2a3569b2008-04-07 05:30:13 +00005974// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005975QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieucfc491d2011-08-02 04:35:43 +00005976 SourceLocation Loc,
5977 QualType* CompLHSTy) {
5978 if (lex.get()->getType()->isVectorType() ||
5979 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005980 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005981 if (CompLHSTy) *CompLHSTy = compType;
5982 return compType;
5983 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005984
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005985 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005986 if (lex.isInvalid() || rex.isInvalid())
5987 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005988
Chris Lattner4d62f422007-12-09 21:53:25 +00005989 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005990
Chris Lattner4d62f422007-12-09 21:53:25 +00005991 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005992 if (lex.get()->getType()->isArithmeticType() &&
5993 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005994 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005995 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
Chris Lattner4d62f422007-12-09 21:53:25 +00005998 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005999 if (lex.get()->getType()->isAnyPointerType()) {
6000 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006001
Chris Lattner12bdebb2009-04-24 23:50:08 +00006002 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006003 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006004 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006005 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006006 return QualType();
6007 }
Mike Stump11289f42009-09-09 15:08:12 +00006008
Chris Lattner4d62f422007-12-09 21:53:25 +00006009 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006010 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00006011 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6012 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006013
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006014 Expr *IExpr = rex.get()->IgnoreParenCasts();
6015 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6016 OK_Ordinary, IExpr->getExprLoc());
6017 // Check array bounds for pointer arithemtic
6018 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6019
John Wiegley01296292011-04-08 18:41:53 +00006020 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6021 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006022 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006023
Chris Lattner4d62f422007-12-09 21:53:25 +00006024 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006025 if (const PointerType *RHSPTy
6026 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006027 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006028
Eli Friedman168fe152009-05-16 13:54:38 +00006029 if (getLangOptions().CPlusPlus) {
6030 // Pointee types must be the same: C++ [expr.add]
6031 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6032 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006033 << lex.get()->getType() << rex.get()->getType()
6034 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006035 return QualType();
6036 }
6037 } else {
6038 // Pointee types must be compatible C99 6.5.6p3
6039 if (!Context.typesAreCompatible(
6040 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6041 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6042 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006043 << lex.get()->getType() << rex.get()->getType()
6044 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006045 return QualType();
6046 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006047 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006048
Chandler Carruthc9332212011-06-27 08:02:19 +00006049 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6050 lex.get(), rex.get()))
6051 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006052
John Wiegley01296292011-04-08 18:41:53 +00006053 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006054 return Context.getPointerDiffType();
6055 }
6056 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006057
Chris Lattner326f7572008-11-18 01:30:42 +00006058 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006059}
6060
Douglas Gregor0bf31402010-10-08 23:50:27 +00006061static bool isScopedEnumerationType(QualType T) {
6062 if (const EnumType *ET = dyn_cast<EnumType>(T))
6063 return ET->getDecl()->isScoped();
6064 return false;
6065}
6066
John Wiegley01296292011-04-08 18:41:53 +00006067static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006068 SourceLocation Loc, unsigned Opc,
6069 QualType LHSTy) {
6070 llvm::APSInt Right;
6071 // Check right/shifter operand
Richard Trieucfc491d2011-08-02 04:35:43 +00006072 if (rex.get()->isValueDependent() ||
6073 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006074 return;
6075
6076 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006077 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006078 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006079 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006080 return;
6081 }
6082 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006083 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006084 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006085 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006086 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006087 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006088 return;
6089 }
6090 if (Opc != BO_Shl)
6091 return;
6092
6093 // When left shifting an ICE which is signed, we can check for overflow which
6094 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6095 // integers have defined behavior modulo one more than the maximum value
6096 // representable in the result type, so never warn for those.
6097 llvm::APSInt Left;
Richard Trieucfc491d2011-08-02 04:35:43 +00006098 if (lex.get()->isValueDependent() ||
6099 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006100 LHSTy->hasUnsignedIntegerRepresentation())
6101 return;
6102 llvm::APInt ResultBits =
6103 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6104 if (LeftBits.uge(ResultBits))
6105 return;
6106 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6107 Result = Result.shl(Right);
6108
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006109 // Print the bit representation of the signed integer as an unsigned
6110 // hexadecimal number.
6111 llvm::SmallString<40> HexResult;
6112 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6113
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006114 // If we are only missing a sign bit, this is less likely to result in actual
6115 // bugs -- if the result is cast back to an unsigned type, it will have the
6116 // expected value. Thus we place this behind a different warning that can be
6117 // turned off separately if needed.
6118 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006119 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6120 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006121 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006122 return;
6123 }
6124
6125 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006126 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieucfc491d2011-08-02 04:35:43 +00006127 << Left.getBitWidth() << lex.get()->getSourceRange()
6128 << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006129}
6130
Chris Lattner2a3569b2008-04-07 05:30:13 +00006131// C99 6.5.7
Richard Trieucfc491d2011-08-02 04:35:43 +00006132QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6133 SourceLocation Loc, unsigned Opc,
6134 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006135 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006136 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6137 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006138 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006139
Douglas Gregor0bf31402010-10-08 23:50:27 +00006140 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6141 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006142 if (isScopedEnumerationType(lex.get()->getType()) ||
6143 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006144 return InvalidOperands(Loc, lex, rex);
6145 }
6146
Nate Begemane46ee9a2009-10-25 02:26:48 +00006147 // Vector shifts promote their scalar inputs to vector type.
Richard Trieucfc491d2011-08-02 04:35:43 +00006148 if (lex.get()->getType()->isVectorType() ||
6149 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006150 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006151
Chris Lattner5c11c412007-12-12 05:47:28 +00006152 // Shifts don't perform usual arithmetic conversions, they just do integer
6153 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006154
John McCall57cdd882010-12-16 19:28:59 +00006155 // For the LHS, do usual unary conversions, but then reset them away
6156 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006157 ExprResult old_lex = lex;
6158 lex = UsualUnaryConversions(lex.take());
6159 if (lex.isInvalid())
6160 return QualType();
6161 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006162 if (isCompAssign) lex = old_lex;
6163
6164 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006165 rex = UsualUnaryConversions(rex.take());
6166 if (rex.isInvalid())
6167 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006168
Ryan Flynnf53fab82009-08-07 16:20:20 +00006169 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006170 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006171
Chris Lattner5c11c412007-12-12 05:47:28 +00006172 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006173 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006174}
6175
Chandler Carruth17773fc2010-07-10 12:30:03 +00006176static bool IsWithinTemplateSpecialization(Decl *D) {
6177 if (DeclContext *DC = D->getDeclContext()) {
6178 if (isa<ClassTemplateSpecializationDecl>(DC))
6179 return true;
6180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6181 return FD->isFunctionTemplateSpecialization();
6182 }
6183 return false;
6184}
6185
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006186// C99 6.5.8, C++ [expr.rel]
Richard Trieucfc491d2011-08-02 04:35:43 +00006187QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6188 SourceLocation Loc, unsigned OpaqueOpc,
6189 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006190 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006191
Chris Lattner9a152e22009-12-05 05:40:13 +00006192 // Handle vector comparisons separately.
Richard Trieucfc491d2011-08-02 04:35:43 +00006193 if (lex.get()->getType()->isVectorType() ||
6194 rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006195 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006196
John Wiegley01296292011-04-08 18:41:53 +00006197 QualType lType = lex.get()->getType();
6198 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006199
John Wiegley01296292011-04-08 18:41:53 +00006200 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6201 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006202 QualType LHSStrippedType = LHSStripped->getType();
6203 QualType RHSStrippedType = RHSStripped->getType();
6204
Douglas Gregor1beec452011-03-12 01:48:56 +00006205
6206
Chandler Carruth712563b2011-02-17 08:37:06 +00006207 // Two different enums will raise a warning when compared.
6208 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6209 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6210 if (LHSEnumType->getDecl()->getIdentifier() &&
6211 RHSEnumType->getDecl()->getIdentifier() &&
6212 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6213 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6214 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006215 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006216 }
6217 }
6218 }
6219
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006220 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006221 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006222 !lex.get()->getLocStart().isMacroID() &&
6223 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006224 // For non-floating point types, check for self-comparisons of the form
6225 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6226 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006227 //
6228 // NOTE: Don't warn about comparison expressions resulting from macro
6229 // expansion. Also don't warn about comparisons which are only self
6230 // comparisons within a template specialization. The warnings should catch
6231 // obvious cases in the definition of the template anyways. The idea is to
6232 // warn when the typed comparison operator will always evaluate to the same
6233 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006234 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006235 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006236 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006237 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006238 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006239 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006240 << (Opc == BO_EQ
6241 || Opc == BO_LE
6242 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006243 } else if (lType->isArrayType() && rType->isArrayType() &&
6244 !DRL->getDecl()->getType()->isReferenceType() &&
6245 !DRR->getDecl()->getType()->isReferenceType()) {
6246 // what is it always going to eval to?
6247 char always_evals_to;
6248 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006249 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006250 always_evals_to = 0; // false
6251 break;
John McCalle3027922010-08-25 11:45:40 +00006252 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006253 always_evals_to = 1; // true
6254 break;
6255 default:
6256 // best we can say is 'a constant'
6257 always_evals_to = 2; // e.g. array1 <= array2
6258 break;
6259 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006260 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006261 << 1 // array
6262 << always_evals_to);
6263 }
6264 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006265 }
Mike Stump11289f42009-09-09 15:08:12 +00006266
Chris Lattner222b8bd2009-03-08 19:39:53 +00006267 if (isa<CastExpr>(LHSStripped))
6268 LHSStripped = LHSStripped->IgnoreParenCasts();
6269 if (isa<CastExpr>(RHSStripped))
6270 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006271
Chris Lattner222b8bd2009-03-08 19:39:53 +00006272 // Warn about comparisons against a string constant (unless the other
6273 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006274 Expr *literalString = 0;
6275 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006276 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006277 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006278 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006279 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006280 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006281 } else if ((isa<StringLiteral>(RHSStripped) ||
6282 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006283 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006284 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006285 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006286 literalStringStripped = RHSStripped;
6287 }
6288
6289 if (literalString) {
6290 std::string resultComparison;
6291 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006292 case BO_LT: resultComparison = ") < 0"; break;
6293 case BO_GT: resultComparison = ") > 0"; break;
6294 case BO_LE: resultComparison = ") <= 0"; break;
6295 case BO_GE: resultComparison = ") >= 0"; break;
6296 case BO_EQ: resultComparison = ") == 0"; break;
6297 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006298 default: assert(false && "Invalid comparison operator");
6299 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006300
Ted Kremenek3427fac2011-02-23 01:52:04 +00006301 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006302 PDiag(diag::warn_stringcompare)
6303 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006304 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006305 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006306 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006307
Douglas Gregorec170db2010-06-08 19:50:34 +00006308 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieucfc491d2011-08-02 04:35:43 +00006309 if (lex.get()->getType()->isArithmeticType() &&
6310 rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006311 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006312 if (lex.isInvalid() || rex.isInvalid())
6313 return QualType();
6314 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006315 else {
John Wiegley01296292011-04-08 18:41:53 +00006316 lex = UsualUnaryConversions(lex.take());
6317 if (lex.isInvalid())
6318 return QualType();
6319
6320 rex = UsualUnaryConversions(rex.take());
6321 if (rex.isInvalid())
6322 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006323 }
6324
John Wiegley01296292011-04-08 18:41:53 +00006325 lType = lex.get()->getType();
6326 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006327
Douglas Gregorca63811b2008-11-19 03:25:36 +00006328 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006329 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006330
Chris Lattnerb620c342007-08-26 01:18:55 +00006331 if (isRelational) {
6332 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006333 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006334 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006335 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006336 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006337 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006338
Chris Lattnerb620c342007-08-26 01:18:55 +00006339 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006340 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006341 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006342
John Wiegley01296292011-04-08 18:41:53 +00006343 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006344 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006345 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006346 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006347
Douglas Gregorf267edd2010-06-15 21:38:40 +00006348 // All of the following pointer-related warnings are GCC extensions, except
6349 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006350 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006351 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006352 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006353 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006354 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006355
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006356 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006357 if (LCanPointeeTy == RCanPointeeTy)
6358 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006359 if (!isRelational &&
6360 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6361 // Valid unless comparison between non-null pointer and function pointer
6362 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006363 // In a SFINAE context, we treat this as a hard error to maintain
6364 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006365 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6366 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006367 Diag(Loc,
6368 isSFINAEContext()?
6369 diag::err_typecheck_comparison_of_fptr_to_void
6370 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006371 << lType << rType << lex.get()->getSourceRange()
6372 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006373
6374 if (isSFINAEContext())
6375 return QualType();
6376
John Wiegley01296292011-04-08 18:41:53 +00006377 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006378 return ResultTy;
6379 }
6380 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006381
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006382 // C++ [expr.rel]p2:
6383 // [...] Pointer conversions (4.10) and qualification
6384 // conversions (4.4) are performed on pointer operands (or on
6385 // a pointer operand and a null pointer constant) to bring
6386 // them to their composite pointer type. [...]
6387 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006388 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006389 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006390 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006391 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006392 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006393 if (T.isNull()) {
6394 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006395 << lType << rType << lex.get()->getSourceRange()
6396 << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006397 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006398 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006399 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006400 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006401 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006402 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006403 }
6404
John Wiegley01296292011-04-08 18:41:53 +00006405 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6406 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006407 return ResultTy;
6408 }
Eli Friedman16c209612009-08-23 00:27:47 +00006409 // C99 6.5.9p2 and C99 6.5.8p2
6410 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6411 RCanPointeeTy.getUnqualifiedType())) {
6412 // Valid unless a relational comparison of function pointers
6413 if (isRelational && LCanPointeeTy->isFunctionType()) {
6414 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006415 << lType << rType << lex.get()->getSourceRange()
6416 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006417 }
6418 } else if (!isRelational &&
6419 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6420 // Valid unless comparison between non-null pointer and function pointer
6421 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6422 && !LHSIsNull && !RHSIsNull) {
6423 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006424 << lType << rType << lex.get()->getSourceRange()
6425 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006426 }
6427 } else {
6428 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006429 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006430 << lType << rType << lex.get()->getSourceRange()
6431 << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006432 }
John McCall7684dde2011-03-11 04:25:25 +00006433 if (LCanPointeeTy != RCanPointeeTy) {
6434 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006435 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006436 else
John Wiegley01296292011-04-08 18:41:53 +00006437 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006438 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006439 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006440 }
Mike Stump11289f42009-09-09 15:08:12 +00006441
Sebastian Redl576fd422009-05-10 18:38:11 +00006442 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006443 // Comparison of nullptr_t with itself.
6444 if (lType->isNullPtrType() && rType->isNullPtrType())
6445 return ResultTy;
6446
Mike Stump11289f42009-09-09 15:08:12 +00006447 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006448 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006449 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006450 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006451 (!isRelational &&
6452 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006453 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006454 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006455 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006456 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006457 return ResultTy;
6458 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006459 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006460 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006461 (!isRelational &&
6462 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006463 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006464 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006465 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006466 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006467 return ResultTy;
6468 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006469
6470 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006471 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006472 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6473 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006474 // In addition, pointers to members can be compared, or a pointer to
6475 // member and a null pointer constant. Pointer to member conversions
6476 // (4.11) and qualification conversions (4.4) are performed to bring
6477 // them to a common type. If one operand is a null pointer constant,
6478 // the common type is the type of the other operand. Otherwise, the
6479 // common type is a pointer to member type similar (4.4) to the type
6480 // of one of the operands, with a cv-qualification signature (4.4)
6481 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006482 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006483 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006484 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006485 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006486 if (T.isNull()) {
6487 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006488 << lType << rType << lex.get()->getSourceRange()
6489 << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006490 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006491 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006492 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006493 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006494 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006495 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006496 }
Mike Stump11289f42009-09-09 15:08:12 +00006497
John Wiegley01296292011-04-08 18:41:53 +00006498 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6499 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006500 return ResultTy;
6501 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006502
6503 // Handle scoped enumeration types specifically, since they don't promote
6504 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006505 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieucfc491d2011-08-02 04:35:43 +00006506 Context.hasSameUnqualifiedType(lex.get()->getType(),
6507 rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006508 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006509 }
Mike Stump11289f42009-09-09 15:08:12 +00006510
Steve Naroff081c7422008-09-04 15:10:53 +00006511 // Handle block pointer types.
Richard Trieucfc491d2011-08-02 04:35:43 +00006512 if (!isRelational && lType->isBlockPointerType() &&
6513 rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006514 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6515 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006516
Steve Naroff081c7422008-09-04 15:10:53 +00006517 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006518 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006519 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006520 << lType << rType << lex.get()->getSourceRange()
6521 << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006522 }
John Wiegley01296292011-04-08 18:41:53 +00006523 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006524 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006525 }
John Wiegley01296292011-04-08 18:41:53 +00006526
Steve Naroffe18f94c2008-09-28 01:11:11 +00006527 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006528 if (!isRelational
6529 && ((lType->isBlockPointerType() && rType->isPointerType())
6530 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006531 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006532 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006533 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006534 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006535 ->getPointeeType()->isVoidType())))
6536 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006537 << lType << rType << lex.get()->getSourceRange()
6538 << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006539 }
John McCall7684dde2011-03-11 04:25:25 +00006540 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006541 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006542 else
John Wiegley01296292011-04-08 18:41:53 +00006543 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006544 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006545 }
Steve Naroff081c7422008-09-04 15:10:53 +00006546
John McCall7684dde2011-03-11 04:25:25 +00006547 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6548 const PointerType *LPT = lType->getAs<PointerType>();
6549 const PointerType *RPT = rType->getAs<PointerType>();
6550 if (LPT || RPT) {
6551 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6552 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006553
Steve Naroff753567f2008-11-17 19:49:16 +00006554 if (!LPtrToVoid && !RPtrToVoid &&
6555 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006556 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006557 << lType << rType << lex.get()->getSourceRange()
6558 << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006559 }
John McCall7684dde2011-03-11 04:25:25 +00006560 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006561 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006562 else
John Wiegley01296292011-04-08 18:41:53 +00006563 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006564 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006565 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006566 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006567 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006568 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006569 << lType << rType << lex.get()->getSourceRange()
6570 << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006571 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006572 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006573 else
John Wiegley01296292011-04-08 18:41:53 +00006574 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006575 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006576 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006577 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006578 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6579 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006580 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006581 bool isError = false;
6582 if ((LHSIsNull && lType->isIntegerType()) ||
6583 (RHSIsNull && rType->isIntegerType())) {
6584 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006585 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006586 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006587 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006588 else if (getLangOptions().CPlusPlus) {
6589 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6590 isError = true;
6591 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006592 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006593
Chris Lattnerd99bd522009-08-23 00:03:44 +00006594 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006595 Diag(Loc, DiagID)
Richard Trieucfc491d2011-08-02 04:35:43 +00006596 << lType << rType << lex.get()->getSourceRange()
6597 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006598 if (isError)
6599 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006600 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006601
6602 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006603 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006604 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006605 else
John Wiegley01296292011-04-08 18:41:53 +00006606 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006607 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006608 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006609 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006610
Steve Naroff4b191572008-09-04 16:56:14 +00006611 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006612 if (!isRelational && RHSIsNull
6613 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006614 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006615 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006616 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006617 if (!isRelational && LHSIsNull
6618 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006619 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006620 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006621 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006622
Chris Lattner326f7572008-11-18 01:30:42 +00006623 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006624}
6625
Nate Begeman191a6b12008-07-14 18:02:46 +00006626/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006627/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006628/// like a scalar comparison, a vector comparison produces a vector of integer
6629/// types.
John Wiegley01296292011-04-08 18:41:53 +00006630QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006631 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006632 bool isRelational) {
6633 // Check to make sure we're operating on vectors of the same type and width,
6634 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006635 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006636 if (vType.isNull())
6637 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006638
John Wiegley01296292011-04-08 18:41:53 +00006639 QualType lType = lex.get()->getType();
6640 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006641
Anton Yartsev530deb92011-03-27 15:36:07 +00006642 // If AltiVec, the comparison results in a numeric type, i.e.
6643 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006644 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006645 return Context.getLogicalOperationType();
6646
Nate Begeman191a6b12008-07-14 18:02:46 +00006647 // For non-floating point types, check for self-comparisons of the form
6648 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6649 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006650 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006651 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6652 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006653 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006654 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006655 PDiag(diag::warn_comparison_always)
6656 << 0 // self-
6657 << 2 // "a constant"
6658 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006659 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006660
Nate Begeman191a6b12008-07-14 18:02:46 +00006661 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006662 if (!isRelational && lType->hasFloatingRepresentation()) {
6663 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006664 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006665 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006666
Nate Begeman191a6b12008-07-14 18:02:46 +00006667 // Return the type for the comparison, which is the same as vector type for
6668 // integer vectors, or an integer type of identical size and number of
6669 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006670 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006671 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006672
John McCall9dd450b2009-09-21 23:43:11 +00006673 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006674 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006675 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006676 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006677 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006678 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6679
Mike Stump4e1f26a2009-02-19 03:04:26 +00006680 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006681 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006682 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6683}
6684
Steve Naroff218bc2b2007-05-04 21:54:46 +00006685inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006686 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00006687 if (lex.get()->getType()->isVectorType() ||
6688 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006689 if (lex.get()->getType()->hasIntegerRepresentation() &&
6690 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006691 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006692
6693 return InvalidOperands(Loc, lex, rex);
6694 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006695
John Wiegley01296292011-04-08 18:41:53 +00006696 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieucfc491d2011-08-02 04:35:43 +00006697 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6698 isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006699 if (lexResult.isInvalid() || rexResult.isInvalid())
6700 return QualType();
6701 lex = lexResult.take();
6702 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006703
John Wiegley01296292011-04-08 18:41:53 +00006704 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6705 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006706 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006707 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006708}
6709
Steve Naroff218bc2b2007-05-04 21:54:46 +00006710inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006711 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006712
6713 // Diagnose cases where the user write a logical and/or but probably meant a
6714 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6715 // is a constant.
Richard Trieucfc491d2011-08-02 04:35:43 +00006716 if (lex.get()->getType()->isIntegerType() &&
6717 !lex.get()->getType()->isBooleanType() &&
John Wiegley01296292011-04-08 18:41:53 +00006718 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006719 // Don't warn in macros or template instantiations.
6720 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006721 // If the RHS can be constant folded, and if it constant folds to something
6722 // that isn't 0 or 1 (which indicate a potential logical operation that
6723 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006724 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006725 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006726 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6727 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6728 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6729 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6730 << rex.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006731 << (Opc == BO_LAnd ? "&&" : "||");
6732 // Suggest replacing the logical operator with the bitwise version
6733 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6734 << (Opc == BO_LAnd ? "&" : "|")
6735 << FixItHint::CreateReplacement(SourceRange(
6736 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6737 getLangOptions())),
6738 Opc == BO_LAnd ? "&" : "|");
6739 if (Opc == BO_LAnd)
6740 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6741 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6742 << FixItHint::CreateRemoval(
6743 SourceRange(
6744 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6745 0, getSourceManager(),
6746 getLangOptions()),
6747 rex.get()->getLocEnd()));
6748 }
Chris Lattner938533d2010-07-24 01:10:11 +00006749 }
Chris Lattner8406c512010-07-13 19:41:32 +00006750
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006751 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006752 lex = UsualUnaryConversions(lex.take());
6753 if (lex.isInvalid())
6754 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006755
John Wiegley01296292011-04-08 18:41:53 +00006756 rex = UsualUnaryConversions(rex.take());
6757 if (rex.isInvalid())
6758 return QualType();
6759
Richard Trieucfc491d2011-08-02 04:35:43 +00006760 if (!lex.get()->getType()->isScalarType() ||
6761 !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006762 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006763
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006764 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006765 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006766
John McCall4a2429a2010-06-04 00:29:51 +00006767 // The following is safe because we only use this method for
6768 // non-overloadable operands.
6769
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006770 // C++ [expr.log.and]p1
6771 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006772 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006773 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6774 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006775 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006776 lex = move(lexRes);
6777
6778 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6779 if (rexRes.isInvalid())
6780 return InvalidOperands(Loc, lex, rex);
6781 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006782
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006783 // C++ [expr.log.and]p2
6784 // C++ [expr.log.or]p2
6785 // The result is a bool.
6786 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006787}
6788
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006789/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6790/// is a read-only property; return true if so. A readonly property expression
6791/// depends on various declarations and thus must be treated specially.
6792///
Mike Stump11289f42009-09-09 15:08:12 +00006793static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006794 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6795 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006796 if (PropExpr->isImplicitProperty()) return false;
6797
6798 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6799 QualType BaseType = PropExpr->isSuperReceiver() ?
6800 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006801 PropExpr->getBase()->getType();
6802
John McCallb7bd14f2010-12-02 01:19:52 +00006803 if (const ObjCObjectPointerType *OPT =
6804 BaseType->getAsObjCInterfacePointerType())
6805 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6806 if (S.isPropertyReadonly(PDecl, IFace))
6807 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006808 }
6809 return false;
6810}
6811
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006812static bool IsConstProperty(Expr *E, Sema &S) {
6813 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6814 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6815 if (PropExpr->isImplicitProperty()) return false;
6816
6817 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6818 QualType T = PDecl->getType();
6819 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006820 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006821 CanQualType CT = S.Context.getCanonicalType(T);
6822 return CT.isConstQualified();
6823 }
6824 return false;
6825}
6826
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006827static bool IsReadonlyMessage(Expr *E, Sema &S) {
6828 if (E->getStmtClass() != Expr::MemberExprClass)
6829 return false;
6830 const MemberExpr *ME = cast<MemberExpr>(E);
6831 NamedDecl *Member = ME->getMemberDecl();
6832 if (isa<FieldDecl>(Member)) {
6833 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6834 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6835 return false;
6836 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6837 }
6838 return false;
6839}
6840
Chris Lattner30bd3272008-11-18 01:22:49 +00006841/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6842/// emit an error and return true. If so, return false.
6843static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006844 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006845 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006846 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006847 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6848 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006849 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6850 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006851 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6852 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006853 if (IsLV == Expr::MLV_Valid)
6854 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006855
Chris Lattner30bd3272008-11-18 01:22:49 +00006856 unsigned Diag = 0;
6857 bool NeedType = false;
6858 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006859 case Expr::MLV_ConstQualified:
6860 Diag = diag::err_typecheck_assign_const;
6861
John McCalld4631322011-06-17 06:42:21 +00006862 // In ARC, use some specialized diagnostics for occasions where we
6863 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006864 if (S.getLangOptions().ObjCAutoRefCount) {
6865 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6866 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6867 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6868
John McCalld4631322011-06-17 06:42:21 +00006869 // Use the normal diagnostic if it's pseudo-__strong but the
6870 // user actually wrote 'const'.
6871 if (var->isARCPseudoStrong() &&
6872 (!var->getTypeSourceInfo() ||
6873 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6874 // There are two pseudo-strong cases:
6875 // - self
John McCall31168b02011-06-15 23:02:42 +00006876 ObjCMethodDecl *method = S.getCurMethodDecl();
6877 if (method && var == method->getSelfDecl())
6878 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006879
6880 // - fast enumeration variables
6881 else
John McCall31168b02011-06-15 23:02:42 +00006882 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006883
John McCall31168b02011-06-15 23:02:42 +00006884 SourceRange Assign;
6885 if (Loc != OrigLoc)
6886 Assign = SourceRange(OrigLoc, OrigLoc);
6887 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6888 // We need to preserve the AST regardless, so migration tool
6889 // can do its job.
6890 return false;
6891 }
6892 }
6893 }
6894
6895 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006897 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6898 NeedType = true;
6899 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006900 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006901 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6902 NeedType = true;
6903 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006904 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006905 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6906 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006907 case Expr::MLV_Valid:
6908 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006909 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006910 case Expr::MLV_MemberFunction:
6911 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006912 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6913 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006914 case Expr::MLV_IncompleteType:
6915 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006916 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006917 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006918 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006919 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006920 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6921 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006922 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006923 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6924 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006925 case Expr::MLV_ReadonlyProperty:
6926 Diag = diag::error_readonly_property_assignment;
6927 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006928 case Expr::MLV_NoSetterProperty:
6929 Diag = diag::error_nosetter_property_assignment;
6930 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006931 case Expr::MLV_InvalidMessageExpression:
6932 Diag = diag::error_readonly_message_assignment;
6933 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006934 case Expr::MLV_SubObjCPropertySetting:
6935 Diag = diag::error_no_subobject_property_setting;
6936 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006937 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006938
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006939 SourceRange Assign;
6940 if (Loc != OrigLoc)
6941 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006942 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006943 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006944 else
Mike Stump11289f42009-09-09 15:08:12 +00006945 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006946 return true;
6947}
6948
6949
6950
6951// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006952QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006953 SourceLocation Loc,
6954 QualType CompoundType) {
6955 // Verify that LHS is a modifiable lvalue, and emit error if not.
6956 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006957 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006958
6959 QualType LHSType = LHS->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00006960 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6961 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006962 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006963 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006964 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006965 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006966 if (LHS->getObjectKind() == OK_ObjCProperty) {
6967 ExprResult LHSResult = Owned(LHS);
6968 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6969 if (LHSResult.isInvalid())
6970 return QualType();
6971 LHS = LHSResult.take();
6972 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006973 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006974 if (RHS.isInvalid())
6975 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006976 // Special case of NSObject attributes on c-style pointer types.
6977 if (ConvTy == IncompatiblePointer &&
6978 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006979 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006980 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006981 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006982 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006983
John McCall7decc9e2010-11-18 06:31:45 +00006984 if (ConvTy == Compatible &&
6985 getLangOptions().ObjCNonFragileABI &&
6986 LHSType->isObjCObjectType())
6987 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6988 << LHSType;
6989
Chris Lattnerea714382008-08-21 18:04:13 +00006990 // If the RHS is a unary plus or minus, check to see if they = and + are
6991 // right next to each other. If so, the user may have typo'd "x =+ 4"
6992 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006993 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006994 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6995 RHSCheck = ICE->getSubExpr();
6996 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006997 if ((UO->getOpcode() == UO_Plus ||
6998 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006999 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007000 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007001 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7002 // And there is a space or other character before the subexpr of the
7003 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007004 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7005 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007006 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007007 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007008 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007009 }
Chris Lattnerea714382008-08-21 18:04:13 +00007010 }
John McCall31168b02011-06-15 23:02:42 +00007011
7012 if (ConvTy == Compatible) {
7013 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7014 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007015 else if (getLangOptions().ObjCAutoRefCount)
7016 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007017 }
Chris Lattnerea714382008-08-21 18:04:13 +00007018 } else {
7019 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007020 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007021 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007022
Chris Lattner326f7572008-11-18 01:30:42 +00007023 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007024 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007025 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007026
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007027 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007028
Steve Naroff98cf3e92007-06-06 18:38:38 +00007029 // C99 6.5.16p3: The type of an assignment expression is the type of the
7030 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007031 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007032 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7033 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007034 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007035 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007036 return (getLangOptions().CPlusPlus
7037 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007038}
7039
Chris Lattner326f7572008-11-18 01:30:42 +00007040// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007041static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007042 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007043 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007044
John McCall3aef3d82011-04-10 19:13:55 +00007045 LHS = S.CheckPlaceholderExpr(LHS.take());
7046 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007047 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007048 return QualType();
7049
John McCall73d36182010-10-12 07:14:40 +00007050 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7051 // operands, but not unary promotions.
7052 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007053
John McCall34376a62010-12-04 03:47:34 +00007054 // So we treat the LHS as a ignored value, and in C++ we allow the
7055 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007056 LHS = S.IgnoredValueConversions(LHS.take());
7057 if (LHS.isInvalid())
7058 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007059
7060 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007061 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7062 if (RHS.isInvalid())
7063 return QualType();
7064 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007065 S.RequireCompleteType(Loc, RHS.get()->getType(),
7066 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007067 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007068
John Wiegley01296292011-04-08 18:41:53 +00007069 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007070}
7071
Steve Naroff7a5af782007-07-13 16:58:59 +00007072/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7073/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007074static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7075 ExprValueKind &VK,
7076 SourceLocation OpLoc,
7077 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007078 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007079 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007080
Chris Lattner6b0cf142008-11-21 07:05:48 +00007081 QualType ResType = Op->getType();
7082 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007083
John McCall4bc41ae2010-11-18 19:01:18 +00007084 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007085 // Decrement of bool is not allowed.
7086 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007087 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007088 return QualType();
7089 }
7090 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007091 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007092 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007093 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007094 } else if (ResType->isAnyPointerType()) {
7095 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007096
Chris Lattner6b0cf142008-11-21 07:05:48 +00007097 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007098 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007099 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007100
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007101 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007102 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7103 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007104 << PointeeTy << Op->getSourceRange();
7105 return QualType();
7106 }
Eli Friedman090addd2010-01-03 00:20:48 +00007107 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007108 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007109 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007110 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007111 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007112 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007113 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007114 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7115 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007116 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7117 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007118 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007119 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007120 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007121 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007122 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007123 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007124 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007125 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007126 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007127 // In C++, a prefix increment is the same type as the operand. Otherwise
7128 // (in C or with postfix), the increment is the unqualified type of the
7129 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007130 if (isPrefix && S.getLangOptions().CPlusPlus) {
7131 VK = VK_LValue;
7132 return ResType;
7133 } else {
7134 VK = VK_RValue;
7135 return ResType.getUnqualifiedType();
7136 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007137}
7138
John Wiegley01296292011-04-08 18:41:53 +00007139ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007140 assert(E->getValueKind() == VK_LValue &&
7141 E->getObjectKind() == OK_ObjCProperty);
7142 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7143
Douglas Gregor33823722011-06-11 01:09:30 +00007144 QualType T = E->getType();
7145 QualType ReceiverType;
7146 if (PRE->isObjectReceiver())
7147 ReceiverType = PRE->getBase()->getType();
7148 else if (PRE->isSuperReceiver())
7149 ReceiverType = PRE->getSuperReceiverType();
7150 else
7151 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7152
John McCall34376a62010-12-04 03:47:34 +00007153 ExprValueKind VK = VK_RValue;
7154 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007155 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007156 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007157 T = getMessageSendResultType(ReceiverType, GetterMethod,
7158 PRE->isClassReceiver(),
7159 PRE->isSuperReceiver());
7160 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007161 }
7162 else {
7163 Diag(PRE->getLocation(), diag::err_getter_not_found)
7164 << PRE->getBase()->getType();
7165 }
John McCall34376a62010-12-04 03:47:34 +00007166 }
Douglas Gregor33823722011-06-11 01:09:30 +00007167
7168 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007169 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007170
7171 ExprResult Result = MaybeBindToTemporary(E);
7172 if (!Result.isInvalid())
7173 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007174
7175 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007176}
7177
Richard Trieucfc491d2011-08-02 04:35:43 +00007178void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7179 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007180 assert(LHS.get()->getValueKind() == VK_LValue &&
7181 LHS.get()->getObjectKind() == OK_ObjCProperty);
7182 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007183
John McCall31168b02011-06-15 23:02:42 +00007184 bool Consumed = false;
7185
John Wiegley01296292011-04-08 18:41:53 +00007186 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007187 // If using property-dot syntax notation for assignment, and there is a
7188 // setter, RHS expression is being passed to the setter argument. So,
7189 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007190 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007191 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7192 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007193 Consumed = (getLangOptions().ObjCAutoRefCount &&
7194 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007195
7196 // Otherwise, if the getter returns an l-value, just call that.
7197 } else {
John Wiegley01296292011-04-08 18:41:53 +00007198 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007199 ExprValueKind VK = Expr::getValueKindForType(Result);
7200 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007201 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7202 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007203 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007204 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007205 }
John McCall31168b02011-06-15 23:02:42 +00007206 } else if (getLangOptions().ObjCAutoRefCount) {
7207 const ObjCMethodDecl *setter
7208 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7209 if (setter) {
7210 ObjCMethodDecl::param_iterator P = setter->param_begin();
7211 LHSTy = (*P)->getType();
7212 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7213 }
John McCall34376a62010-12-04 03:47:34 +00007214 }
7215
John McCall31168b02011-06-15 23:02:42 +00007216 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7217 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007218 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007219 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007220 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007221 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007222 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007223 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7224 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7225 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007226 }
7227}
7228
7229
Anders Carlsson806700f2008-02-01 07:15:58 +00007230/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007231/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007232/// where the declaration is needed for type checking. We only need to
7233/// handle cases when the expression references a function designator
7234/// or is an lvalue. Here are some examples:
7235/// - &(x) => x
7236/// - &*****f => f for f a function designator.
7237/// - &s.xx => s
7238/// - &s.zz[1].yy -> s, if zz is an array
7239/// - *(x + 1) -> x, if x is an array
7240/// - &"123"[2] -> 0
7241/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007242static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007243 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007244 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007245 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007246 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007247 // If this is an arrow operator, the address is an offset from
7248 // the base's value, so the object the base refers to is
7249 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007250 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007251 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007252 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007253 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007254 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007255 // FIXME: This code shouldn't be necessary! We should catch the implicit
7256 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007257 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7258 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7259 if (ICE->getSubExpr()->getType()->isArrayType())
7260 return getPrimaryDecl(ICE->getSubExpr());
7261 }
7262 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007263 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007264 case Stmt::UnaryOperatorClass: {
7265 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007266
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007267 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007268 case UO_Real:
7269 case UO_Imag:
7270 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007271 return getPrimaryDecl(UO->getSubExpr());
7272 default:
7273 return 0;
7274 }
7275 }
Steve Naroff47500512007-04-19 23:00:49 +00007276 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007277 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007278 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007279 // If the result of an implicit cast is an l-value, we care about
7280 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007281 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007282 default:
7283 return 0;
7284 }
7285}
7286
7287/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007288/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007289/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007290/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007291/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007292/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007293/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007294static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7295 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007296 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007297 return S.Context.DependentTy;
7298 if (OrigOp->getType() == S.Context.OverloadTy)
7299 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007300 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7301 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007302 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7303 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7304 << OrigOp->getSourceRange();
7305 return QualType();
7306 }
John McCall8d08b9b2010-08-27 09:08:28 +00007307
John McCall2979fe02011-04-12 00:42:48 +00007308 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007309
John McCall8d08b9b2010-08-27 09:08:28 +00007310 // Make sure to ignore parentheses in subsequent checks
7311 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007312
John McCall4bc41ae2010-11-18 19:01:18 +00007313 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007314 // Implement C99-only parts of addressof rules.
7315 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007316 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007317 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7318 // (assuming the deref expression is valid).
7319 return uOp->getSubExpr()->getType();
7320 }
7321 // Technically, there should be a check for array subscript
7322 // expressions here, but the result of one is always an lvalue anyway.
7323 }
John McCallf3a88602011-02-03 08:15:49 +00007324 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007325 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007326
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007327 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007328 bool sfinae = S.isSFINAEContext();
7329 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7330 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007331 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007332 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007333 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007334 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007335 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007336 } else if (lval == Expr::LV_MemberFunction) {
7337 // If it's an instance method, make a member pointer.
7338 // The expression must have exactly the form &A::foo.
7339
7340 // If the underlying expression isn't a decl ref, give up.
7341 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007342 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007343 << OrigOp->getSourceRange();
7344 return QualType();
7345 }
7346 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7347 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7348
7349 // The id-expression was parenthesized.
7350 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007351 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007352 << OrigOp->getSourceRange();
7353
7354 // The method was named without a qualifier.
7355 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007356 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007357 << op->getSourceRange();
7358 }
7359
John McCall4bc41ae2010-11-18 19:01:18 +00007360 return S.Context.getMemberPointerType(op->getType(),
7361 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007362 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007363 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007364 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007365 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007366 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007367 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007368 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007369 return QualType();
7370 }
John McCall086a4642010-11-24 05:12:34 +00007371 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007372 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007373 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007374 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007375 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007376 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007377 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007378 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007379 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007380 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007381 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007382 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007383 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007384 << "property expression" << op->getSourceRange();
7385 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007386 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007387 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007388 // with the register storage-class specifier.
7389 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007390 // in C++ it is not error to take address of a register
7391 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007392 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007393 !S.getLangOptions().CPlusPlus) {
7394 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007395 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007396 return QualType();
7397 }
John McCalld14a8642009-11-21 08:51:07 +00007398 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007399 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007400 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007401 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007402 // Could be a pointer to member, though, if there is an explicit
7403 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007404 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007405 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007406 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007407 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007408 S.Diag(OpLoc,
7409 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007410 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007411 return QualType();
7412 }
Mike Stump11289f42009-09-09 15:08:12 +00007413
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007414 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7415 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007416 return S.Context.getMemberPointerType(op->getType(),
7417 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007418 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007419 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007420 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007421 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007422 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007423
Eli Friedmance7f9002009-05-16 23:27:50 +00007424 if (lval == Expr::LV_IncompleteVoidType) {
7425 // Taking the address of a void variable is technically illegal, but we
7426 // allow it in cases which are otherwise valid.
7427 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007428 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007429 }
7430
Steve Naroff47500512007-04-19 23:00:49 +00007431 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007432 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007433 return S.Context.getObjCObjectPointerType(op->getType());
7434 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007435}
7436
Chris Lattner9156f1b2010-07-05 19:17:26 +00007437/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007438static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7439 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007440 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007441 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007442
John Wiegley01296292011-04-08 18:41:53 +00007443 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7444 if (ConvResult.isInvalid())
7445 return QualType();
7446 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007447 QualType OpTy = Op->getType();
7448 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007449
7450 if (isa<CXXReinterpretCastExpr>(Op)) {
7451 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7452 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7453 Op->getSourceRange());
7454 }
7455
Chris Lattner9156f1b2010-07-05 19:17:26 +00007456 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7457 // is an incomplete type or void. It would be possible to warn about
7458 // dereferencing a void pointer, but it's completely well-defined, and such a
7459 // warning is unlikely to catch any mistakes.
7460 if (const PointerType *PT = OpTy->getAs<PointerType>())
7461 Result = PT->getPointeeType();
7462 else if (const ObjCObjectPointerType *OPT =
7463 OpTy->getAs<ObjCObjectPointerType>())
7464 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007465 else {
John McCall3aef3d82011-04-10 19:13:55 +00007466 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007467 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007468 if (PR.take() != Op)
7469 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007470 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007471
Chris Lattner9156f1b2010-07-05 19:17:26 +00007472 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007473 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007474 << OpTy << Op->getSourceRange();
7475 return QualType();
7476 }
John McCall4bc41ae2010-11-18 19:01:18 +00007477
7478 // Dereferences are usually l-values...
7479 VK = VK_LValue;
7480
7481 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007482 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007483 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007484
7485 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007486}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007487
John McCalle3027922010-08-25 11:45:40 +00007488static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007489 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007490 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007491 switch (Kind) {
7492 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007493 case tok::periodstar: Opc = BO_PtrMemD; break;
7494 case tok::arrowstar: Opc = BO_PtrMemI; break;
7495 case tok::star: Opc = BO_Mul; break;
7496 case tok::slash: Opc = BO_Div; break;
7497 case tok::percent: Opc = BO_Rem; break;
7498 case tok::plus: Opc = BO_Add; break;
7499 case tok::minus: Opc = BO_Sub; break;
7500 case tok::lessless: Opc = BO_Shl; break;
7501 case tok::greatergreater: Opc = BO_Shr; break;
7502 case tok::lessequal: Opc = BO_LE; break;
7503 case tok::less: Opc = BO_LT; break;
7504 case tok::greaterequal: Opc = BO_GE; break;
7505 case tok::greater: Opc = BO_GT; break;
7506 case tok::exclaimequal: Opc = BO_NE; break;
7507 case tok::equalequal: Opc = BO_EQ; break;
7508 case tok::amp: Opc = BO_And; break;
7509 case tok::caret: Opc = BO_Xor; break;
7510 case tok::pipe: Opc = BO_Or; break;
7511 case tok::ampamp: Opc = BO_LAnd; break;
7512 case tok::pipepipe: Opc = BO_LOr; break;
7513 case tok::equal: Opc = BO_Assign; break;
7514 case tok::starequal: Opc = BO_MulAssign; break;
7515 case tok::slashequal: Opc = BO_DivAssign; break;
7516 case tok::percentequal: Opc = BO_RemAssign; break;
7517 case tok::plusequal: Opc = BO_AddAssign; break;
7518 case tok::minusequal: Opc = BO_SubAssign; break;
7519 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7520 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7521 case tok::ampequal: Opc = BO_AndAssign; break;
7522 case tok::caretequal: Opc = BO_XorAssign; break;
7523 case tok::pipeequal: Opc = BO_OrAssign; break;
7524 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007525 }
7526 return Opc;
7527}
7528
John McCalle3027922010-08-25 11:45:40 +00007529static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007530 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007531 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007532 switch (Kind) {
7533 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007534 case tok::plusplus: Opc = UO_PreInc; break;
7535 case tok::minusminus: Opc = UO_PreDec; break;
7536 case tok::amp: Opc = UO_AddrOf; break;
7537 case tok::star: Opc = UO_Deref; break;
7538 case tok::plus: Opc = UO_Plus; break;
7539 case tok::minus: Opc = UO_Minus; break;
7540 case tok::tilde: Opc = UO_Not; break;
7541 case tok::exclaim: Opc = UO_LNot; break;
7542 case tok::kw___real: Opc = UO_Real; break;
7543 case tok::kw___imag: Opc = UO_Imag; break;
7544 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007545 }
7546 return Opc;
7547}
7548
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007549/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7550/// This warning is only emitted for builtin assignment operations. It is also
7551/// suppressed in the event of macro expansions.
7552static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7553 SourceLocation OpLoc) {
7554 if (!S.ActiveTemplateInstantiations.empty())
7555 return;
7556 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7557 return;
7558 lhs = lhs->IgnoreParenImpCasts();
7559 rhs = rhs->IgnoreParenImpCasts();
7560 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7561 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7562 if (!LeftDeclRef || !RightDeclRef ||
7563 LeftDeclRef->getLocation().isMacroID() ||
7564 RightDeclRef->getLocation().isMacroID())
7565 return;
7566 const ValueDecl *LeftDecl =
7567 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7568 const ValueDecl *RightDecl =
7569 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7570 if (LeftDecl != RightDecl)
7571 return;
7572 if (LeftDecl->getType().isVolatileQualified())
7573 return;
7574 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7575 if (RefTy->getPointeeType().isVolatileQualified())
7576 return;
7577
7578 S.Diag(OpLoc, diag::warn_self_assignment)
7579 << LeftDeclRef->getType()
7580 << lhs->getSourceRange() << rhs->getSourceRange();
7581}
7582
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007583/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7584/// operator @p Opc at location @c TokLoc. This routine only supports
7585/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007586ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007587 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007588 Expr *lhsExpr, Expr *rhsExpr) {
7589 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007590 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007591 // The following two variables are used for compound assignment operators
7592 QualType CompLHSTy; // Type of LHS after promotions for computation
7593 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007594 ExprValueKind VK = VK_RValue;
7595 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007596
Douglas Gregor1beec452011-03-12 01:48:56 +00007597 // Check if a 'foo<int>' involved in a binary op, identifies a single
7598 // function unambiguously (i.e. an lvalue ala 13.4)
7599 // But since an assignment can trigger target based overload, exclude it in
7600 // our blind search. i.e:
7601 // template<class T> void f(); template<class T, class U> void f(U);
7602 // f<int> == 0; // resolve f<int> blindly
7603 // void (*p)(int); p = f<int>; // resolve f<int> using target
7604 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007605 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007606 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007607 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007608
John McCall3aef3d82011-04-10 19:13:55 +00007609 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007610 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007611 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007612 }
7613
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007614 // The canonical way to check for a GNU null is with isNullPointerConstant,
7615 // but we use a bit of a hack here for speed; this is a relatively
7616 // hot path, and isNullPointerConstant is slow.
7617 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7618 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007619
7620 // Detect when a NULL constant is used improperly in an expression. These
7621 // are mainly cases where the null pointer is used as an integer instead
7622 // of a pointer.
7623 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007624 // Avoid analyzing cases where the result will either be invalid (and
7625 // diagnosed as such) or entirely valid and not something to warn about.
7626 QualType LeftType = lhs.get()->getType();
7627 QualType RightType = rhs.get()->getType();
7628 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7629 !LeftType->isFunctionType() &&
7630 !RightType->isBlockPointerType() &&
7631 !RightType->isMemberPointerType() &&
7632 !RightType->isFunctionType()) {
7633 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7634 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7635 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7636 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7637 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7638 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7639 // These are the operations that would not make sense with a null pointer
Richard Trieucfc491d2011-08-02 04:35:43 +00007640 // pointer no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007641 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007642 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7643 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7644 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7645 Opc == BO_EQ || Opc == BO_NE) {
7646 // These are the operations that would not make sense with a null pointer
7647 // if the other expression the other expression is not a pointer.
7648 if (LeftNull != RightNull &&
7649 !LeftType->isAnyPointerType() &&
7650 !LeftType->canDecayToPointerType() &&
7651 !RightType->isAnyPointerType() &&
7652 !RightType->canDecayToPointerType()) {
Richard Trieuaee9e762011-08-11 22:38:21 +00007653 Diag(OpLoc, diag::warn_null_in_comparison_operation)
7654 << LeftNull /* LHS is NULL */
7655 << (LeftNull ? rhs.get()->getType() : lhs.get()->getType())
7656 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
Chandler Carruth4f04b432011-06-20 07:38:51 +00007657 }
Richard Trieu701fb362011-06-16 21:36:56 +00007658 }
7659 }
7660 }
7661
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007662 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007663 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007664 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007665 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007666 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7667 VK = lhs.get()->getValueKind();
7668 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007669 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007670 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007671 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007672 break;
John McCalle3027922010-08-25 11:45:40 +00007673 case BO_PtrMemD:
7674 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007675 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007676 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007677 break;
John McCalle3027922010-08-25 11:45:40 +00007678 case BO_Mul:
7679 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007680 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007681 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007682 break;
John McCalle3027922010-08-25 11:45:40 +00007683 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007684 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7685 break;
John McCalle3027922010-08-25 11:45:40 +00007686 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007687 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7688 break;
John McCalle3027922010-08-25 11:45:40 +00007689 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007690 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7691 break;
John McCalle3027922010-08-25 11:45:40 +00007692 case BO_Shl:
7693 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007694 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007695 break;
John McCalle3027922010-08-25 11:45:40 +00007696 case BO_LE:
7697 case BO_LT:
7698 case BO_GE:
7699 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007700 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007701 break;
John McCalle3027922010-08-25 11:45:40 +00007702 case BO_EQ:
7703 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007704 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007705 break;
John McCalle3027922010-08-25 11:45:40 +00007706 case BO_And:
7707 case BO_Xor:
7708 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007709 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7710 break;
John McCalle3027922010-08-25 11:45:40 +00007711 case BO_LAnd:
7712 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007713 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007714 break;
John McCalle3027922010-08-25 11:45:40 +00007715 case BO_MulAssign:
7716 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007717 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007718 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007719 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007720 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7721 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007722 break;
John McCalle3027922010-08-25 11:45:40 +00007723 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007724 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7725 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007726 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7727 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007728 break;
John McCalle3027922010-08-25 11:45:40 +00007729 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007730 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007731 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7732 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007733 break;
John McCalle3027922010-08-25 11:45:40 +00007734 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007735 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007736 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7737 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007738 break;
John McCalle3027922010-08-25 11:45:40 +00007739 case BO_ShlAssign:
7740 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007741 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007742 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007743 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7744 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007745 break;
John McCalle3027922010-08-25 11:45:40 +00007746 case BO_AndAssign:
7747 case BO_XorAssign:
7748 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007749 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7750 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007751 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7752 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007753 break;
John McCalle3027922010-08-25 11:45:40 +00007754 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007755 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007756 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7757 VK = rhs.get()->getValueKind();
7758 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007759 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007760 break;
7761 }
John Wiegley01296292011-04-08 18:41:53 +00007762 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007763 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007764
7765 // Check for array bounds violations for both sides of the BinaryOperator
7766 CheckArrayAccess(lhs.get());
7767 CheckArrayAccess(rhs.get());
7768
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007769 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007770 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7771 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007772 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7773 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007774 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007775 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007776 }
John Wiegley01296292011-04-08 18:41:53 +00007777 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7778 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007779 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007780}
7781
Sebastian Redl44615072009-10-27 12:10:02 +00007782/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7783/// operators are mixed in a way that suggests that the programmer forgot that
7784/// comparison operators have higher precedence. The most typical example of
7785/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007786static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007787 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007788 typedef BinaryOperator BinOp;
7789 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7790 rhsopc = static_cast<BinOp::Opcode>(-1);
7791 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007792 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007793 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007794 rhsopc = BO->getOpcode();
7795
7796 // Subs are not binary operators.
7797 if (lhsopc == -1 && rhsopc == -1)
7798 return;
7799
7800 // Bitwise operations are sometimes used as eager logical ops.
7801 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007802 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7803 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007804 return;
7805
Richard Trieu73088052011-08-10 22:41:34 +00007806 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7807 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7808 if (!isLeftComp && !isRightComp) return;
7809
7810 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7811 : SourceRange(OpLoc, rhs->getLocEnd());
7812 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7813 : BinOp::getOpcodeStr(rhsopc);
7814 SourceRange ParensRange = isLeftComp ?
7815 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7816 rhs->getLocEnd())
7817 : SourceRange(lhs->getLocStart(),
7818 cast<BinOp>(rhs)->getLHS()->getLocStart());
7819
7820 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7821 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7822 SuggestParentheses(Self, OpLoc,
7823 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7824 rhs->getSourceRange());
7825 SuggestParentheses(Self, OpLoc,
7826 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7827 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007828}
7829
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007830/// \brief It accepts a '&' expr that is inside a '|' one.
7831/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7832/// in parentheses.
7833static void
7834EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7835 BinaryOperator *Bop) {
7836 assert(Bop->getOpcode() == BO_And);
7837 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7838 << Bop->getSourceRange() << OpLoc;
7839 SuggestParentheses(Self, Bop->getOperatorLoc(),
7840 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7841 Bop->getSourceRange());
7842}
7843
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007844/// \brief It accepts a '&&' expr that is inside a '||' one.
7845/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7846/// in parentheses.
7847static void
7848EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007849 BinaryOperator *Bop) {
7850 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007851 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7852 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007853 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007854 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007855 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007856}
7857
7858/// \brief Returns true if the given expression can be evaluated as a constant
7859/// 'true'.
7860static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7861 bool Res;
7862 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7863}
7864
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007865/// \brief Returns true if the given expression can be evaluated as a constant
7866/// 'false'.
7867static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7868 bool Res;
7869 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7870}
7871
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007872/// \brief Look for '&&' in the left hand of a '||' expr.
7873static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007874 Expr *OrLHS, Expr *OrRHS) {
7875 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007876 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007877 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7878 if (EvaluatesAsFalse(S, OrRHS))
7879 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007880 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7881 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7882 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7883 } else if (Bop->getOpcode() == BO_LOr) {
7884 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7885 // If it's "a || b && 1 || c" we didn't warn earlier for
7886 // "a || b && 1", but warn now.
7887 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7888 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7889 }
7890 }
7891 }
7892}
7893
7894/// \brief Look for '&&' in the right hand of a '||' expr.
7895static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007896 Expr *OrLHS, Expr *OrRHS) {
7897 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007898 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007899 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7900 if (EvaluatesAsFalse(S, OrLHS))
7901 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007902 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7903 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7904 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007905 }
7906 }
7907}
7908
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007909/// \brief Look for '&' in the left or right hand of a '|' expr.
7910static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7911 Expr *OrArg) {
7912 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7913 if (Bop->getOpcode() == BO_And)
7914 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7915 }
7916}
7917
Sebastian Redl43028242009-10-26 15:24:15 +00007918/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007919/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007920static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007921 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007922 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007923 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007924 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7925
7926 // Diagnose "arg1 & arg2 | arg3"
7927 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7928 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7929 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7930 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007931
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007932 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7933 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007934 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007935 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7936 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007937 }
Sebastian Redl43028242009-10-26 15:24:15 +00007938}
7939
Steve Naroff218bc2b2007-05-04 21:54:46 +00007940// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007941ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007942 tok::TokenKind Kind,
7943 Expr *lhs, Expr *rhs) {
7944 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007945 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7946 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007947
Sebastian Redl43028242009-10-26 15:24:15 +00007948 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7949 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7950
Douglas Gregor5287f092009-11-05 00:51:44 +00007951 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7952}
7953
John McCalldadc5752010-08-24 06:29:42 +00007954ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007955 BinaryOperatorKind Opc,
7956 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007957 if (getLangOptions().CPlusPlus) {
7958 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007959
John McCall622114c2010-12-06 05:26:58 +00007960 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7961 UseBuiltinOperator = false;
7962 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7963 UseBuiltinOperator = true;
7964 } else {
7965 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7966 !rhs->getType()->isOverloadableType();
7967 }
7968
7969 if (!UseBuiltinOperator) {
7970 // Find all of the overloaded operators visible from this
7971 // point. We perform both an operator-name lookup from the local
7972 // scope and an argument-dependent lookup based on the types of
7973 // the arguments.
7974 UnresolvedSet<16> Functions;
7975 OverloadedOperatorKind OverOp
7976 = BinaryOperator::getOverloadedOperator(Opc);
7977 if (S && OverOp != OO_None)
7978 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7979 Functions);
7980
7981 // Build the (potentially-overloaded, potentially-dependent)
7982 // binary operation.
7983 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7984 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007985 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007986
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007987 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007988 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007989}
7990
John McCalldadc5752010-08-24 06:29:42 +00007991ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007992 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007993 Expr *InputExpr) {
7994 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007995 ExprValueKind VK = VK_RValue;
7996 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007997 QualType resultType;
7998 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007999 case UO_PreInc:
8000 case UO_PreDec:
8001 case UO_PostInc:
8002 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008003 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008004 Opc == UO_PreInc ||
8005 Opc == UO_PostInc,
8006 Opc == UO_PreInc ||
8007 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008008 break;
John McCalle3027922010-08-25 11:45:40 +00008009 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008010 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008011 break;
John McCall31996342011-04-07 08:22:57 +00008012 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008013 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008014 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008015 Input = move(resolved);
8016 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8017 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008018 break;
John McCall31996342011-04-07 08:22:57 +00008019 }
John McCalle3027922010-08-25 11:45:40 +00008020 case UO_Plus:
8021 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008022 Input = UsualUnaryConversions(Input.take());
8023 if (Input.isInvalid()) return ExprError();
8024 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008025 if (resultType->isDependentType())
8026 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008027 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8028 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008029 break;
8030 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8031 resultType->isEnumeralType())
8032 break;
8033 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008034 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008035 resultType->isPointerType())
8036 break;
John McCall36226622010-10-12 02:09:17 +00008037 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008038 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008039 if (Input.isInvalid()) return ExprError();
8040 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008041 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008042
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008043 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008044 << resultType << Input.get()->getSourceRange());
8045
John McCalle3027922010-08-25 11:45:40 +00008046 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008047 Input = UsualUnaryConversions(Input.take());
8048 if (Input.isInvalid()) return ExprError();
8049 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008050 if (resultType->isDependentType())
8051 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008052 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8053 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8054 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008055 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008056 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008057 else if (resultType->hasIntegerRepresentation())
8058 break;
8059 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008060 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008061 if (Input.isInvalid()) return ExprError();
8062 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008063 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008064 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008065 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008066 }
Steve Naroff35d85152007-05-07 00:24:15 +00008067 break;
John Wiegley01296292011-04-08 18:41:53 +00008068
John McCalle3027922010-08-25 11:45:40 +00008069 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008070 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008071 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8072 if (Input.isInvalid()) return ExprError();
8073 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008074 if (resultType->isDependentType())
8075 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008076 if (resultType->isScalarType()) {
8077 // C99 6.5.3.3p1: ok, fallthrough;
8078 if (Context.getLangOptions().CPlusPlus) {
8079 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8080 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008081 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8082 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008083 }
John McCall36226622010-10-12 02:09:17 +00008084 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008085 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008086 if (Input.isInvalid()) return ExprError();
8087 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008088 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008089 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008090 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008091 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008092
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008093 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008094 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008095 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008096 break;
John McCalle3027922010-08-25 11:45:40 +00008097 case UO_Real:
8098 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008099 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008100 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008101 if (Input.isInvalid()) return ExprError();
8102 if (Input.get()->getValueKind() != VK_RValue &&
8103 Input.get()->getObjectKind() == OK_Ordinary)
8104 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008105 break;
John McCalle3027922010-08-25 11:45:40 +00008106 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008107 resultType = Input.get()->getType();
8108 VK = Input.get()->getValueKind();
8109 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008110 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008111 }
John Wiegley01296292011-04-08 18:41:53 +00008112 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008113 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008114
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008115 // Check for array bounds violations in the operand of the UnaryOperator,
8116 // except for the '*' and '&' operators that have to be handled specially
8117 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8118 // that are explicitly defined as valid by the standard).
8119 if (Opc != UO_AddrOf && Opc != UO_Deref)
8120 CheckArrayAccess(Input.get());
8121
John Wiegley01296292011-04-08 18:41:53 +00008122 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008123 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008124}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008125
John McCalldadc5752010-08-24 06:29:42 +00008126ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008127 UnaryOperatorKind Opc,
8128 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008129 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008130 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008131 // Find all of the overloaded operators visible from this
8132 // point. We perform both an operator-name lookup from the local
8133 // scope and an argument-dependent lookup based on the types of
8134 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008135 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008136 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008137 if (S && OverOp != OO_None)
8138 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8139 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008140
John McCallb268a282010-08-23 23:25:46 +00008141 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008142 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008143
John McCallb268a282010-08-23 23:25:46 +00008144 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008145}
8146
Douglas Gregor5287f092009-11-05 00:51:44 +00008147// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008148ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008149 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008150 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008151}
8152
Steve Naroff66356bd2007-09-16 14:56:35 +00008153/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008154ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008155 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008156 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008157 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008158 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008159 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008160}
8161
John McCall31168b02011-06-15 23:02:42 +00008162/// Given the last statement in a statement-expression, check whether
8163/// the result is a producing expression (like a call to an
8164/// ns_returns_retained function) and, if so, rebuild it to hoist the
8165/// release out of the full-expression. Otherwise, return null.
8166/// Cannot fail.
8167static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8168 // Should always be wrapped with one of these.
8169 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8170 if (!cleanups) return 0;
8171
8172 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8173 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8174 return 0;
8175
8176 // Splice out the cast. This shouldn't modify any interesting
8177 // features of the statement.
8178 Expr *producer = cast->getSubExpr();
8179 assert(producer->getType() == cast->getType());
8180 assert(producer->getValueKind() == cast->getValueKind());
8181 cleanups->setSubExpr(producer);
8182 return cleanups;
8183}
8184
John McCalldadc5752010-08-24 06:29:42 +00008185ExprResult
John McCallb268a282010-08-23 23:25:46 +00008186Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008187 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008188 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8189 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8190
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008191 bool isFileScope
8192 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008193 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008194 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008195
Chris Lattner366727f2007-07-24 16:58:17 +00008196 // FIXME: there are a variety of strange constraints to enforce here, for
8197 // example, it is not possible to goto into a stmt expression apparently.
8198 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008199
Chris Lattner366727f2007-07-24 16:58:17 +00008200 // If there are sub stmts in the compound stmt, take the type of the last one
8201 // as the type of the stmtexpr.
8202 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008203 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008204 if (!Compound->body_empty()) {
8205 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008206 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008207 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008208 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8209 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008210 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008211 }
John McCall31168b02011-06-15 23:02:42 +00008212
John Wiegley01296292011-04-08 18:41:53 +00008213 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008214 // Do function/array conversion on the last expression, but not
8215 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008216 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8217 if (LastExpr.isInvalid())
8218 return ExprError();
8219 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008220
John Wiegley01296292011-04-08 18:41:53 +00008221 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008222 // In ARC, if the final expression ends in a consume, splice
8223 // the consume out and bind it later. In the alternate case
8224 // (when dealing with a retainable type), the result
8225 // initialization will create a produce. In both cases the
8226 // result will be +1, and we'll need to balance that out with
8227 // a bind.
8228 if (Expr *rebuiltLastStmt
8229 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8230 LastExpr = rebuiltLastStmt;
8231 } else {
8232 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008233 InitializedEntity::InitializeResult(LPLoc,
8234 Ty,
8235 false),
8236 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008237 LastExpr);
8238 }
8239
John Wiegley01296292011-04-08 18:41:53 +00008240 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008241 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008242 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008243 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008244 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008245 else
John Wiegley01296292011-04-08 18:41:53 +00008246 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008247 StmtExprMayBindToTemp = true;
8248 }
8249 }
8250 }
Chris Lattner944d3062008-07-26 19:51:01 +00008251 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008252
Eli Friedmanba961a92009-03-23 00:24:07 +00008253 // FIXME: Check that expression type is complete/non-abstract; statement
8254 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008255 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8256 if (StmtExprMayBindToTemp)
8257 return MaybeBindToTemporary(ResStmtExpr);
8258 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008259}
Steve Naroff78864672007-08-01 22:05:33 +00008260
John McCalldadc5752010-08-24 06:29:42 +00008261ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008262 TypeSourceInfo *TInfo,
8263 OffsetOfComponent *CompPtr,
8264 unsigned NumComponents,
8265 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008266 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008267 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008268 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008269
Chris Lattnerf17bd422007-08-30 17:45:32 +00008270 // We must have at least one component that refers to the type, and the first
8271 // one is known to be a field designator. Verify that the ArgTy represents
8272 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008273 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008274 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8275 << ArgTy << TypeRange);
8276
8277 // Type must be complete per C99 7.17p3 because a declaring a variable
8278 // with an incomplete type would be ill-formed.
8279 if (!Dependent
8280 && RequireCompleteType(BuiltinLoc, ArgTy,
8281 PDiag(diag::err_offsetof_incomplete_type)
8282 << TypeRange))
8283 return ExprError();
8284
Chris Lattner78502cf2007-08-31 21:49:13 +00008285 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8286 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008287 // FIXME: This diagnostic isn't actually visible because the location is in
8288 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008289 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008290 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8291 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008292
8293 bool DidWarnAboutNonPOD = false;
8294 QualType CurrentType = ArgTy;
8295 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008296 SmallVector<OffsetOfNode, 4> Comps;
8297 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008298 for (unsigned i = 0; i != NumComponents; ++i) {
8299 const OffsetOfComponent &OC = CompPtr[i];
8300 if (OC.isBrackets) {
8301 // Offset of an array sub-field. TODO: Should we allow vector elements?
8302 if (!CurrentType->isDependentType()) {
8303 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8304 if(!AT)
8305 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8306 << CurrentType);
8307 CurrentType = AT->getElementType();
8308 } else
8309 CurrentType = Context.DependentTy;
8310
8311 // The expression must be an integral expression.
8312 // FIXME: An integral constant expression?
8313 Expr *Idx = static_cast<Expr*>(OC.U.E);
8314 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8315 !Idx->getType()->isIntegerType())
8316 return ExprError(Diag(Idx->getLocStart(),
8317 diag::err_typecheck_subscript_not_integer)
8318 << Idx->getSourceRange());
8319
8320 // Record this array index.
8321 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8322 Exprs.push_back(Idx);
8323 continue;
8324 }
8325
8326 // Offset of a field.
8327 if (CurrentType->isDependentType()) {
8328 // We have the offset of a field, but we can't look into the dependent
8329 // type. Just record the identifier of the field.
8330 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8331 CurrentType = Context.DependentTy;
8332 continue;
8333 }
8334
8335 // We need to have a complete type to look into.
8336 if (RequireCompleteType(OC.LocStart, CurrentType,
8337 diag::err_offsetof_incomplete_type))
8338 return ExprError();
8339
8340 // Look for the designated field.
8341 const RecordType *RC = CurrentType->getAs<RecordType>();
8342 if (!RC)
8343 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8344 << CurrentType);
8345 RecordDecl *RD = RC->getDecl();
8346
8347 // C++ [lib.support.types]p5:
8348 // The macro offsetof accepts a restricted set of type arguments in this
8349 // International Standard. type shall be a POD structure or a POD union
8350 // (clause 9).
8351 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8352 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008353 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008354 PDiag(diag::warn_offsetof_non_pod_type)
8355 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8356 << CurrentType))
8357 DidWarnAboutNonPOD = true;
8358 }
8359
8360 // Look for the field.
8361 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8362 LookupQualifiedName(R, RD);
8363 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008364 IndirectFieldDecl *IndirectMemberDecl = 0;
8365 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008366 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008367 MemberDecl = IndirectMemberDecl->getAnonField();
8368 }
8369
Douglas Gregor882211c2010-04-28 22:16:22 +00008370 if (!MemberDecl)
8371 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8372 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8373 OC.LocEnd));
8374
Douglas Gregor10982ea2010-04-28 22:36:06 +00008375 // C99 7.17p3:
8376 // (If the specified member is a bit-field, the behavior is undefined.)
8377 //
8378 // We diagnose this as an error.
8379 if (MemberDecl->getBitWidth()) {
8380 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8381 << MemberDecl->getDeclName()
8382 << SourceRange(BuiltinLoc, RParenLoc);
8383 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8384 return ExprError();
8385 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008386
8387 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008388 if (IndirectMemberDecl)
8389 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008390
Douglas Gregord1702062010-04-29 00:18:15 +00008391 // If the member was found in a base class, introduce OffsetOfNodes for
8392 // the base class indirections.
8393 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8394 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008395 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008396 CXXBasePath &Path = Paths.front();
8397 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8398 B != BEnd; ++B)
8399 Comps.push_back(OffsetOfNode(B->Base));
8400 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008401
Francois Pichet783dd6e2010-11-21 06:08:52 +00008402 if (IndirectMemberDecl) {
8403 for (IndirectFieldDecl::chain_iterator FI =
8404 IndirectMemberDecl->chain_begin(),
8405 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8406 assert(isa<FieldDecl>(*FI));
8407 Comps.push_back(OffsetOfNode(OC.LocStart,
8408 cast<FieldDecl>(*FI), OC.LocEnd));
8409 }
8410 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008411 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008412
Douglas Gregor882211c2010-04-28 22:16:22 +00008413 CurrentType = MemberDecl->getType().getNonReferenceType();
8414 }
8415
8416 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8417 TInfo, Comps.data(), Comps.size(),
8418 Exprs.data(), Exprs.size(), RParenLoc));
8419}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008420
John McCalldadc5752010-08-24 06:29:42 +00008421ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008422 SourceLocation BuiltinLoc,
8423 SourceLocation TypeLoc,
8424 ParsedType argty,
8425 OffsetOfComponent *CompPtr,
8426 unsigned NumComponents,
8427 SourceLocation RPLoc) {
8428
Douglas Gregor882211c2010-04-28 22:16:22 +00008429 TypeSourceInfo *ArgTInfo;
8430 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8431 if (ArgTy.isNull())
8432 return ExprError();
8433
Eli Friedman06dcfd92010-08-05 10:15:45 +00008434 if (!ArgTInfo)
8435 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8436
8437 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8438 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008439}
8440
8441
John McCalldadc5752010-08-24 06:29:42 +00008442ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008443 Expr *CondExpr,
8444 Expr *LHSExpr, Expr *RHSExpr,
8445 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008446 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8447
John McCall7decc9e2010-11-18 06:31:45 +00008448 ExprValueKind VK = VK_RValue;
8449 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008450 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008451 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008452 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008453 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008454 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008455 } else {
8456 // The conditional expression is required to be a constant expression.
8457 llvm::APSInt condEval(32);
8458 SourceLocation ExpLoc;
8459 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008460 return ExprError(Diag(ExpLoc,
8461 diag::err_typecheck_choose_expr_requires_constant)
8462 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008463
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008464 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008465 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8466
8467 resType = ActiveExpr->getType();
8468 ValueDependent = ActiveExpr->isValueDependent();
8469 VK = ActiveExpr->getValueKind();
8470 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008471 }
8472
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008473 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008474 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008475 resType->isDependentType(),
8476 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008477}
8478
Steve Naroffc540d662008-09-03 18:15:37 +00008479//===----------------------------------------------------------------------===//
8480// Clang Extensions.
8481//===----------------------------------------------------------------------===//
8482
8483/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008484void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008485 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8486 PushBlockScope(BlockScope, Block);
8487 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008488 if (BlockScope)
8489 PushDeclContext(BlockScope, Block);
8490 else
8491 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008492}
8493
Mike Stump82f071f2009-02-04 22:31:32 +00008494void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008495 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008496 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008497 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008498
John McCall8cb7bdf2010-06-04 23:28:52 +00008499 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008500 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008501
John McCall3882ace2011-01-05 12:14:39 +00008502 // GetTypeForDeclarator always produces a function type for a block
8503 // literal signature. Furthermore, it is always a FunctionProtoType
8504 // unless the function was written with a typedef.
8505 assert(T->isFunctionType() &&
8506 "GetTypeForDeclarator made a non-function block signature");
8507
8508 // Look for an explicit signature in that function type.
8509 FunctionProtoTypeLoc ExplicitSignature;
8510
8511 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8512 if (isa<FunctionProtoTypeLoc>(tmp)) {
8513 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8514
8515 // Check whether that explicit signature was synthesized by
8516 // GetTypeForDeclarator. If so, don't save that as part of the
8517 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008518 if (ExplicitSignature.getLocalRangeBegin() ==
8519 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008520 // This would be much cheaper if we stored TypeLocs instead of
8521 // TypeSourceInfos.
8522 TypeLoc Result = ExplicitSignature.getResultLoc();
8523 unsigned Size = Result.getFullDataSize();
8524 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8525 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8526
8527 ExplicitSignature = FunctionProtoTypeLoc();
8528 }
John McCalla3ccba02010-06-04 11:21:44 +00008529 }
Mike Stump11289f42009-09-09 15:08:12 +00008530
John McCall3882ace2011-01-05 12:14:39 +00008531 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8532 CurBlock->FunctionType = T;
8533
8534 const FunctionType *Fn = T->getAs<FunctionType>();
8535 QualType RetTy = Fn->getResultType();
8536 bool isVariadic =
8537 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8538
John McCall8e346702010-06-04 19:02:56 +00008539 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008540
John McCalla3ccba02010-06-04 11:21:44 +00008541 // Don't allow returning a objc interface by value.
8542 if (RetTy->isObjCObjectType()) {
8543 Diag(ParamInfo.getSourceRange().getBegin(),
8544 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8545 return;
8546 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008547
John McCalla3ccba02010-06-04 11:21:44 +00008548 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008549 // return type. TODO: what should we do with declarators like:
8550 // ^ * { ... }
8551 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008552 if (RetTy != Context.DependentTy)
8553 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008554
John McCalla3ccba02010-06-04 11:21:44 +00008555 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008556 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008557 if (ExplicitSignature) {
8558 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8559 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008560 if (Param->getIdentifier() == 0 &&
8561 !Param->isImplicit() &&
8562 !Param->isInvalidDecl() &&
8563 !getLangOptions().CPlusPlus)
8564 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008565 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008566 }
John McCalla3ccba02010-06-04 11:21:44 +00008567
8568 // Fake up parameter variables if we have a typedef, like
8569 // ^ fntype { ... }
8570 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8571 for (FunctionProtoType::arg_type_iterator
8572 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8573 ParmVarDecl *Param =
8574 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8575 ParamInfo.getSourceRange().getBegin(),
8576 *I);
John McCall8e346702010-06-04 19:02:56 +00008577 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008578 }
Steve Naroffc540d662008-09-03 18:15:37 +00008579 }
John McCalla3ccba02010-06-04 11:21:44 +00008580
John McCall8e346702010-06-04 19:02:56 +00008581 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008582 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008583 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008584 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8585 CurBlock->TheDecl->param_end(),
8586 /*CheckParameterNames=*/false);
8587 }
8588
John McCalla3ccba02010-06-04 11:21:44 +00008589 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008590 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008591
John McCall8e346702010-06-04 19:02:56 +00008592 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008593 Diag(ParamInfo.getAttributes()->getLoc(),
8594 diag::warn_attribute_sentinel_not_variadic) << 1;
8595 // FIXME: remove the attribute.
8596 }
8597
8598 // Put the parameter variables in scope. We can bail out immediately
8599 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008600 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008601 return;
8602
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008603 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008604 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8605 (*AI)->setOwningFunction(CurBlock->TheDecl);
8606
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008607 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008608 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008609 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008610
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008611 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008612 }
John McCallf7b2fb52010-01-22 00:28:27 +00008613 }
Steve Naroffc540d662008-09-03 18:15:37 +00008614}
8615
8616/// ActOnBlockError - If there is an error parsing a block, this callback
8617/// is invoked to pop the information about the block from the action impl.
8618void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008619 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008620 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008621 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008622}
8623
8624/// ActOnBlockStmtExpr - This is called when the body of a block statement
8625/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008626ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008627 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008628 // If blocks are disabled, emit an error.
8629 if (!LangOpts.Blocks)
8630 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008631
Douglas Gregor9a28e842010-03-01 23:15:13 +00008632 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008633
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008634 PopDeclContext();
8635
Steve Naroffc540d662008-09-03 18:15:37 +00008636 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008637 if (!BSI->ReturnType.isNull())
8638 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008639
Mike Stump3bf1ab42009-07-28 22:04:01 +00008640 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008641 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008642
John McCallc63de662011-02-02 13:00:07 +00008643 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008644 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8645 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008646
John McCall8e346702010-06-04 19:02:56 +00008647 // If the user wrote a function type in some form, try to use that.
8648 if (!BSI->FunctionType.isNull()) {
8649 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8650
8651 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8652 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8653
8654 // Turn protoless block types into nullary block types.
8655 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008656 FunctionProtoType::ExtProtoInfo EPI;
8657 EPI.ExtInfo = Ext;
8658 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008659
8660 // Otherwise, if we don't need to change anything about the function type,
8661 // preserve its sugar structure.
8662 } else if (FTy->getResultType() == RetTy &&
8663 (!NoReturn || FTy->getNoReturnAttr())) {
8664 BlockTy = BSI->FunctionType;
8665
8666 // Otherwise, make the minimal modifications to the function type.
8667 } else {
8668 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008669 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8670 EPI.TypeQuals = 0; // FIXME: silently?
8671 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008672 BlockTy = Context.getFunctionType(RetTy,
8673 FPT->arg_type_begin(),
8674 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008675 EPI);
John McCall8e346702010-06-04 19:02:56 +00008676 }
8677
8678 // If we don't have a function type, just build one from nothing.
8679 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008680 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008681 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008682 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008683 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008684
John McCall8e346702010-06-04 19:02:56 +00008685 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8686 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008687 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008688
Chris Lattner45542ea2009-04-19 05:28:12 +00008689 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008690 if (getCurFunction()->NeedsScopeChecking() &&
8691 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008692 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008693
Chris Lattner60f84492011-02-17 23:58:47 +00008694 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008695
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008696 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8697 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8698 const VarDecl *variable = ci->getVariable();
8699 QualType T = variable->getType();
8700 QualType::DestructionKind destructKind = T.isDestructedType();
8701 if (destructKind != QualType::DK_none)
8702 getCurFunction()->setHasBranchProtectedScope();
8703 }
8704
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008705 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8706 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8707 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8708
Douglas Gregor9a28e842010-03-01 23:15:13 +00008709 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008710}
8711
John McCalldadc5752010-08-24 06:29:42 +00008712ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008713 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008714 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008715 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008716 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008717 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008718}
8719
John McCalldadc5752010-08-24 06:29:42 +00008720ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008721 Expr *E, TypeSourceInfo *TInfo,
8722 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008723 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008724
Eli Friedman121ba0c2008-08-09 23:32:40 +00008725 // Get the va_list type
8726 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008727 if (VaListType->isArrayType()) {
8728 // Deal with implicit array decay; for example, on x86-64,
8729 // va_list is an array, but it's supposed to decay to
8730 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008731 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008732 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008733 ExprResult Result = UsualUnaryConversions(E);
8734 if (Result.isInvalid())
8735 return ExprError();
8736 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008737 } else {
8738 // Otherwise, the va_list argument must be an l-value because
8739 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008740 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008741 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008742 return ExprError();
8743 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008744
Douglas Gregorad3150c2009-05-19 23:10:31 +00008745 if (!E->isTypeDependent() &&
8746 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008747 return ExprError(Diag(E->getLocStart(),
8748 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008749 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008750 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008751
David Majnemerc75d1a12011-06-14 05:17:32 +00008752 if (!TInfo->getType()->isDependentType()) {
8753 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8754 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8755 << TInfo->getTypeLoc().getSourceRange()))
8756 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008757
David Majnemerc75d1a12011-06-14 05:17:32 +00008758 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8759 TInfo->getType(),
8760 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8761 << TInfo->getTypeLoc().getSourceRange()))
8762 return ExprError();
8763
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008764 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008765 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008766 TInfo->getType()->isObjCLifetimeType()
8767 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8768 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008769 << TInfo->getType()
8770 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008771 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008772
8773 // Check for va_arg where arguments of the given type will be promoted
8774 // (i.e. this va_arg is guaranteed to have undefined behavior).
8775 QualType PromoteType;
8776 if (TInfo->getType()->isPromotableIntegerType()) {
8777 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8778 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8779 PromoteType = QualType();
8780 }
8781 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8782 PromoteType = Context.DoubleTy;
8783 if (!PromoteType.isNull())
8784 Diag(TInfo->getTypeLoc().getBeginLoc(),
8785 diag::warn_second_parameter_to_va_arg_never_compatible)
8786 << TInfo->getType()
8787 << PromoteType
8788 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008789 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008790
Abramo Bagnara27db2392010-08-10 10:06:15 +00008791 QualType T = TInfo->getType().getNonLValueExprType(Context);
8792 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008793}
8794
John McCalldadc5752010-08-24 06:29:42 +00008795ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008796 // The type of __null will be int or long, depending on the size of
8797 // pointers on the target.
8798 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008799 unsigned pw = Context.Target.getPointerWidth(0);
8800 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008801 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008802 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008803 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008804 else if (pw == Context.Target.getLongLongWidth())
8805 Ty = Context.LongLongTy;
8806 else {
8807 assert(!"I don't know size of pointer!");
8808 Ty = Context.IntTy;
8809 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008810
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008811 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008812}
8813
Alexis Huntc46382e2010-04-28 23:02:27 +00008814static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008815 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008816 if (!SemaRef.getLangOptions().ObjC1)
8817 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008818
Anders Carlssonace5d072009-11-10 04:46:30 +00008819 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8820 if (!PT)
8821 return;
8822
8823 // Check if the destination is of type 'id'.
8824 if (!PT->isObjCIdType()) {
8825 // Check if the destination is the 'NSString' interface.
8826 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8827 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8828 return;
8829 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008830
Anders Carlssonace5d072009-11-10 04:46:30 +00008831 // Strip off any parens and casts.
8832 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008833 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008834 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008835
Douglas Gregora771f462010-03-31 17:46:05 +00008836 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008837}
8838
Chris Lattner9bad62c2008-01-04 18:04:52 +00008839bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8840 SourceLocation Loc,
8841 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008842 Expr *SrcExpr, AssignmentAction Action,
8843 bool *Complained) {
8844 if (Complained)
8845 *Complained = false;
8846
Chris Lattner9bad62c2008-01-04 18:04:52 +00008847 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008848 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008849 bool isInvalid = false;
8850 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008851 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008852 ConversionFixItGenerator ConvHints;
8853 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008854
Chris Lattner9bad62c2008-01-04 18:04:52 +00008855 switch (ConvTy) {
8856 default: assert(0 && "Unknown conversion type");
8857 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008858 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008859 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008860 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8861 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008862 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008863 case IntToPointer:
8864 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008865 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8866 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008867 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008868 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008869 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008870 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008871 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8872 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008873 if (Hint.isNull() && !CheckInferredResultType) {
8874 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8875 }
8876 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008877 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008878 case IncompatiblePointerSign:
8879 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8880 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008881 case FunctionVoidPointer:
8882 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8883 break;
John McCall4fff8f62011-02-01 00:10:29 +00008884 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008885 // Perform array-to-pointer decay if necessary.
8886 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8887
John McCall4fff8f62011-02-01 00:10:29 +00008888 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8889 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8890 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8891 DiagKind = diag::err_typecheck_incompatible_address_space;
8892 break;
John McCall31168b02011-06-15 23:02:42 +00008893
8894
8895 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008896 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008897 break;
John McCall4fff8f62011-02-01 00:10:29 +00008898 }
8899
8900 llvm_unreachable("unknown error case for discarding qualifiers!");
8901 // fallthrough
8902 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008903 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008904 // If the qualifiers lost were because we were applying the
8905 // (deprecated) C++ conversion from a string literal to a char*
8906 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8907 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008908 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008909 // bit of refactoring (so that the second argument is an
8910 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008911 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008912 // C++ semantics.
8913 if (getLangOptions().CPlusPlus &&
8914 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8915 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008916 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8917 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008918 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008919 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008920 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008921 case IntToBlockPointer:
8922 DiagKind = diag::err_int_to_block_pointer;
8923 break;
8924 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008925 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008926 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008927 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008928 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008929 // it can give a more specific diagnostic.
8930 DiagKind = diag::warn_incompatible_qualified_id;
8931 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008932 case IncompatibleVectors:
8933 DiagKind = diag::warn_incompatible_vectors;
8934 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008935 case IncompatibleObjCWeakRef:
8936 DiagKind = diag::err_arc_weak_unavailable_assign;
8937 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008938 case Incompatible:
8939 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008940 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8941 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008942 isInvalid = true;
8943 break;
8944 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008945
Douglas Gregorc68e1402010-04-09 00:35:39 +00008946 QualType FirstType, SecondType;
8947 switch (Action) {
8948 case AA_Assigning:
8949 case AA_Initializing:
8950 // The destination type comes first.
8951 FirstType = DstType;
8952 SecondType = SrcType;
8953 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008954
Douglas Gregorc68e1402010-04-09 00:35:39 +00008955 case AA_Returning:
8956 case AA_Passing:
8957 case AA_Converting:
8958 case AA_Sending:
8959 case AA_Casting:
8960 // The source type comes first.
8961 FirstType = SrcType;
8962 SecondType = DstType;
8963 break;
8964 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008965
Anna Zaks3b402712011-07-28 19:51:27 +00008966 PartialDiagnostic FDiag = PDiag(DiagKind);
8967 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8968
8969 // If we can fix the conversion, suggest the FixIts.
8970 assert(ConvHints.isNull() || Hint.isNull());
8971 if (!ConvHints.isNull()) {
8972 for (llvm::SmallVector<FixItHint, 1>::iterator
8973 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8974 HI != HE; ++HI)
8975 FDiag << *HI;
8976 } else {
8977 FDiag << Hint;
8978 }
8979 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8980
8981 Diag(Loc, FDiag);
8982
Douglas Gregor33823722011-06-11 01:09:30 +00008983 if (CheckInferredResultType)
8984 EmitRelatedResultTypeNote(SrcExpr);
8985
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008986 if (Complained)
8987 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008988 return isInvalid;
8989}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008990
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008991bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008992 llvm::APSInt ICEResult;
8993 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8994 if (Result)
8995 *Result = ICEResult;
8996 return false;
8997 }
8998
Anders Carlssone54e8a12008-11-30 19:50:32 +00008999 Expr::EvalResult EvalResult;
9000
Mike Stump4e1f26a2009-02-19 03:04:26 +00009001 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009002 EvalResult.HasSideEffects) {
9003 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9004
9005 if (EvalResult.Diag) {
9006 // We only show the note if it's not the usual "invalid subexpression"
9007 // or if it's actually in a subexpression.
9008 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9009 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9010 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9011 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009012
Anders Carlssone54e8a12008-11-30 19:50:32 +00009013 return true;
9014 }
9015
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009016 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9017 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009018
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009019 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009020 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9021 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009022 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009023
Anders Carlssone54e8a12008-11-30 19:50:32 +00009024 if (Result)
9025 *Result = EvalResult.Val.getInt();
9026 return false;
9027}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009028
Douglas Gregorff790f12009-11-26 00:44:06 +00009029void
Mike Stump11289f42009-09-09 15:08:12 +00009030Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009031 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009032 ExpressionEvaluationContextRecord(NewContext,
9033 ExprTemporaries.size(),
9034 ExprNeedsCleanups));
9035 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009036}
9037
Richard Trieucfc491d2011-08-02 04:35:43 +00009038void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009039 // Pop the current expression evaluation context off the stack.
9040 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9041 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009042
Douglas Gregorfab31f42009-12-12 07:57:52 +00009043 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9044 if (Rec.PotentiallyReferenced) {
9045 // Mark any remaining declarations in the current position of the stack
9046 // as "referenced". If they were not meant to be referenced, semantic
9047 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009048 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009049 I = Rec.PotentiallyReferenced->begin(),
9050 IEnd = Rec.PotentiallyReferenced->end();
9051 I != IEnd; ++I)
9052 MarkDeclarationReferenced(I->first, I->second);
9053 }
9054
9055 if (Rec.PotentiallyDiagnosed) {
9056 // Emit any pending diagnostics.
9057 for (PotentiallyEmittedDiagnostics::iterator
9058 I = Rec.PotentiallyDiagnosed->begin(),
9059 IEnd = Rec.PotentiallyDiagnosed->end();
9060 I != IEnd; ++I)
9061 Diag(I->first, I->second);
9062 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009063 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009064
9065 // When are coming out of an unevaluated context, clear out any
9066 // temporaries that we may have created as part of the evaluation of
9067 // the expression in that context: they aren't relevant because they
9068 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009069 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009070 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9071 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009072 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9073
9074 // Otherwise, merge the contexts together.
9075 } else {
9076 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9077 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009078
9079 // Destroy the popped expression evaluation record.
9080 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009081}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009082
John McCall31168b02011-06-15 23:02:42 +00009083void Sema::DiscardCleanupsInEvaluationContext() {
9084 ExprTemporaries.erase(
9085 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9086 ExprTemporaries.end());
9087 ExprNeedsCleanups = false;
9088}
9089
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009090/// \brief Note that the given declaration was referenced in the source code.
9091///
9092/// This routine should be invoke whenever a given declaration is referenced
9093/// in the source code, and where that reference occurred. If this declaration
9094/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9095/// C99 6.9p3), then the declaration will be marked as used.
9096///
9097/// \param Loc the location where the declaration was referenced.
9098///
9099/// \param D the declaration that has been referenced by the source code.
9100void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9101 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009102
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009103 D->setReferenced();
9104
Douglas Gregorebada0772010-06-17 23:14:26 +00009105 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009106 return;
Mike Stump11289f42009-09-09 15:08:12 +00009107
Richard Trieucfc491d2011-08-02 04:35:43 +00009108 // Mark a parameter or variable declaration "used", regardless of whether
9109 // we're in a template or not. The reason for this is that unevaluated
9110 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9111 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009112 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009113 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009114 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009115 return;
9116 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009117
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009118 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9119 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009120
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009121 // Do not mark anything as "used" within a dependent context; wait for
9122 // an instantiation.
9123 if (CurContext->isDependentContext())
9124 return;
Mike Stump11289f42009-09-09 15:08:12 +00009125
Douglas Gregorff790f12009-11-26 00:44:06 +00009126 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009127 case Unevaluated:
9128 // We are in an expression that is not potentially evaluated; do nothing.
9129 return;
Mike Stump11289f42009-09-09 15:08:12 +00009130
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009131 case PotentiallyEvaluated:
9132 // We are in a potentially-evaluated expression, so this declaration is
9133 // "used"; handle this below.
9134 break;
Mike Stump11289f42009-09-09 15:08:12 +00009135
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009136 case PotentiallyPotentiallyEvaluated:
9137 // We are in an expression that may be potentially evaluated; queue this
9138 // declaration reference until we know whether the expression is
9139 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009140 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009141 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009142
9143 case PotentiallyEvaluatedIfUsed:
9144 // Referenced declarations will only be used if the construct in the
9145 // containing expression is used.
9146 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009147 }
Mike Stump11289f42009-09-09 15:08:12 +00009148
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009149 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009150 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009151 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9152 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00009153 return;
9154 if (!Constructor->isUsed(false))
9155 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00009156 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00009157 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009158 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009159 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009160 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009161
Douglas Gregor88d292c2010-05-13 16:44:06 +00009162 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009163 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009164 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009165 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009166 if (Destructor->isVirtual())
9167 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009168 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009169 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009170 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009171 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009172 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009173 } else if (MethodDecl->isVirtual())
9174 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009175 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009176 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009177 // Recursive functions should be marked when used from another function.
9178 if (CurContext == Function) return;
9179
Mike Stump11289f42009-09-09 15:08:12 +00009180 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009181 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009182 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009183 bool AlreadyInstantiated = false;
9184 if (FunctionTemplateSpecializationInfo *SpecInfo
9185 = Function->getTemplateSpecializationInfo()) {
9186 if (SpecInfo->getPointOfInstantiation().isInvalid())
9187 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009188 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009189 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009190 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009191 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009192 = Function->getMemberSpecializationInfo()) {
9193 if (MSInfo->getPointOfInstantiation().isInvalid())
9194 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009195 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009196 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009197 AlreadyInstantiated = true;
9198 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009199
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009200 if (!AlreadyInstantiated) {
9201 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9202 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9203 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9204 Loc));
9205 else
Chandler Carruth54080172010-08-25 08:44:16 +00009206 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009207 }
John McCall83779672011-02-19 02:53:41 +00009208 } else {
9209 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009210 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9211 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009212 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009213 MarkDeclarationReferenced(Loc, *i);
9214 }
John McCall83779672011-02-19 02:53:41 +00009215 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009216
John McCall83779672011-02-19 02:53:41 +00009217 // Keep track of used but undefined functions.
9218 if (!Function->isPure() && !Function->hasBody() &&
9219 Function->getLinkage() != ExternalLinkage) {
9220 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9221 if (old.isInvalid()) old = Loc;
9222 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009223
John McCall83779672011-02-19 02:53:41 +00009224 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009225 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009226 }
Mike Stump11289f42009-09-09 15:08:12 +00009227
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009228 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009229 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009230 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009231 Var->getInstantiatedFromStaticDataMember()) {
9232 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9233 assert(MSInfo && "Missing member specialization information?");
9234 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9235 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9236 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009237 // This is a modification of an existing AST node. Notify listeners.
9238 if (ASTMutationListener *L = getASTMutationListener())
9239 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009240 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009241 }
9242 }
Mike Stump11289f42009-09-09 15:08:12 +00009243
John McCall15dd4042011-02-21 19:25:48 +00009244 // Keep track of used but undefined variables. We make a hole in
9245 // the warning for static const data members with in-line
9246 // initializers.
John McCall83779672011-02-19 02:53:41 +00009247 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009248 && Var->getLinkage() != ExternalLinkage
9249 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009250 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9251 if (old.isInvalid()) old = Loc;
9252 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009253
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009254 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009255 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009256 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009257}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009258
Douglas Gregor5597ab42010-05-07 23:12:07 +00009259namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009260 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009261 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009262 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009263 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9264 Sema &S;
9265 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009266
Douglas Gregor5597ab42010-05-07 23:12:07 +00009267 public:
9268 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009269
Douglas Gregor5597ab42010-05-07 23:12:07 +00009270 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009271
9272 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9273 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009274 };
9275}
9276
Chandler Carruthaf80f662010-06-09 08:17:30 +00009277bool MarkReferencedDecls::TraverseTemplateArgument(
9278 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009279 if (Arg.getKind() == TemplateArgument::Declaration) {
9280 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9281 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009282
9283 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009284}
9285
Chandler Carruthaf80f662010-06-09 08:17:30 +00009286bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009287 if (ClassTemplateSpecializationDecl *Spec
9288 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9289 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009290 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009291 }
9292
Chandler Carruthc65667c2010-06-10 10:31:57 +00009293 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009294}
9295
9296void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9297 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009298 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009299}
9300
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009301namespace {
9302 /// \brief Helper class that marks all of the declarations referenced by
9303 /// potentially-evaluated subexpressions as "referenced".
9304 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9305 Sema &S;
9306
9307 public:
9308 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9309
9310 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9311
9312 void VisitDeclRefExpr(DeclRefExpr *E) {
9313 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9314 }
9315
9316 void VisitMemberExpr(MemberExpr *E) {
9317 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009318 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009319 }
9320
9321 void VisitCXXNewExpr(CXXNewExpr *E) {
9322 if (E->getConstructor())
9323 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9324 if (E->getOperatorNew())
9325 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9326 if (E->getOperatorDelete())
9327 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009328 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009329 }
9330
9331 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9332 if (E->getOperatorDelete())
9333 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009334 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9335 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9336 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9337 S.MarkDeclarationReferenced(E->getLocStart(),
9338 S.LookupDestructor(Record));
9339 }
9340
Douglas Gregor32b3de52010-09-11 23:32:50 +00009341 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009342 }
9343
9344 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9345 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009346 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009347 }
9348
9349 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9350 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9351 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009352
9353 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9354 Visit(E->getExpr());
9355 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009356 };
9357}
9358
9359/// \brief Mark any declarations that appear within this expression or any
9360/// potentially-evaluated subexpressions as "referenced".
9361void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9362 EvaluatedExprMarker(*this).Visit(E);
9363}
9364
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009365/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9366/// of the program being compiled.
9367///
9368/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009369/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009370/// possibility that the code will actually be executable. Code in sizeof()
9371/// expressions, code used only during overload resolution, etc., are not
9372/// potentially evaluated. This routine will suppress such diagnostics or,
9373/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009374/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009375/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009376///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009377/// This routine should be used for all diagnostics that describe the run-time
9378/// behavior of a program, such as passing a non-POD value through an ellipsis.
9379/// Failure to do so will likely result in spurious diagnostics or failures
9380/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009381bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009382 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009383 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009384 case Unevaluated:
9385 // The argument will never be evaluated, so don't complain.
9386 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009387
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009388 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009389 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009390 if (stmt && getCurFunctionOrMethodDecl()) {
9391 FunctionScopes.back()->PossiblyUnreachableDiags.
9392 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9393 }
9394 else
9395 Diag(Loc, PD);
9396
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009397 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009398
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009399 case PotentiallyPotentiallyEvaluated:
9400 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9401 break;
9402 }
9403
9404 return false;
9405}
9406
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009407bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9408 CallExpr *CE, FunctionDecl *FD) {
9409 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9410 return false;
9411
9412 PartialDiagnostic Note =
9413 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9414 << FD->getDeclName() : PDiag();
9415 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009416
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009417 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009418 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009419 PDiag(diag::err_call_function_incomplete_return)
9420 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009421 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009422 << CE->getSourceRange(),
9423 std::make_pair(NoteLoc, Note)))
9424 return true;
9425
9426 return false;
9427}
9428
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009429// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009430// will prevent this condition from triggering, which is what we want.
9431void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9432 SourceLocation Loc;
9433
John McCall0506e4a2009-11-11 02:41:58 +00009434 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009435 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009436
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009437 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009438 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009439 return;
9440
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009441 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9442
John McCallb0e419e2009-11-12 00:06:05 +00009443 // Greylist some idioms by putting them into a warning subcategory.
9444 if (ObjCMessageExpr *ME
9445 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9446 Selector Sel = ME->getSelector();
9447
John McCallb0e419e2009-11-12 00:06:05 +00009448 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009449 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009450 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9451
9452 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009453 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009454 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9455 }
John McCall0506e4a2009-11-11 02:41:58 +00009456
John McCalld5707ab2009-10-12 21:59:07 +00009457 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009458 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009459 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009460 return;
9461
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009462 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009463 Loc = Op->getOperatorLoc();
9464 } else {
9465 // Not an assignment.
9466 return;
9467 }
9468
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009469 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009470
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009471 SourceLocation Open = E->getSourceRange().getBegin();
9472 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9473 Diag(Loc, diag::note_condition_assign_silence)
9474 << FixItHint::CreateInsertion(Open, "(")
9475 << FixItHint::CreateInsertion(Close, ")");
9476
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009477 if (IsOrAssign)
9478 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9479 << FixItHint::CreateReplacement(Loc, "!=");
9480 else
9481 Diag(Loc, diag::note_condition_assign_to_comparison)
9482 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009483}
9484
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009485/// \brief Redundant parentheses over an equality comparison can indicate
9486/// that the user intended an assignment used as condition.
9487void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009488 // Don't warn if the parens came from a macro.
9489 SourceLocation parenLoc = parenE->getLocStart();
9490 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9491 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009492 // Don't warn for dependent expressions.
9493 if (parenE->isTypeDependent())
9494 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009495
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009496 Expr *E = parenE->IgnoreParens();
9497
9498 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009499 if (opE->getOpcode() == BO_EQ &&
9500 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9501 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009502 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009503
Ted Kremenekae022092011-02-02 02:20:30 +00009504 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009505 Diag(Loc, diag::note_equality_comparison_silence)
9506 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9507 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009508 Diag(Loc, diag::note_equality_comparison_to_assign)
9509 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009510 }
9511}
9512
John Wiegley01296292011-04-08 18:41:53 +00009513ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009514 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009515 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9516 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009517
John McCall0009fcc2011-04-26 20:42:42 +00009518 ExprResult result = CheckPlaceholderExpr(E);
9519 if (result.isInvalid()) return ExprError();
9520 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009521
John McCall0009fcc2011-04-26 20:42:42 +00009522 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009523 if (getLangOptions().CPlusPlus)
9524 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9525
John Wiegley01296292011-04-08 18:41:53 +00009526 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9527 if (ERes.isInvalid())
9528 return ExprError();
9529 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009530
9531 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009532 if (!T->isScalarType()) { // C99 6.8.4.1p1
9533 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9534 << T << E->getSourceRange();
9535 return ExprError();
9536 }
John McCalld5707ab2009-10-12 21:59:07 +00009537 }
9538
John Wiegley01296292011-04-08 18:41:53 +00009539 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009540}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009541
John McCalldadc5752010-08-24 06:29:42 +00009542ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9543 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009544 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009545 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009546
9547 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009548}
John McCall36e7fe32010-10-12 00:20:44 +00009549
John McCall31996342011-04-07 08:22:57 +00009550namespace {
John McCall2979fe02011-04-12 00:42:48 +00009551 /// A visitor for rebuilding a call to an __unknown_any expression
9552 /// to have an appropriate type.
9553 struct RebuildUnknownAnyFunction
9554 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9555
9556 Sema &S;
9557
9558 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9559
9560 ExprResult VisitStmt(Stmt *S) {
9561 llvm_unreachable("unexpected statement!");
9562 return ExprError();
9563 }
9564
9565 ExprResult VisitExpr(Expr *expr) {
9566 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9567 << expr->getSourceRange();
9568 return ExprError();
9569 }
9570
9571 /// Rebuild an expression which simply semantically wraps another
9572 /// expression which it shares the type and value kind of.
9573 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9574 ExprResult subResult = Visit(expr->getSubExpr());
9575 if (subResult.isInvalid()) return ExprError();
9576
9577 Expr *subExpr = subResult.take();
9578 expr->setSubExpr(subExpr);
9579 expr->setType(subExpr->getType());
9580 expr->setValueKind(subExpr->getValueKind());
9581 assert(expr->getObjectKind() == OK_Ordinary);
9582 return expr;
9583 }
9584
9585 ExprResult VisitParenExpr(ParenExpr *paren) {
9586 return rebuildSugarExpr(paren);
9587 }
9588
9589 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9590 return rebuildSugarExpr(op);
9591 }
9592
9593 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9594 ExprResult subResult = Visit(op->getSubExpr());
9595 if (subResult.isInvalid()) return ExprError();
9596
9597 Expr *subExpr = subResult.take();
9598 op->setSubExpr(subExpr);
9599 op->setType(S.Context.getPointerType(subExpr->getType()));
9600 assert(op->getValueKind() == VK_RValue);
9601 assert(op->getObjectKind() == OK_Ordinary);
9602 return op;
9603 }
9604
9605 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9606 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9607
9608 expr->setType(decl->getType());
9609
9610 assert(expr->getValueKind() == VK_RValue);
9611 if (S.getLangOptions().CPlusPlus &&
9612 !(isa<CXXMethodDecl>(decl) &&
9613 cast<CXXMethodDecl>(decl)->isInstance()))
9614 expr->setValueKind(VK_LValue);
9615
9616 return expr;
9617 }
9618
9619 ExprResult VisitMemberExpr(MemberExpr *mem) {
9620 return resolveDecl(mem, mem->getMemberDecl());
9621 }
9622
9623 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9624 return resolveDecl(ref, ref->getDecl());
9625 }
9626 };
9627}
9628
9629/// Given a function expression of unknown-any type, try to rebuild it
9630/// to have a function type.
9631static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9632 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9633 if (result.isInvalid()) return ExprError();
9634 return S.DefaultFunctionArrayConversion(result.take());
9635}
9636
9637namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009638 /// A visitor for rebuilding an expression of type __unknown_anytype
9639 /// into one which resolves the type directly on the referring
9640 /// expression. Strict preservation of the original source
9641 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009642 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009643 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009644
9645 Sema &S;
9646
9647 /// The current destination type.
9648 QualType DestType;
9649
9650 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9651 : S(S), DestType(castType) {}
9652
John McCall39439732011-04-09 22:50:59 +00009653 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009654 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009655 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009656 }
9657
John McCall2d2e8702011-04-11 07:02:50 +00009658 ExprResult VisitExpr(Expr *expr) {
9659 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9660 << expr->getSourceRange();
9661 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009662 }
9663
John McCall2d2e8702011-04-11 07:02:50 +00009664 ExprResult VisitCallExpr(CallExpr *call);
9665 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9666
John McCall39439732011-04-09 22:50:59 +00009667 /// Rebuild an expression which simply semantically wraps another
9668 /// expression which it shares the type and value kind of.
9669 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9670 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009671 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009672 Expr *subExpr = subResult.take();
9673 expr->setSubExpr(subExpr);
9674 expr->setType(subExpr->getType());
9675 expr->setValueKind(subExpr->getValueKind());
9676 assert(expr->getObjectKind() == OK_Ordinary);
9677 return expr;
9678 }
John McCall31996342011-04-07 08:22:57 +00009679
John McCall39439732011-04-09 22:50:59 +00009680 ExprResult VisitParenExpr(ParenExpr *paren) {
9681 return rebuildSugarExpr(paren);
9682 }
9683
9684 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9685 return rebuildSugarExpr(op);
9686 }
9687
John McCall2979fe02011-04-12 00:42:48 +00009688 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9689 const PointerType *ptr = DestType->getAs<PointerType>();
9690 if (!ptr) {
9691 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9692 << op->getSourceRange();
9693 return ExprError();
9694 }
9695 assert(op->getValueKind() == VK_RValue);
9696 assert(op->getObjectKind() == OK_Ordinary);
9697 op->setType(DestType);
9698
9699 // Build the sub-expression as if it were an object of the pointee type.
9700 DestType = ptr->getPointeeType();
9701 ExprResult subResult = Visit(op->getSubExpr());
9702 if (subResult.isInvalid()) return ExprError();
9703 op->setSubExpr(subResult.take());
9704 return op;
9705 }
9706
John McCall2d2e8702011-04-11 07:02:50 +00009707 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009708
John McCall2979fe02011-04-12 00:42:48 +00009709 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009710
John McCall2979fe02011-04-12 00:42:48 +00009711 ExprResult VisitMemberExpr(MemberExpr *mem) {
9712 return resolveDecl(mem, mem->getMemberDecl());
9713 }
John McCall39439732011-04-09 22:50:59 +00009714
9715 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009716 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009717 }
9718 };
9719}
9720
John McCall2d2e8702011-04-11 07:02:50 +00009721/// Rebuilds a call expression which yielded __unknown_anytype.
9722ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9723 Expr *callee = call->getCallee();
9724
9725 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009726 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009727 FK_FunctionPointer,
9728 FK_BlockPointer
9729 };
9730
9731 FnKind kind;
9732 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009733 if (type == S.Context.BoundMemberTy) {
9734 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9735 kind = FK_MemberFunction;
9736 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009737 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9738 type = ptr->getPointeeType();
9739 kind = FK_FunctionPointer;
9740 } else {
9741 type = type->castAs<BlockPointerType>()->getPointeeType();
9742 kind = FK_BlockPointer;
9743 }
9744 const FunctionType *fnType = type->castAs<FunctionType>();
9745
9746 // Verify that this is a legal result type of a function.
9747 if (DestType->isArrayType() || DestType->isFunctionType()) {
9748 unsigned diagID = diag::err_func_returning_array_function;
9749 if (kind == FK_BlockPointer)
9750 diagID = diag::err_block_returning_array_function;
9751
9752 S.Diag(call->getExprLoc(), diagID)
9753 << DestType->isFunctionType() << DestType;
9754 return ExprError();
9755 }
9756
9757 // Otherwise, go ahead and set DestType as the call's result.
9758 call->setType(DestType.getNonLValueExprType(S.Context));
9759 call->setValueKind(Expr::getValueKindForType(DestType));
9760 assert(call->getObjectKind() == OK_Ordinary);
9761
9762 // Rebuild the function type, replacing the result type with DestType.
9763 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9764 DestType = S.Context.getFunctionType(DestType,
9765 proto->arg_type_begin(),
9766 proto->getNumArgs(),
9767 proto->getExtProtoInfo());
9768 else
9769 DestType = S.Context.getFunctionNoProtoType(DestType,
9770 fnType->getExtInfo());
9771
9772 // Rebuild the appropriate pointer-to-function type.
9773 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009774 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009775 // Nothing to do.
9776 break;
9777
9778 case FK_FunctionPointer:
9779 DestType = S.Context.getPointerType(DestType);
9780 break;
9781
9782 case FK_BlockPointer:
9783 DestType = S.Context.getBlockPointerType(DestType);
9784 break;
9785 }
9786
9787 // Finally, we can recurse.
9788 ExprResult calleeResult = Visit(callee);
9789 if (!calleeResult.isUsable()) return ExprError();
9790 call->setCallee(calleeResult.take());
9791
9792 // Bind a temporary if necessary.
9793 return S.MaybeBindToTemporary(call);
9794}
9795
9796ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009797 // Verify that this is a legal result type of a call.
9798 if (DestType->isArrayType() || DestType->isFunctionType()) {
9799 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9800 << DestType->isFunctionType() << DestType;
9801 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009802 }
9803
John McCall3f4138c2011-07-13 17:56:40 +00009804 // Rewrite the method result type if available.
9805 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9806 assert(method->getResultType() == S.Context.UnknownAnyTy);
9807 method->setResultType(DestType);
9808 }
John McCall2979fe02011-04-12 00:42:48 +00009809
John McCall2d2e8702011-04-11 07:02:50 +00009810 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009811 msg->setType(DestType.getNonReferenceType());
9812 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009813
John McCall2979fe02011-04-12 00:42:48 +00009814 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009815}
9816
9817ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009818 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009819 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009820 assert(ice->getValueKind() == VK_RValue);
9821 assert(ice->getObjectKind() == OK_Ordinary);
9822
John McCall2979fe02011-04-12 00:42:48 +00009823 ice->setType(DestType);
9824
John McCall2d2e8702011-04-11 07:02:50 +00009825 // Rebuild the sub-expression as the pointee (function) type.
9826 DestType = DestType->castAs<PointerType>()->getPointeeType();
9827
9828 ExprResult result = Visit(ice->getSubExpr());
9829 if (!result.isUsable()) return ExprError();
9830
9831 ice->setSubExpr(result.take());
9832 return S.Owned(ice);
9833}
9834
John McCall2979fe02011-04-12 00:42:48 +00009835ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009836 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009837 QualType type = DestType;
9838
9839 // We know how to make this work for certain kinds of decls:
9840
9841 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009842 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall9a877fe2011-08-10 04:12:23 +00009843 if (const PointerType *ptr = type->getAs<PointerType>()) {
9844 DestType = ptr->getPointeeType();
9845 ExprResult result = resolveDecl(expr, decl);
9846 if (result.isInvalid()) return ExprError();
9847 return S.ImpCastExprToType(result.take(), type,
9848 CK_FunctionToPointerDecay, VK_RValue);
9849 }
9850
9851 if (!type->isFunctionType()) {
9852 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9853 << decl << expr->getSourceRange();
9854 return ExprError();
9855 }
John McCall2d2e8702011-04-11 07:02:50 +00009856
John McCall4adb38c2011-04-27 00:36:17 +00009857 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9858 if (method->isInstance()) {
9859 valueKind = VK_RValue;
9860 type = S.Context.BoundMemberTy;
9861 }
9862
John McCall2d2e8702011-04-11 07:02:50 +00009863 // Function references aren't l-values in C.
9864 if (!S.getLangOptions().CPlusPlus)
9865 valueKind = VK_RValue;
9866
9867 // - variables
9868 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009869 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9870 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009871 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009872 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9873 << decl << expr->getSourceRange();
9874 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009875 }
9876
9877 // - nothing else
9878 } else {
9879 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9880 << decl << expr->getSourceRange();
9881 return ExprError();
9882 }
9883
John McCall2979fe02011-04-12 00:42:48 +00009884 decl->setType(DestType);
9885 expr->setType(type);
9886 expr->setValueKind(valueKind);
9887 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009888}
9889
John McCall31996342011-04-07 08:22:57 +00009890/// Check a cast of an unknown-any type. We intentionally only
9891/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009892ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9893 Expr *castExpr, CastKind &castKind,
9894 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009895 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009896 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9897 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009898
John McCall39439732011-04-09 22:50:59 +00009899 castExpr = result.take();
9900 VK = castExpr->getValueKind();
9901 castKind = CK_NoOp;
9902
9903 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009904}
9905
9906static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9907 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009908 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009909 while (true) {
9910 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009911 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009912 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009913 diagID = diag::err_uncasted_call_of_unknown_any;
9914 } else {
John McCall31996342011-04-07 08:22:57 +00009915 break;
John McCall2d2e8702011-04-11 07:02:50 +00009916 }
John McCall31996342011-04-07 08:22:57 +00009917 }
9918
John McCall2d2e8702011-04-11 07:02:50 +00009919 SourceLocation loc;
9920 NamedDecl *d;
9921 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9922 loc = ref->getLocation();
9923 d = ref->getDecl();
9924 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9925 loc = mem->getMemberLoc();
9926 d = mem->getMemberDecl();
9927 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9928 diagID = diag::err_uncasted_call_of_unknown_any;
9929 loc = msg->getSelectorLoc();
9930 d = msg->getMethodDecl();
9931 assert(d && "unknown method returning __unknown_any?");
9932 } else {
9933 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9934 << e->getSourceRange();
9935 return ExprError();
9936 }
9937
9938 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009939
9940 // Never recoverable.
9941 return ExprError();
9942}
9943
John McCall36e7fe32010-10-12 00:20:44 +00009944/// Check for operands with placeholder types and complain if found.
9945/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009946ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009947 // Placeholder types are always *exactly* the appropriate builtin type.
9948 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009949
John McCall31996342011-04-07 08:22:57 +00009950 // Overloaded expressions.
9951 if (type == Context.OverloadTy)
9952 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009953 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009954 QualType(),
9955 diag::err_ovl_unresolvable);
9956
John McCall0009fcc2011-04-26 20:42:42 +00009957 // Bound member functions.
9958 if (type == Context.BoundMemberTy) {
9959 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9960 << E->getSourceRange();
9961 return ExprError();
9962 }
9963
John McCall31996342011-04-07 08:22:57 +00009964 // Expressions of unknown type.
9965 if (type == Context.UnknownAnyTy)
9966 return diagnoseUnknownAnyExpr(*this, E);
9967
9968 assert(!type->isPlaceholderType());
9969 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009970}
Richard Trieu2c850c02011-04-21 21:44:26 +00009971
9972bool Sema::CheckCaseExpression(Expr *expr) {
9973 if (expr->isTypeDependent())
9974 return true;
9975 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9976 return expr->getType()->isIntegralOrEnumerationType();
9977 return false;
9978}