blob: 65c12fe13a8cae1e1d3b272e5c1e2d90a1308d54 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000161
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000246 SourceLocation MissingNilLoc
247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
248 std::string NullValue;
249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition())
250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
253 else if (Context.getTypeSize(Context.IntTy)
254 == Context.getTypeSize(Context.getSizeType()))
255 NullValue = "0";
256 else
257 NullValue = "0L";
258
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << isMethod
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall7ddbcf42010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000263}
264
Douglas Gregor87f95b02009-02-26 21:00:50 +0000265SourceRange Sema::getExprRange(ExprTy *E) const {
266 Expr *Ex = (Expr *)E;
267 return Ex? Ex->getSourceRange() : SourceRange();
268}
269
Chris Lattner513165e2008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattner513165e2008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattner513165e2008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000282 else if (Ty->isArrayType()) {
283 // In C90 mode, arrays only promote to pointers if the array expression is
284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
285 // type 'array of type' is converted to an expression that has type 'pointer
286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
287 // that has type 'array of type' ...". The relevant change is "an lvalue"
288 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000289 //
290 // C++ 4.2p1:
291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
292 // T" can be converted to an rvalue of type "pointer to T".
293 //
John McCall086a4642010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000297 }
John Wiegley01296292011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000301static void CheckForNullPointerDereference(Sema &S, Expr *E) {
302 // Check to see if we are dereferencing a null pointer. If so,
303 // and if not volatile-qualified, this is undefined behavior that the
304 // optimizer will delete, so warn about it. People sometimes try to use this
305 // to get a deterministic trap and are surprised by clang's behavior. This
306 // only handles the pattern "*null", which is a very syntactic check.
307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
308 if (UO->getOpcode() == UO_Deref &&
309 UO->getSubExpr()->IgnoreParenCasts()->
310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
311 !UO->getType().isVolatileQualified()) {
312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
313 S.PDiag(diag::warn_indirection_through_null)
314 << UO->getSubExpr()->getSourceRange());
315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
316 S.PDiag(diag::note_indirection_through_null));
317 }
318}
319
John Wiegley01296292011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000321 // C++ [conv.lval]p1:
322 // A glvalue of a non-function, non-array type T can be
323 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000325
John McCall27584242010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000328
John McCall27584242010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000337 }
John McCall27584242010-12-06 20:48:59 +0000338
339 // We don't want to throw lvalue-to-rvalue casts on top of
340 // expressions of certain types in C++.
341 if (getLangOptions().CPlusPlus &&
342 (E->getType() == Context.OverloadTy ||
343 T->isDependentType() ||
344 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000345 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000346
347 // The C standard is actually really unclear on this point, and
348 // DR106 tells us what the result should be but not why. It's
349 // generally best to say that void types just doesn't undergo
350 // lvalue-to-rvalue at all. Note that expressions of unqualified
351 // 'void' type are never l-values, but qualified void can be.
352 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000353 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000354
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall27584242010-12-06 20:48:59 +0000357 // C++ [conv.lval]p1:
358 // [...] If T is a non-class type, the type of the prvalue is the
359 // cv-unqualified version of T. Otherwise, the type of the
360 // rvalue is T.
361 //
362 // C99 6.3.2.1p2:
363 // If the lvalue has qualified type, the value has the unqualified
364 // version of the type of the lvalue; otherwise, the value has the
365 // type of the lvalue.
366 if (T.hasQualifiers())
367 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000368
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000371}
372
John Wiegley01296292011-04-08 18:41:53 +0000373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
374 ExprResult Res = DefaultFunctionArrayConversion(E);
375 if (Res.isInvalid())
376 return ExprError();
377 Res = DefaultLvalueConversion(Res.take());
378 if (Res.isInvalid())
379 return ExprError();
380 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000381}
382
383
Chris Lattner513165e2008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000387/// apply if the array is an argument to the sizeof or address (&) operators.
388/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000398
399 // Try to perform integral promotions if the object has a theoretically
400 // promotable type.
401 if (Ty->isIntegralOrUnscopedEnumerationType()) {
402 // C99 6.3.1.1p2:
403 //
404 // The following may be used in an expression wherever an int or
405 // unsigned int may be used:
406 // - an object or expression with an integer type whose integer
407 // conversion rank is less than or equal to the rank of int
408 // and unsigned int.
409 // - A bit-field of type _Bool, int, signed int, or unsigned int.
410 //
411 // If an int can represent all values of the original type, the
412 // value is converted to an int; otherwise, it is converted to an
413 // unsigned int. These are called the integer promotions. All
414 // other types are unchanged by the integer promotions.
415
416 QualType PTy = Context.isPromotableBitField(E);
417 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000425 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000426 }
John Wiegley01296292011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000428}
429
Chris Lattner2ce500f2008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000436
John Wiegley01296292011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000441
Chris Lattner2ce500f2008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
John McCall4bb057d2011-08-27 22:06:17 +0000446 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000447 // promotion, even on class types, but note:
448 // C++11 [conv.lval]p2:
449 // When an lvalue-to-rvalue conversion occurs in an unevaluated
450 // operand or a subexpression thereof the value contained in the
451 // referenced object is not accessed. Otherwise, if the glvalue
452 // has a class type, the conversion copy-initializes a temporary
453 // of type T from the glvalue and the result of the conversion
454 // is a prvalue for the temporary.
455 // FIXME: add some way to gate this entire thing for correctness in
456 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000457 if (getLangOptions().CPlusPlus && E->isGLValue() &&
458 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000459 ExprResult Temp = PerformCopyInitialization(
460 InitializedEntity::InitializeTemporary(E->getType()),
461 E->getExprLoc(),
462 Owned(E));
463 if (Temp.isInvalid())
464 return ExprError();
465 E = Temp.get();
466 }
467
John Wiegley01296292011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000469}
470
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000471/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
472/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000473/// interfaces passed by value.
474ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000475 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000476 ExprResult ExprRes = CheckPlaceholderExpr(E);
477 if (ExprRes.isInvalid())
478 return ExprError();
479
480 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000481 if (ExprRes.isInvalid())
482 return ExprError();
483 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregor347e0f22011-05-21 19:26:31 +0000485 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000486 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000487 DiagRuntimeBehavior(E->getLocStart(), 0,
488 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
489 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000490 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000491
John McCall31168b02011-06-15 23:02:42 +0000492 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000493 // C++0x [expr.call]p7:
494 // Passing a potentially-evaluated argument of class type (Clause 9)
495 // having a non-trivial copy constructor, a non-trivial move constructor,
496 // or a non-trivial destructor, with no corresponding parameter,
497 // is conditionally-supported with implementation-defined semantics.
498 bool TrivialEnough = false;
499 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
500 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
501 if (Record->hasTrivialCopyConstructor() &&
502 Record->hasTrivialMoveConstructor() &&
503 Record->hasTrivialDestructor())
504 TrivialEnough = true;
505 }
506 }
John McCall31168b02011-06-15 23:02:42 +0000507
508 if (!TrivialEnough &&
509 getLangOptions().ObjCAutoRefCount &&
510 E->getType()->isObjCLifetimeType())
511 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000512
513 if (TrivialEnough) {
514 // Nothing to diagnose. This is okay.
515 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000516 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000517 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000518 << CT)) {
519 // Turn this into a trap.
520 CXXScopeSpec SS;
521 UnqualifiedId Name;
522 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
523 E->getLocStart());
524 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
525 if (TrapFn.isInvalid())
526 return ExprError();
527
528 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
529 MultiExprArg(), E->getLocEnd());
530 if (Call.isInvalid())
531 return ExprError();
532
533 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
534 Call.get(), E);
535 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000536 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000537 E = Comma.get();
538 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000539 }
540
John Wiegley01296292011-04-08 18:41:53 +0000541 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000542}
543
Richard Trieu7aa58f12011-09-02 20:58:51 +0000544/// \brief Converts an integer to complex float type. Helper function of
545/// UsualArithmeticConversions()
546///
547/// \return false if the integer expression is an integer type and is
548/// successfully converted to the complex type.
549static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &intExpr,
550 ExprResult &complexExpr,
551 QualType intTy,
552 QualType complexTy,
553 bool skipCast) {
554 if (intTy->isComplexType() || intTy->isRealFloatingType()) return true;
555 if (skipCast) return false;
556 if (intTy->isIntegerType()) {
557 QualType fpTy = cast<ComplexType>(complexTy)->getElementType();
558 intExpr = S.ImpCastExprToType(intExpr.take(), fpTy, CK_IntegralToFloating);
559 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
560 CK_FloatingRealToComplex);
561 } else {
562 assert(intTy->isComplexIntegerType());
563 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
564 CK_IntegralComplexToFloatingComplex);
565 }
566 return false;
567}
568
569/// \brief Takes two complex float types and converts them to the same type.
570/// Helper function of UsualArithmeticConversions()
571static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000572handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
573 ExprResult &RHS, QualType LHSType,
574 QualType RHSType,
575 bool isCompAssign) {
576 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000577
578 if (order < 0) {
579 // _Complex float -> _Complex double
580 if (!isCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000581 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
582 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000583 }
584 if (order > 0)
585 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000586 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
587 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000588}
589
590/// \brief Converts otherExpr to complex float and promotes complexExpr if
591/// necessary. Helper function of UsualArithmeticConversions()
592static QualType handleOtherComplexFloatConversion(Sema &S,
593 ExprResult &complexExpr,
594 ExprResult &otherExpr,
595 QualType complexTy,
596 QualType otherTy,
597 bool convertComplexExpr,
598 bool convertOtherExpr) {
599 int order = S.Context.getFloatingTypeOrder(complexTy, otherTy);
600
601 // If just the complexExpr is complex, the otherExpr needs to be converted,
602 // and the complexExpr might need to be promoted.
603 if (order > 0) { // complexExpr is wider
604 // float -> _Complex double
605 if (convertOtherExpr) {
606 QualType fp = cast<ComplexType>(complexTy)->getElementType();
607 otherExpr = S.ImpCastExprToType(otherExpr.take(), fp, CK_FloatingCast);
608 otherExpr = S.ImpCastExprToType(otherExpr.take(), complexTy,
609 CK_FloatingRealToComplex);
610 }
611 return complexTy;
612 }
613
614 // otherTy is at least as wide. Find its corresponding complex type.
615 QualType result = (order == 0 ? complexTy :
616 S.Context.getComplexType(otherTy));
617
618 // double -> _Complex double
619 if (convertOtherExpr)
620 otherExpr = S.ImpCastExprToType(otherExpr.take(), result,
621 CK_FloatingRealToComplex);
622
623 // _Complex float -> _Complex double
624 if (convertComplexExpr && order < 0)
625 complexExpr = S.ImpCastExprToType(complexExpr.take(), result,
626 CK_FloatingComplexCast);
627
628 return result;
629}
630
631/// \brief Handle arithmetic conversion with complex types. Helper function of
632/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000633static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
634 ExprResult &RHS, QualType LHSType,
635 QualType RHSType,
636 bool isCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000637 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000638 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000639 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000640 return LHSType;
641 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000642 /*skipCast*/isCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000643 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000644
645 // This handles complex/complex, complex/float, or float/complex.
646 // When both operands are complex, the shorter operand is converted to the
647 // type of the longer, and that is the type of the result. This corresponds
648 // to what is done when combining two real floating-point operands.
649 // The fun begins when size promotion occur across type domains.
650 // From H&S 6.3.4: When one operand is complex and the other is a real
651 // floating-point type, the less precise type is converted, within it's
652 // real or complex domain, to the precision of the other type. For example,
653 // when combining a "long double" with a "double _Complex", the
654 // "double _Complex" is promoted to "long double _Complex".
655
Richard Trieu5065cdd2011-09-06 18:25:09 +0000656 bool LHSComplexFloat = LHSType->isComplexType();
657 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000658
659 // If both are complex, just cast to the more precise type.
660 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000661 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
662 LHSType, RHSType,
663 isCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000664
665 // If only one operand is complex, promote it if necessary and convert the
666 // other operand to complex.
667 if (LHSComplexFloat)
668 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000669 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!isCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000670 /*convertOtherExpr*/ true);
671
672 assert(RHSComplexFloat);
673 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000674 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675 /*convertOtherExpr*/ !isCompAssign);
676}
677
678/// \brief Hande arithmetic conversion from integer to float. Helper function
679/// of UsualArithmeticConversions()
680static QualType handleIntToFloatConversion(Sema &S, ExprResult &floatExpr,
681 ExprResult &intExpr,
682 QualType floatTy, QualType intTy,
683 bool convertFloat, bool convertInt) {
684 if (intTy->isIntegerType()) {
685 if (convertInt)
686 // Convert intExpr to the lhs floating point type.
687 intExpr = S.ImpCastExprToType(intExpr.take(), floatTy,
688 CK_IntegralToFloating);
689 return floatTy;
690 }
691
692 // Convert both sides to the appropriate complex float.
693 assert(intTy->isComplexIntegerType());
694 QualType result = S.Context.getComplexType(floatTy);
695
696 // _Complex int -> _Complex float
697 if (convertInt)
698 intExpr = S.ImpCastExprToType(intExpr.take(), result,
699 CK_IntegralComplexToFloatingComplex);
700
701 // float -> _Complex float
702 if (convertFloat)
703 floatExpr = S.ImpCastExprToType(floatExpr.take(), result,
704 CK_FloatingRealToComplex);
705
706 return result;
707}
708
709/// \brief Handle arithmethic conversion with floating point types. Helper
710/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000711static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
712 ExprResult &RHS, QualType LHSType,
713 QualType RHSType, bool isCompAssign) {
714 bool LHSFloat = LHSType->isRealFloatingType();
715 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000716
717 // If we have two real floating types, convert the smaller operand
718 // to the bigger result.
719 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000720 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000721 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000722 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
723 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000724 }
725
726 assert(order < 0 && "illegal float comparison");
727 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000728 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
729 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000730 }
731
732 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000733 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000734 /*convertFloat=*/!isCompAssign,
735 /*convertInt=*/ true);
736 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000737 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000738 /*convertInt=*/ true,
739 /*convertFloat=*/!isCompAssign);
740}
741
742/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000743/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000744// FIXME: if the operands are (int, _Complex long), we currently
745// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000746static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
749 bool isCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000750 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
751 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000752
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 if (LHSComplexInt && RHSComplexInt) {
754 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
755 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000756 assert(order && "inequal types with equal element ordering");
757 if (order > 0) {
758 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000759 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
760 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000761 }
762
763 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000764 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
765 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000766 }
767
Richard Trieucfe3f212011-09-06 18:38:41 +0000768 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000769 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000770 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
771 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772 }
773
Richard Trieucfe3f212011-09-06 18:38:41 +0000774 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000775 // int -> _Complex int
776 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000777 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
778 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779}
780
781/// \brief Handle integer arithmetic conversions. Helper function of
782/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000783static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
784 ExprResult &RHS, QualType LHSType,
785 QualType RHSType, bool isCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000786 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000787 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
788 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
789 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
790 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791 // Same signedness; use the higher-ranked type
792 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000793 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
794 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795 } else if (!isCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000796 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
797 return RHSType;
798 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799 // The unsigned type has greater than or equal rank to the
800 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000801 if (RHSSigned) {
802 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
803 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 } else if (!isCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000805 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
806 return RHSType;
807 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000808 // The two types are different widths; if we are here, that
809 // means the signed type is larger than the unsigned type, so
810 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000811 if (LHSSigned) {
812 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
813 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000814 } else if (!isCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000815 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
816 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000817 } else {
818 // The signed type is higher-ranked than the unsigned type,
819 // but isn't actually any bigger (like unsigned int and long
820 // on most 32-bit systems). Use the unsigned type corresponding
821 // to the signed type.
822 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000823 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
824 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000825 if (!isCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000826 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000827 return result;
828 }
829}
830
Chris Lattner513165e2008-07-25 21:10:04 +0000831/// UsualArithmeticConversions - Performs various conversions that are common to
832/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000833/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000834/// responsible for emitting appropriate error diagnostics.
835/// FIXME: verify the conversion rules for "complex int" are consistent with
836/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000837QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Chris Lattner513165e2008-07-25 21:10:04 +0000838 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000839 if (!isCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000840 LHS = UsualUnaryConversions(LHS.take());
841 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000842 return QualType();
843 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000844
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000845 RHS = UsualUnaryConversions(RHS.take());
846 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000847 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000848
Mike Stump11289f42009-09-09 15:08:12 +0000849 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000850 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000851 QualType LHSType =
852 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
853 QualType RHSType =
854 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000855
856 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000857 if (LHSType == RHSType)
858 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000859
860 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
861 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000862 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
863 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000864
John McCalld005ac92010-11-13 08:17:45 +0000865 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000866 QualType LHSUnpromotedType = LHSType;
867 if (LHSType->isPromotableIntegerType())
868 LHSType = Context.getPromotedIntegerType(LHSType);
869 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000870 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000871 LHSType = LHSBitfieldPromoteTy;
872 if (LHSType != LHSUnpromotedType && !isCompAssign)
873 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000874
John McCalld005ac92010-11-13 08:17:45 +0000875 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000876 if (LHSType == RHSType)
877 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000878
879 // At this point, we have two different arithmetic types.
880
881 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000882 if (LHSType->isComplexType() || RHSType->isComplexType())
883 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000884 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000885
886 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000887 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
888 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000889 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000890
891 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000892 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000893 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
894 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000895
896 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000897 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000898 isCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000899}
900
Chris Lattner513165e2008-07-25 21:10:04 +0000901//===----------------------------------------------------------------------===//
902// Semantic Analysis for various Expression Types
903//===----------------------------------------------------------------------===//
904
905
Peter Collingbourne91147592011-04-15 00:35:48 +0000906ExprResult
907Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
908 SourceLocation DefaultLoc,
909 SourceLocation RParenLoc,
910 Expr *ControllingExpr,
911 MultiTypeArg types,
912 MultiExprArg exprs) {
913 unsigned NumAssocs = types.size();
914 assert(NumAssocs == exprs.size());
915
916 ParsedType *ParsedTypes = types.release();
917 Expr **Exprs = exprs.release();
918
919 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
920 for (unsigned i = 0; i < NumAssocs; ++i) {
921 if (ParsedTypes[i])
922 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
923 else
924 Types[i] = 0;
925 }
926
927 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
928 ControllingExpr, Types, Exprs,
929 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000930 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000931 return ER;
932}
933
934ExprResult
935Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
936 SourceLocation DefaultLoc,
937 SourceLocation RParenLoc,
938 Expr *ControllingExpr,
939 TypeSourceInfo **Types,
940 Expr **Exprs,
941 unsigned NumAssocs) {
942 bool TypeErrorFound = false,
943 IsResultDependent = ControllingExpr->isTypeDependent(),
944 ContainsUnexpandedParameterPack
945 = ControllingExpr->containsUnexpandedParameterPack();
946
947 for (unsigned i = 0; i < NumAssocs; ++i) {
948 if (Exprs[i]->containsUnexpandedParameterPack())
949 ContainsUnexpandedParameterPack = true;
950
951 if (Types[i]) {
952 if (Types[i]->getType()->containsUnexpandedParameterPack())
953 ContainsUnexpandedParameterPack = true;
954
955 if (Types[i]->getType()->isDependentType()) {
956 IsResultDependent = true;
957 } else {
958 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
959 // complete object type other than a variably modified type."
960 unsigned D = 0;
961 if (Types[i]->getType()->isIncompleteType())
962 D = diag::err_assoc_type_incomplete;
963 else if (!Types[i]->getType()->isObjectType())
964 D = diag::err_assoc_type_nonobject;
965 else if (Types[i]->getType()->isVariablyModifiedType())
966 D = diag::err_assoc_type_variably_modified;
967
968 if (D != 0) {
969 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
970 << Types[i]->getTypeLoc().getSourceRange()
971 << Types[i]->getType();
972 TypeErrorFound = true;
973 }
974
975 // C1X 6.5.1.1p2 "No two generic associations in the same generic
976 // selection shall specify compatible types."
977 for (unsigned j = i+1; j < NumAssocs; ++j)
978 if (Types[j] && !Types[j]->getType()->isDependentType() &&
979 Context.typesAreCompatible(Types[i]->getType(),
980 Types[j]->getType())) {
981 Diag(Types[j]->getTypeLoc().getBeginLoc(),
982 diag::err_assoc_compatible_types)
983 << Types[j]->getTypeLoc().getSourceRange()
984 << Types[j]->getType()
985 << Types[i]->getType();
986 Diag(Types[i]->getTypeLoc().getBeginLoc(),
987 diag::note_compat_assoc)
988 << Types[i]->getTypeLoc().getSourceRange()
989 << Types[i]->getType();
990 TypeErrorFound = true;
991 }
992 }
993 }
994 }
995 if (TypeErrorFound)
996 return ExprError();
997
998 // If we determined that the generic selection is result-dependent, don't
999 // try to compute the result expression.
1000 if (IsResultDependent)
1001 return Owned(new (Context) GenericSelectionExpr(
1002 Context, KeyLoc, ControllingExpr,
1003 Types, Exprs, NumAssocs, DefaultLoc,
1004 RParenLoc, ContainsUnexpandedParameterPack));
1005
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001006 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001007 unsigned DefaultIndex = -1U;
1008 for (unsigned i = 0; i < NumAssocs; ++i) {
1009 if (!Types[i])
1010 DefaultIndex = i;
1011 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1012 Types[i]->getType()))
1013 CompatIndices.push_back(i);
1014 }
1015
1016 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1017 // type compatible with at most one of the types named in its generic
1018 // association list."
1019 if (CompatIndices.size() > 1) {
1020 // We strip parens here because the controlling expression is typically
1021 // parenthesized in macro definitions.
1022 ControllingExpr = ControllingExpr->IgnoreParens();
1023 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1024 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1025 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001026 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001027 E = CompatIndices.end(); I != E; ++I) {
1028 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1029 diag::note_compat_assoc)
1030 << Types[*I]->getTypeLoc().getSourceRange()
1031 << Types[*I]->getType();
1032 }
1033 return ExprError();
1034 }
1035
1036 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1037 // its controlling expression shall have type compatible with exactly one of
1038 // the types named in its generic association list."
1039 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1040 // We strip parens here because the controlling expression is typically
1041 // parenthesized in macro definitions.
1042 ControllingExpr = ControllingExpr->IgnoreParens();
1043 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1044 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1045 return ExprError();
1046 }
1047
1048 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1049 // type name that is compatible with the type of the controlling expression,
1050 // then the result expression of the generic selection is the expression
1051 // in that generic association. Otherwise, the result expression of the
1052 // generic selection is the expression in the default generic association."
1053 unsigned ResultIndex =
1054 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1055
1056 return Owned(new (Context) GenericSelectionExpr(
1057 Context, KeyLoc, ControllingExpr,
1058 Types, Exprs, NumAssocs, DefaultLoc,
1059 RParenLoc, ContainsUnexpandedParameterPack,
1060 ResultIndex));
1061}
1062
Steve Naroff83895f72007-09-16 03:34:24 +00001063/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001064/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1065/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1066/// multiple tokens. However, the common case is that StringToks points to one
1067/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001068///
John McCalldadc5752010-08-24 06:29:42 +00001069ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001070Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001071 assert(NumStringToks && "Must have at least one string!");
1072
Chris Lattner8a24e582009-01-16 18:51:42 +00001073 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001074 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001075 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001076
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001077 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001078 for (unsigned i = 0; i != NumStringToks; ++i)
1079 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001080
Chris Lattner36fc8792008-02-11 00:02:17 +00001081 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001082 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001083 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001084 else if (Literal.isUTF16())
1085 StrTy = Context.Char16Ty;
1086 else if (Literal.isUTF32())
1087 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001088 else if (Literal.Pascal)
1089 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001090
Douglas Gregorfb65e592011-07-27 05:40:30 +00001091 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1092 if (Literal.isWide())
1093 Kind = StringLiteral::Wide;
1094 else if (Literal.isUTF8())
1095 Kind = StringLiteral::UTF8;
1096 else if (Literal.isUTF16())
1097 Kind = StringLiteral::UTF16;
1098 else if (Literal.isUTF32())
1099 Kind = StringLiteral::UTF32;
1100
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001101 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001102 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001103 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001104
Chris Lattner36fc8792008-02-11 00:02:17 +00001105 // Get an array type for the string, according to C99 6.4.5. This includes
1106 // the nul terminator character as well as the string length for pascal
1107 // strings.
1108 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001109 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001110 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattner5b183d82006-11-10 05:03:26 +00001112 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001113 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001114 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001115 &StringTokLocs[0],
1116 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001117}
1118
John McCallc63de662011-02-02 13:00:07 +00001119enum CaptureResult {
1120 /// No capture is required.
1121 CR_NoCapture,
1122
1123 /// A capture is required.
1124 CR_Capture,
1125
John McCall351762c2011-02-07 10:33:21 +00001126 /// A by-ref capture is required.
1127 CR_CaptureByRef,
1128
John McCallc63de662011-02-02 13:00:07 +00001129 /// An error occurred when trying to capture the given variable.
1130 CR_Error
1131};
1132
1133/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001134///
John McCallc63de662011-02-02 13:00:07 +00001135/// \param var - the variable referenced
1136/// \param DC - the context which we couldn't capture through
1137static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001138diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001139 VarDecl *var, DeclContext *DC) {
1140 switch (S.ExprEvalContexts.back().Context) {
1141 case Sema::Unevaluated:
1142 // The argument will never be evaluated, so don't complain.
1143 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001144
John McCallc63de662011-02-02 13:00:07 +00001145 case Sema::PotentiallyEvaluated:
1146 case Sema::PotentiallyEvaluatedIfUsed:
1147 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001148
John McCallc63de662011-02-02 13:00:07 +00001149 case Sema::PotentiallyPotentiallyEvaluated:
1150 // FIXME: delay these!
1151 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153
John McCallc63de662011-02-02 13:00:07 +00001154 // Don't diagnose about capture if we're not actually in code right
1155 // now; in general, there are more appropriate places that will
1156 // diagnose this.
1157 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1158
John McCall92d627e2011-03-22 23:15:50 +00001159 // Certain madnesses can happen with parameter declarations, which
1160 // we want to ignore.
1161 if (isa<ParmVarDecl>(var)) {
1162 // - If the parameter still belongs to the translation unit, then
1163 // we're actually just using one parameter in the declaration of
1164 // the next. This is useful in e.g. VLAs.
1165 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1166 return CR_NoCapture;
1167
1168 // - This particular madness can happen in ill-formed default
1169 // arguments; claim it's okay and let downstream code handle it.
1170 if (S.CurContext == var->getDeclContext()->getParent())
1171 return CR_NoCapture;
1172 }
John McCallc63de662011-02-02 13:00:07 +00001173
1174 DeclarationName functionName;
1175 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1176 functionName = fn->getDeclName();
1177 // FIXME: variable from enclosing block that we couldn't capture from!
1178
1179 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1180 << var->getIdentifier() << functionName;
1181 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1182 << var->getIdentifier();
1183
1184 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001185}
1186
John McCall351762c2011-02-07 10:33:21 +00001187/// There is a well-formed capture at a particular scope level;
1188/// propagate it through all the nested blocks.
1189static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1190 const BlockDecl::Capture &capture) {
1191 VarDecl *var = capture.getVariable();
1192
1193 // Update all the inner blocks with the capture information.
1194 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1195 i != e; ++i) {
1196 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1197 innerBlock->Captures.push_back(
1198 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1199 /*nested*/ true, capture.getCopyExpr()));
1200 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1201 }
1202
1203 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1204}
1205
1206/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001207/// given value in the current context requires a variable capture.
1208///
1209/// This also keeps the captures set in the BlockScopeInfo records
1210/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001211static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001212 ValueDecl *value) {
1213 // Only variables ever require capture.
1214 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001215 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001216
1217 // Fast path: variables from the current context never require capture.
1218 DeclContext *DC = S.CurContext;
1219 if (var->getDeclContext() == DC) return CR_NoCapture;
1220
1221 // Only variables with local storage require capture.
1222 // FIXME: What about 'const' variables in C++?
1223 if (!var->hasLocalStorage()) return CR_NoCapture;
1224
1225 // Otherwise, we need to capture.
1226
1227 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001228 do {
1229 // Only blocks (and eventually C++0x closures) can capture; other
1230 // scopes don't work.
1231 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001232 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001233
1234 BlockScopeInfo *blockScope =
1235 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1236 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1237
John McCall351762c2011-02-07 10:33:21 +00001238 // Check whether we've already captured it in this block. If so,
1239 // we're done.
1240 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1241 return propagateCapture(S, functionScopesIndex,
1242 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001243
1244 functionScopesIndex--;
1245 DC = cast<BlockDecl>(DC)->getDeclContext();
1246 } while (var->getDeclContext() != DC);
1247
John McCall351762c2011-02-07 10:33:21 +00001248 // Okay, we descended all the way to the block that defines the variable.
1249 // Actually try to capture it.
1250 QualType type = var->getType();
1251
1252 // Prohibit variably-modified types.
1253 if (type->isVariablyModifiedType()) {
1254 S.Diag(loc, diag::err_ref_vm_type);
1255 S.Diag(var->getLocation(), diag::note_declared_at);
1256 return CR_Error;
1257 }
1258
1259 // Prohibit arrays, even in __block variables, but not references to
1260 // them.
1261 if (type->isArrayType()) {
1262 S.Diag(loc, diag::err_ref_array_type);
1263 S.Diag(var->getLocation(), diag::note_declared_at);
1264 return CR_Error;
1265 }
1266
1267 S.MarkDeclarationReferenced(loc, var);
1268
1269 // The BlocksAttr indicates the variable is bound by-reference.
1270 bool byRef = var->hasAttr<BlocksAttr>();
1271
1272 // Build a copy expression.
1273 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001274 const RecordType *rtype;
1275 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1276 (rtype = type->getAs<RecordType>())) {
1277
1278 // The capture logic needs the destructor, so make sure we mark it.
1279 // Usually this is unnecessary because most local variables have
1280 // their destructors marked at declaration time, but parameters are
1281 // an exception because it's technically only the call site that
1282 // actually requires the destructor.
1283 if (isa<ParmVarDecl>(var))
1284 S.FinalizeVarWithDestructor(var, rtype);
1285
John McCall351762c2011-02-07 10:33:21 +00001286 // According to the blocks spec, the capture of a variable from
1287 // the stack requires a const copy constructor. This is not true
1288 // of the copy/move done to move a __block variable to the heap.
1289 type.addConst();
1290
1291 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1292 ExprResult result =
1293 S.PerformCopyInitialization(
1294 InitializedEntity::InitializeBlock(var->getLocation(),
1295 type, false),
1296 loc, S.Owned(declRef));
1297
1298 // Build a full-expression copy expression if initialization
1299 // succeeded and used a non-trivial constructor. Recover from
1300 // errors by pretending that the copy isn't necessary.
1301 if (!result.isInvalid() &&
1302 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1303 result = S.MaybeCreateExprWithCleanups(result);
1304 copyExpr = result.take();
1305 }
1306 }
1307
1308 // We're currently at the declarer; go back to the closure.
1309 functionScopesIndex++;
1310 BlockScopeInfo *blockScope =
1311 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1312
1313 // Build a valid capture in this scope.
1314 blockScope->Captures.push_back(
1315 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1316 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1317
1318 // Propagate that to inner captures if necessary.
1319 return propagateCapture(S, functionScopesIndex,
1320 blockScope->Captures.back());
1321}
1322
1323static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1324 const DeclarationNameInfo &NameInfo,
1325 bool byRef) {
1326 assert(isa<VarDecl>(vd) && "capturing non-variable");
1327
1328 VarDecl *var = cast<VarDecl>(vd);
1329 assert(var->hasLocalStorage() && "capturing non-local");
1330 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1331
1332 QualType exprType = var->getType().getNonReferenceType();
1333
1334 BlockDeclRefExpr *BDRE;
1335 if (!byRef) {
1336 // The variable will be bound by copy; make it const within the
1337 // closure, but record that this was done in the expression.
1338 bool constAdded = !exprType.isConstQualified();
1339 exprType.addConst();
1340
1341 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1342 NameInfo.getLoc(), false,
1343 constAdded);
1344 } else {
1345 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1346 NameInfo.getLoc(), true);
1347 }
1348
1349 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001350}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001351
John McCalldadc5752010-08-24 06:29:42 +00001352ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001353Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001354 SourceLocation Loc,
1355 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001356 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001357 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001358}
1359
John McCallf4cd4f92011-02-09 01:13:10 +00001360/// BuildDeclRefExpr - Build an expression that references a
1361/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001362ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001363Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001364 const DeclarationNameInfo &NameInfo,
1365 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001366 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCall086a4642010-11-24 05:12:34 +00001368 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001369 SS? SS->getWithLocInContext(Context)
1370 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001371 D, NameInfo, Ty, VK);
1372
1373 // Just in case we're building an illegal pointer-to-member.
1374 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1375 E->setObjectKind(OK_BitField);
1376
1377 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001378}
1379
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001380/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001381/// possibly a list of template arguments.
1382///
1383/// If this produces template arguments, it is permitted to call
1384/// DecomposeTemplateName.
1385///
1386/// This actually loses a lot of source location information for
1387/// non-standard name kinds; we should consider preserving that in
1388/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001389void
1390Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1391 TemplateArgumentListInfo &Buffer,
1392 DeclarationNameInfo &NameInfo,
1393 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001394 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1395 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1396 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1397
Douglas Gregor5476205b2011-06-23 00:49:38 +00001398 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001399 Id.TemplateId->getTemplateArgs(),
1400 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001401 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001402 TemplateArgsPtr.release();
1403
John McCall3e56fd42010-08-23 07:28:44 +00001404 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001405 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001406 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001407 TemplateArgs = &Buffer;
1408 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001409 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001410 TemplateArgs = 0;
1411 }
1412}
1413
John McCalld681c392009-12-16 08:11:27 +00001414/// Diagnose an empty lookup.
1415///
1416/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001417bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001418 CorrectTypoContext CTC,
1419 TemplateArgumentListInfo *ExplicitTemplateArgs,
1420 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001421 DeclarationName Name = R.getLookupName();
1422
John McCalld681c392009-12-16 08:11:27 +00001423 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001424 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001425 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1426 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001427 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001428 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001429 diagnostic_suggest = diag::err_undeclared_use_suggest;
1430 }
John McCalld681c392009-12-16 08:11:27 +00001431
Douglas Gregor598b08f2009-12-31 05:20:13 +00001432 // If the original lookup was an unqualified lookup, fake an
1433 // unqualified lookup. This is useful when (for example) the
1434 // original lookup would not have found something because it was a
1435 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001436 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001437 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001438 if (isa<CXXRecordDecl>(DC)) {
1439 LookupQualifiedName(R, DC);
1440
1441 if (!R.empty()) {
1442 // Don't give errors about ambiguities in this lookup.
1443 R.suppressDiagnostics();
1444
1445 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1446 bool isInstance = CurMethod &&
1447 CurMethod->isInstance() &&
1448 DC == CurMethod->getParent();
1449
1450 // Give a code modification hint to insert 'this->'.
1451 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1452 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001453 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001454 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1455 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001456 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001457 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001458 if (DepMethod) {
Francois Pichetbcf64712011-09-07 00:14:57 +00001459 if (getLangOptions().Microsoft)
1460 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001461 Diag(R.getNameLoc(), diagnostic) << Name
1462 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1463 QualType DepThisType = DepMethod->getThisType(Context);
1464 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1465 R.getNameLoc(), DepThisType, false);
1466 TemplateArgumentListInfo TList;
1467 if (ULE->hasExplicitTemplateArgs())
1468 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001469
Douglas Gregore16af532011-02-28 18:50:33 +00001470 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001471 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001472 CXXDependentScopeMemberExpr *DepExpr =
1473 CXXDependentScopeMemberExpr::Create(
1474 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001475 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001476 R.getLookupNameInfo(),
1477 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001478 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001479 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001480 // FIXME: we should be able to handle this case too. It is correct
1481 // to add this-> here. This is a workaround for PR7947.
1482 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001483 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001484 } else {
John McCalld681c392009-12-16 08:11:27 +00001485 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001486 }
John McCalld681c392009-12-16 08:11:27 +00001487
1488 // Do we really want to note all of these?
1489 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1490 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1491
1492 // Tell the callee to try to recover.
1493 return false;
1494 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001495
1496 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001497 }
1498 }
1499
Douglas Gregor598b08f2009-12-31 05:20:13 +00001500 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001501 TypoCorrection Corrected;
1502 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1503 S, &SS, NULL, false, CTC))) {
1504 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1505 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1506 R.setLookupName(Corrected.getCorrection());
1507
Hans Wennborg38198de2011-07-12 08:45:31 +00001508 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001509 if (Corrected.isOverloaded()) {
1510 OverloadCandidateSet OCS(R.getNameLoc());
1511 OverloadCandidateSet::iterator Best;
1512 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1513 CDEnd = Corrected.end();
1514 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001515 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001516 dyn_cast<FunctionTemplateDecl>(*CD))
1517 AddTemplateOverloadCandidate(
1518 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1519 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001520 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1521 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1522 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1523 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001524 }
1525 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1526 case OR_Success:
1527 ND = Best->Function;
1528 break;
1529 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001530 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001531 }
1532 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001533 R.addDecl(ND);
1534 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001535 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001536 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1537 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001538 else
1539 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001540 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001541 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001542 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1543 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001544 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001545 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001546
1547 // Tell the callee to try to recover.
1548 return false;
1549 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001550
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001551 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001552 // FIXME: If we ended up with a typo for a type name or
1553 // Objective-C class name, we're in trouble because the parser
1554 // is in the wrong place to recover. Suggest the typo
1555 // correction, but don't make it a fix-it since we're not going
1556 // to recover well anyway.
1557 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001558 Diag(R.getNameLoc(), diagnostic_suggest)
1559 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001560 else
1561 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001562 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001563 << SS.getRange();
1564
1565 // Don't try to recover; it won't work.
1566 return true;
1567 }
1568 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001569 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001570 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001571 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001572 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001573 else
Douglas Gregor25363982010-01-01 00:15:04 +00001574 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001575 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001576 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001577 return true;
1578 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001579 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001580 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001581
1582 // Emit a special diagnostic for failed member lookups.
1583 // FIXME: computing the declaration context might fail here (?)
1584 if (!SS.isEmpty()) {
1585 Diag(R.getNameLoc(), diag::err_no_member)
1586 << Name << computeDeclContext(SS, false)
1587 << SS.getRange();
1588 return true;
1589 }
1590
John McCalld681c392009-12-16 08:11:27 +00001591 // Give up, we can't recover.
1592 Diag(R.getNameLoc(), diagnostic) << Name;
1593 return true;
1594}
1595
John McCalldadc5752010-08-24 06:29:42 +00001596ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001597 CXXScopeSpec &SS,
1598 UnqualifiedId &Id,
1599 bool HasTrailingLParen,
1600 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001601 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1602 "cannot be direct & operand and have a trailing lparen");
1603
1604 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001605 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001606
John McCall10eae182009-11-30 22:42:35 +00001607 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001608
1609 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001610 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001611 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001612 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001613
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001614 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001615 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001616 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001617
John McCalle66edc12009-11-24 19:00:30 +00001618 // C++ [temp.dep.expr]p3:
1619 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001620 // -- an identifier that was declared with a dependent type,
1621 // (note: handled after lookup)
1622 // -- a template-id that is dependent,
1623 // (note: handled in BuildTemplateIdExpr)
1624 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001625 // -- a nested-name-specifier that contains a class-name that
1626 // names a dependent type.
1627 // Determine whether this is a member of an unknown specialization;
1628 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001629 bool DependentID = false;
1630 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1631 Name.getCXXNameType()->isDependentType()) {
1632 DependentID = true;
1633 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001634 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001635 if (RequireCompleteDeclContext(SS, DC))
1636 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001637 } else {
1638 DependentID = true;
1639 }
1640 }
1641
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001642 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001643 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001644 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001645
Fariborz Jahanian86151342010-07-22 23:33:21 +00001646 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001647 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001648 LookupResult R(*this, NameInfo,
1649 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1650 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001651 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001652 // Lookup the template name again to correctly establish the context in
1653 // which it was found. This is really unfortunate as we already did the
1654 // lookup to determine that it was a template name in the first place. If
1655 // this becomes a performance hit, we can work harder to preserve those
1656 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001657 bool MemberOfUnknownSpecialization;
1658 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1659 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001660
1661 if (MemberOfUnknownSpecialization ||
1662 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1663 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1664 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001665 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001666 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001667 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001668
Douglas Gregora5226932011-02-04 13:35:07 +00001669 // If the result might be in a dependent base class, this is a dependent
1670 // id-expression.
1671 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1672 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1673 TemplateArgs);
1674
John McCalle66edc12009-11-24 19:00:30 +00001675 // If this reference is in an Objective-C method, then we need to do
1676 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001677 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001678 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001679 if (E.isInvalid())
1680 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001681
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001682 if (Expr *Ex = E.takeAs<Expr>())
1683 return Owned(Ex);
1684
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001685 // for further use, this must be set to false if in class method.
1686 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001687 }
Chris Lattner59a25942008-03-31 00:36:02 +00001688 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001689
John McCalle66edc12009-11-24 19:00:30 +00001690 if (R.isAmbiguous())
1691 return ExprError();
1692
Douglas Gregor171c45a2009-02-18 21:56:37 +00001693 // Determine whether this name might be a candidate for
1694 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001695 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001696
John McCalle66edc12009-11-24 19:00:30 +00001697 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001698 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001699 // in C90, extension in C99, forbidden in C++).
1700 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1701 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1702 if (D) R.addDecl(D);
1703 }
1704
1705 // If this name wasn't predeclared and if this is not a function
1706 // call, diagnose the problem.
1707 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001708 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001709 return ExprError();
1710
1711 assert(!R.empty() &&
1712 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001713
1714 // If we found an Objective-C instance variable, let
1715 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001716 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001717 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1718 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001719 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001720 assert(E.isInvalid() || E.get());
1721 return move(E);
1722 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001723 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
John McCalle66edc12009-11-24 19:00:30 +00001726 // This is guaranteed from this point on.
1727 assert(!R.empty() || ADL);
1728
John McCall2d74de92009-12-01 22:10:20 +00001729 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001730 // C++ [class.mfct.non-static]p3:
1731 // When an id-expression that is not part of a class member access
1732 // syntax and not used to form a pointer to member is used in the
1733 // body of a non-static member function of class X, if name lookup
1734 // resolves the name in the id-expression to a non-static non-type
1735 // member of some class C, the id-expression is transformed into a
1736 // class member access expression using (*this) as the
1737 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001738 //
1739 // But we don't actually need to do this for '&' operands if R
1740 // resolved to a function or overloaded function set, because the
1741 // expression is ill-formed if it actually works out to be a
1742 // non-static member function:
1743 //
1744 // C++ [expr.ref]p4:
1745 // Otherwise, if E1.E2 refers to a non-static member function. . .
1746 // [t]he expression can be used only as the left-hand operand of a
1747 // member function call.
1748 //
1749 // There are other safeguards against such uses, but it's important
1750 // to get this right here so that we don't end up making a
1751 // spuriously dependent expression if we're inside a dependent
1752 // instance method.
John McCall57500772009-12-16 12:17:52 +00001753 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001754 bool MightBeImplicitMember;
1755 if (!isAddressOfOperand)
1756 MightBeImplicitMember = true;
1757 else if (!SS.isEmpty())
1758 MightBeImplicitMember = false;
1759 else if (R.isOverloadedResult())
1760 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001761 else if (R.isUnresolvableResult())
1762 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001763 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001764 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1765 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001766
1767 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001768 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001769 }
1770
John McCalle66edc12009-11-24 19:00:30 +00001771 if (TemplateArgs)
1772 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001773
John McCalle66edc12009-11-24 19:00:30 +00001774 return BuildDeclarationNameExpr(SS, R, ADL);
1775}
1776
John McCall10eae182009-11-30 22:42:35 +00001777/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1778/// declaration name, generally during template instantiation.
1779/// There's a large number of things which don't need to be done along
1780/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001781ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001782Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001783 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001784 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001785 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001786 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001787
John McCall0b66eb32010-05-01 00:40:08 +00001788 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001789 return ExprError();
1790
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001791 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001792 LookupQualifiedName(R, DC);
1793
1794 if (R.isAmbiguous())
1795 return ExprError();
1796
1797 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001798 Diag(NameInfo.getLoc(), diag::err_no_member)
1799 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001800 return ExprError();
1801 }
1802
1803 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1804}
1805
1806/// LookupInObjCMethod - The parser has read a name in, and Sema has
1807/// detected that we're currently inside an ObjC method. Perform some
1808/// additional lookup.
1809///
1810/// Ideally, most of this would be done by lookup, but there's
1811/// actually quite a lot of extra work involved.
1812///
1813/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001814ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001815Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001816 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001817 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001818 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001819
John McCalle66edc12009-11-24 19:00:30 +00001820 // There are two cases to handle here. 1) scoped lookup could have failed,
1821 // in which case we should look for an ivar. 2) scoped lookup could have
1822 // found a decl, but that decl is outside the current instance method (i.e.
1823 // a global variable). In these two cases, we do a lookup for an ivar with
1824 // this name, if the lookup sucedes, we replace it our current decl.
1825
1826 // If we're in a class method, we don't normally want to look for
1827 // ivars. But if we don't find anything else, and there's an
1828 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001829 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001830
1831 bool LookForIvars;
1832 if (Lookup.empty())
1833 LookForIvars = true;
1834 else if (IsClassMethod)
1835 LookForIvars = false;
1836 else
1837 LookForIvars = (Lookup.isSingleResult() &&
1838 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001839 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001840 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001841 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001842 ObjCInterfaceDecl *ClassDeclared;
1843 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1844 // Diagnose using an ivar in a class method.
1845 if (IsClassMethod)
1846 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1847 << IV->getDeclName());
1848
1849 // If we're referencing an invalid decl, just return this as a silent
1850 // error node. The error diagnostic was already emitted on the decl.
1851 if (IV->isInvalidDecl())
1852 return ExprError();
1853
1854 // Check if referencing a field with __attribute__((deprecated)).
1855 if (DiagnoseUseOfDecl(IV, Loc))
1856 return ExprError();
1857
1858 // Diagnose the use of an ivar outside of the declaring class.
1859 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1860 ClassDeclared != IFace)
1861 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1862
1863 // FIXME: This should use a new expr for a direct reference, don't
1864 // turn this into Self->ivar, just return a BareIVarExpr or something.
1865 IdentifierInfo &II = Context.Idents.get("self");
1866 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001867 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001868 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001869 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001870 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001871 SelfName, false, false);
1872 if (SelfExpr.isInvalid())
1873 return ExprError();
1874
John Wiegley01296292011-04-08 18:41:53 +00001875 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1876 if (SelfExpr.isInvalid())
1877 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001878
John McCalle66edc12009-11-24 19:00:30 +00001879 MarkDeclarationReferenced(Loc, IV);
1880 return Owned(new (Context)
1881 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001882 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001883 }
Chris Lattner87313662010-04-12 05:10:17 +00001884 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001885 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001886 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001887 ObjCInterfaceDecl *ClassDeclared;
1888 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1889 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1890 IFace == ClassDeclared)
1891 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1892 }
1893 }
1894
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001895 if (Lookup.empty() && II && AllowBuiltinCreation) {
1896 // FIXME. Consolidate this with similar code in LookupName.
1897 if (unsigned BuiltinID = II->getBuiltinID()) {
1898 if (!(getLangOptions().CPlusPlus &&
1899 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1900 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1901 S, Lookup.isForRedeclaration(),
1902 Lookup.getNameLoc());
1903 if (D) Lookup.addDecl(D);
1904 }
1905 }
1906 }
John McCalle66edc12009-11-24 19:00:30 +00001907 // Sentinel value saying that we didn't do anything special.
1908 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001909}
John McCalld14a8642009-11-21 08:51:07 +00001910
John McCall16df1e52010-03-30 21:47:33 +00001911/// \brief Cast a base object to a member's actual type.
1912///
1913/// Logically this happens in three phases:
1914///
1915/// * First we cast from the base type to the naming class.
1916/// The naming class is the class into which we were looking
1917/// when we found the member; it's the qualifier type if a
1918/// qualifier was provided, and otherwise it's the base type.
1919///
1920/// * Next we cast from the naming class to the declaring class.
1921/// If the member we found was brought into a class's scope by
1922/// a using declaration, this is that class; otherwise it's
1923/// the class declaring the member.
1924///
1925/// * Finally we cast from the declaring class to the "true"
1926/// declaring class of the member. This conversion does not
1927/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001928ExprResult
1929Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001931 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001932 NamedDecl *Member) {
1933 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1934 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001935 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001936
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001937 QualType DestRecordType;
1938 QualType DestType;
1939 QualType FromRecordType;
1940 QualType FromType = From->getType();
1941 bool PointerConversions = false;
1942 if (isa<FieldDecl>(Member)) {
1943 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001944
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001945 if (FromType->getAs<PointerType>()) {
1946 DestType = Context.getPointerType(DestRecordType);
1947 FromRecordType = FromType->getPointeeType();
1948 PointerConversions = true;
1949 } else {
1950 DestType = DestRecordType;
1951 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001952 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001953 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1954 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001955 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001957 DestType = Method->getThisType(Context);
1958 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001959
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 if (FromType->getAs<PointerType>()) {
1961 FromRecordType = FromType->getPointeeType();
1962 PointerConversions = true;
1963 } else {
1964 FromRecordType = FromType;
1965 DestType = DestRecordType;
1966 }
1967 } else {
1968 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001969 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001970 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001973 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 // If the unqualified types are the same, no conversion is necessary.
1976 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001977 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001978
John McCall16df1e52010-03-30 21:47:33 +00001979 SourceRange FromRange = From->getSourceRange();
1980 SourceLocation FromLoc = FromRange.getBegin();
1981
John McCall2536c6d2010-08-25 10:28:54 +00001982 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001984 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001985 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 // class name.
1987 //
1988 // If the member was a qualified name and the qualified referred to a
1989 // specific base subobject type, we'll cast to that intermediate type
1990 // first and then to the object in which the member is declared. That allows
1991 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1992 //
1993 // class Base { public: int x; };
1994 // class Derived1 : public Base { };
1995 // class Derived2 : public Base { };
1996 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1997 //
1998 // void VeryDerived::f() {
1999 // x = 17; // error: ambiguous base subobjects
2000 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2001 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002003 QualType QType = QualType(Qualifier->getAsType(), 0);
2004 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2005 assert(QType->isRecordType() && "lookup done with non-record type");
2006
2007 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2008
2009 // In C++98, the qualifier type doesn't actually have to be a base
2010 // type of the object type, in which case we just ignore it.
2011 // Otherwise build the appropriate casts.
2012 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002013 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002014 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002015 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002016 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002017
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002018 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002019 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002020 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2021 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002022
2023 FromType = QType;
2024 FromRecordType = QRecordType;
2025
2026 // If the qualifier type was the same as the destination type,
2027 // we're done.
2028 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002029 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002030 }
2031 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002032
John McCall16df1e52010-03-30 21:47:33 +00002033 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002034
John McCall16df1e52010-03-30 21:47:33 +00002035 // If we actually found the member through a using declaration, cast
2036 // down to the using declaration's type.
2037 //
2038 // Pointer equality is fine here because only one declaration of a
2039 // class ever has member declarations.
2040 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2041 assert(isa<UsingShadowDecl>(FoundDecl));
2042 QualType URecordType = Context.getTypeDeclType(
2043 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2044
2045 // We only need to do this if the naming-class to declaring-class
2046 // conversion is non-trivial.
2047 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2048 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002049 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002050 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002051 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002052 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002053
John McCall16df1e52010-03-30 21:47:33 +00002054 QualType UType = URecordType;
2055 if (PointerConversions)
2056 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002057 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2058 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002059 FromType = UType;
2060 FromRecordType = URecordType;
2061 }
2062
2063 // We don't do access control for the conversion from the
2064 // declaring class to the true declaring class.
2065 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002066 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002067
John McCallcf142162010-08-07 06:22:56 +00002068 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002069 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2070 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002071 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002072 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002073
John Wiegley01296292011-04-08 18:41:53 +00002074 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2075 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002076}
Douglas Gregor3256d042009-06-30 15:47:41 +00002077
John McCalle66edc12009-11-24 19:00:30 +00002078bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002079 const LookupResult &R,
2080 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002081 // Only when used directly as the postfix-expression of a call.
2082 if (!HasTrailingLParen)
2083 return false;
2084
2085 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002086 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002087 return false;
2088
2089 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002090 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002091 return false;
2092
2093 // Turn off ADL when we find certain kinds of declarations during
2094 // normal lookup:
2095 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2096 NamedDecl *D = *I;
2097
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a declaration of a class member
2100 // Since using decls preserve this property, we check this on the
2101 // original decl.
John McCall57500772009-12-16 12:17:52 +00002102 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002103 return false;
2104
2105 // C++0x [basic.lookup.argdep]p3:
2106 // -- a block-scope function declaration that is not a
2107 // using-declaration
2108 // NOTE: we also trigger this for function templates (in fact, we
2109 // don't check the decl type at all, since all other decl types
2110 // turn off ADL anyway).
2111 if (isa<UsingShadowDecl>(D))
2112 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2113 else if (D->getDeclContext()->isFunctionOrMethod())
2114 return false;
2115
2116 // C++0x [basic.lookup.argdep]p3:
2117 // -- a declaration that is neither a function or a function
2118 // template
2119 // And also for builtin functions.
2120 if (isa<FunctionDecl>(D)) {
2121 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2122
2123 // But also builtin functions.
2124 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2125 return false;
2126 } else if (!isa<FunctionTemplateDecl>(D))
2127 return false;
2128 }
2129
2130 return true;
2131}
2132
2133
John McCalld14a8642009-11-21 08:51:07 +00002134/// Diagnoses obvious problems with the use of the given declaration
2135/// as an expression. This is only actually called for lookups that
2136/// were not overloaded, and it doesn't promise that the declaration
2137/// will in fact be used.
2138static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002139 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002140 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2141 return true;
2142 }
2143
2144 if (isa<ObjCInterfaceDecl>(D)) {
2145 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2146 return true;
2147 }
2148
2149 if (isa<NamespaceDecl>(D)) {
2150 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2151 return true;
2152 }
2153
2154 return false;
2155}
2156
John McCalldadc5752010-08-24 06:29:42 +00002157ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002158Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002159 LookupResult &R,
2160 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002161 // If this is a single, fully-resolved result and we don't need ADL,
2162 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002163 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002164 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2165 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002166
2167 // We only need to check the declaration if there's exactly one
2168 // result, because in the overloaded case the results can only be
2169 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002170 if (R.isSingleResult() &&
2171 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002172 return ExprError();
2173
John McCall58cc69d2010-01-27 01:50:18 +00002174 // Otherwise, just build an unresolved lookup expression. Suppress
2175 // any lookup-related diagnostics; we'll hash these out later, when
2176 // we've picked a target.
2177 R.suppressDiagnostics();
2178
John McCalld14a8642009-11-21 08:51:07 +00002179 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002180 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002181 SS.getWithLocInContext(Context),
2182 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002183 NeedsADL, R.isOverloadedResult(),
2184 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002185
2186 return Owned(ULE);
2187}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002188
John McCalld14a8642009-11-21 08:51:07 +00002189/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002190ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002191Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002192 const DeclarationNameInfo &NameInfo,
2193 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002194 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002195 assert(!isa<FunctionTemplateDecl>(D) &&
2196 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002197
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002198 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002199 if (CheckDeclInExpr(*this, Loc, D))
2200 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002201
Douglas Gregore7488b92009-12-01 16:58:18 +00002202 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2203 // Specifically diagnose references to class templates that are missing
2204 // a template argument list.
2205 Diag(Loc, diag::err_template_decl_ref)
2206 << Template << SS.getRange();
2207 Diag(Template->getLocation(), diag::note_template_decl_here);
2208 return ExprError();
2209 }
2210
2211 // Make sure that we're referring to a value.
2212 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2213 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002214 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002215 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002216 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002217 return ExprError();
2218 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002219
Douglas Gregor171c45a2009-02-18 21:56:37 +00002220 // Check whether this declaration can be used. Note that we suppress
2221 // this check when we're going to perform argument-dependent lookup
2222 // on this function name, because this might not be the function
2223 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002224 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002225 return ExprError();
2226
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002227 // Only create DeclRefExpr's for valid Decl's.
2228 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002229 return ExprError();
2230
John McCallf3a88602011-02-03 08:15:49 +00002231 // Handle members of anonymous structs and unions. If we got here,
2232 // and the reference is to a class member indirect field, then this
2233 // must be the subject of a pointer-to-member expression.
2234 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2235 if (!indirectField->isCXXClassMember())
2236 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2237 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002238
Chris Lattner2a9d9892008-10-20 05:16:36 +00002239 // If the identifier reference is inside a block, and it refers to a value
2240 // that is outside the block, create a BlockDeclRefExpr instead of a
2241 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2242 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002243 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002244 // We do not do this for things like enum constants, global variables, etc,
2245 // as they do not get snapshotted.
2246 //
John McCall351762c2011-02-07 10:33:21 +00002247 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002248 case CR_Error:
2249 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002250
John McCallc63de662011-02-02 13:00:07 +00002251 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002252 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2253 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2254
2255 case CR_CaptureByRef:
2256 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2257 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002258
2259 case CR_NoCapture: {
2260 // If this reference is not in a block or if the referenced
2261 // variable is within the block, create a normal DeclRefExpr.
2262
2263 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002264 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002265
2266 switch (D->getKind()) {
2267 // Ignore all the non-ValueDecl kinds.
2268#define ABSTRACT_DECL(kind)
2269#define VALUE(type, base)
2270#define DECL(type, base) \
2271 case Decl::type:
2272#include "clang/AST/DeclNodes.inc"
2273 llvm_unreachable("invalid value decl kind");
2274 return ExprError();
2275
2276 // These shouldn't make it here.
2277 case Decl::ObjCAtDefsField:
2278 case Decl::ObjCIvar:
2279 llvm_unreachable("forming non-member reference to ivar?");
2280 return ExprError();
2281
2282 // Enum constants are always r-values and never references.
2283 // Unresolved using declarations are dependent.
2284 case Decl::EnumConstant:
2285 case Decl::UnresolvedUsingValue:
2286 valueKind = VK_RValue;
2287 break;
2288
2289 // Fields and indirect fields that got here must be for
2290 // pointer-to-member expressions; we just call them l-values for
2291 // internal consistency, because this subexpression doesn't really
2292 // exist in the high-level semantics.
2293 case Decl::Field:
2294 case Decl::IndirectField:
2295 assert(getLangOptions().CPlusPlus &&
2296 "building reference to field in C?");
2297
2298 // These can't have reference type in well-formed programs, but
2299 // for internal consistency we do this anyway.
2300 type = type.getNonReferenceType();
2301 valueKind = VK_LValue;
2302 break;
2303
2304 // Non-type template parameters are either l-values or r-values
2305 // depending on the type.
2306 case Decl::NonTypeTemplateParm: {
2307 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2308 type = reftype->getPointeeType();
2309 valueKind = VK_LValue; // even if the parameter is an r-value reference
2310 break;
2311 }
2312
2313 // For non-references, we need to strip qualifiers just in case
2314 // the template parameter was declared as 'const int' or whatever.
2315 valueKind = VK_RValue;
2316 type = type.getUnqualifiedType();
2317 break;
2318 }
2319
2320 case Decl::Var:
2321 // In C, "extern void blah;" is valid and is an r-value.
2322 if (!getLangOptions().CPlusPlus &&
2323 !type.hasQualifiers() &&
2324 type->isVoidType()) {
2325 valueKind = VK_RValue;
2326 break;
2327 }
2328 // fallthrough
2329
2330 case Decl::ImplicitParam:
2331 case Decl::ParmVar:
2332 // These are always l-values.
2333 valueKind = VK_LValue;
2334 type = type.getNonReferenceType();
2335 break;
2336
2337 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002338 const FunctionType *fty = type->castAs<FunctionType>();
2339
2340 // If we're referring to a function with an __unknown_anytype
2341 // result type, make the entire expression __unknown_anytype.
2342 if (fty->getResultType() == Context.UnknownAnyTy) {
2343 type = Context.UnknownAnyTy;
2344 valueKind = VK_RValue;
2345 break;
2346 }
2347
John McCallf4cd4f92011-02-09 01:13:10 +00002348 // Functions are l-values in C++.
2349 if (getLangOptions().CPlusPlus) {
2350 valueKind = VK_LValue;
2351 break;
2352 }
2353
2354 // C99 DR 316 says that, if a function type comes from a
2355 // function definition (without a prototype), that type is only
2356 // used for checking compatibility. Therefore, when referencing
2357 // the function, we pretend that we don't have the full function
2358 // type.
John McCall2979fe02011-04-12 00:42:48 +00002359 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2360 isa<FunctionProtoType>(fty))
2361 type = Context.getFunctionNoProtoType(fty->getResultType(),
2362 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002363
2364 // Functions are r-values in C.
2365 valueKind = VK_RValue;
2366 break;
2367 }
2368
2369 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002370 // If we're referring to a method with an __unknown_anytype
2371 // result type, make the entire expression __unknown_anytype.
2372 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002373 if (const FunctionProtoType *proto
2374 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002375 if (proto->getResultType() == Context.UnknownAnyTy) {
2376 type = Context.UnknownAnyTy;
2377 valueKind = VK_RValue;
2378 break;
2379 }
2380
John McCallf4cd4f92011-02-09 01:13:10 +00002381 // C++ methods are l-values if static, r-values if non-static.
2382 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2383 valueKind = VK_LValue;
2384 break;
2385 }
2386 // fallthrough
2387
2388 case Decl::CXXConversion:
2389 case Decl::CXXDestructor:
2390 case Decl::CXXConstructor:
2391 valueKind = VK_RValue;
2392 break;
2393 }
2394
2395 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2396 }
2397
John McCallc63de662011-02-02 13:00:07 +00002398 }
John McCall7decc9e2010-11-18 06:31:45 +00002399
John McCall351762c2011-02-07 10:33:21 +00002400 llvm_unreachable("unknown capture result");
2401 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002402}
Chris Lattnere168f762006-11-10 05:29:30 +00002403
John McCall2979fe02011-04-12 00:42:48 +00002404ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002405 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002406
Chris Lattnere168f762006-11-10 05:29:30 +00002407 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002408 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002409 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2410 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2411 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002412 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002413
Chris Lattnera81a0272008-01-12 08:14:25 +00002414 // Pre-defined identifiers are of type char[x], where x is the length of the
2415 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002416
Anders Carlsson2fb08242009-09-08 18:24:21 +00002417 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002418 if (!currentDecl && getCurBlock())
2419 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002420 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002421 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002422 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002423 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002424
Anders Carlsson0b209a82009-09-11 01:22:35 +00002425 QualType ResTy;
2426 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2427 ResTy = Context.DependentTy;
2428 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002429 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002430
Anders Carlsson0b209a82009-09-11 01:22:35 +00002431 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002432 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002433 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2434 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002435 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002436}
2437
John McCalldadc5752010-08-24 06:29:42 +00002438ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002439 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002440 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002441 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002442 if (Invalid)
2443 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002444
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002445 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002446 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002447 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002449
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002450 QualType Ty;
2451 if (!getLangOptions().CPlusPlus)
2452 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2453 else if (Literal.isWide())
2454 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002455 else if (Literal.isUTF16())
2456 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2457 else if (Literal.isUTF32())
2458 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002459 else if (Literal.isMultiChar())
2460 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002461 else
2462 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002463
Douglas Gregorfb65e592011-07-27 05:40:30 +00002464 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2465 if (Literal.isWide())
2466 Kind = CharacterLiteral::Wide;
2467 else if (Literal.isUTF16())
2468 Kind = CharacterLiteral::UTF16;
2469 else if (Literal.isUTF32())
2470 Kind = CharacterLiteral::UTF32;
2471
2472 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2473 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002474}
2475
John McCalldadc5752010-08-24 06:29:42 +00002476ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002478 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2479 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002480 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002481 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002482 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002483 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002484 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002485
Chris Lattner23b7eb62007-06-15 23:05:46 +00002486 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002487 // Add padding so that NumericLiteralParser can overread by one character.
2488 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002489 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002490
Chris Lattner67ca9252007-05-21 01:08:44 +00002491 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002492 bool Invalid = false;
2493 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2494 if (Invalid)
2495 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002496
Mike Stump11289f42009-09-09 15:08:12 +00002497 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002498 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002499 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002500 return ExprError();
2501
Chris Lattner1c20a172007-08-26 03:42:43 +00002502 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503
Chris Lattner1c20a172007-08-26 03:42:43 +00002504 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002505 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002506 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002507 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002508 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002509 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002510 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002511 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002512
2513 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2514
John McCall53b93a02009-12-24 09:08:04 +00002515 using llvm::APFloat;
2516 APFloat Val(Format);
2517
2518 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002519
2520 // Overflow is always an error, but underflow is only an error if
2521 // we underflowed to zero (APFloat reports denormals as underflow).
2522 if ((result & APFloat::opOverflow) ||
2523 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002524 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002525 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002526 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002527 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002528 APFloat::getLargest(Format).toString(buffer);
2529 } else {
John McCall62abc942010-02-26 23:35:57 +00002530 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002531 APFloat::getSmallest(Format).toString(buffer);
2532 }
2533
2534 Diag(Tok.getLocation(), diagnostic)
2535 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002536 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002537 }
2538
2539 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002540 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002541
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002542 if (Ty == Context.DoubleTy) {
2543 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002544 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002545 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2546 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002547 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002548 }
2549 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002550 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002551 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002552 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002553 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002554
Neil Boothac582c52007-08-29 22:00:19 +00002555 // long long is a C99 feature.
2556 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002557 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002558 Diag(Tok.getLocation(), diag::ext_longlong);
2559
Chris Lattner67ca9252007-05-21 01:08:44 +00002560 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002561 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002562
Chris Lattner67ca9252007-05-21 01:08:44 +00002563 if (Literal.GetIntegerValue(ResultVal)) {
2564 // If this value didn't fit into uintmax_t, warn and force to ull.
2565 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002566 Ty = Context.UnsignedLongLongTy;
2567 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002568 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002569 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002570 // If this value fits into a ULL, try to figure out what else it fits into
2571 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002572
Chris Lattner67ca9252007-05-21 01:08:44 +00002573 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2574 // be an unsigned int.
2575 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2576
2577 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002578 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002579 if (!Literal.isLong && !Literal.isLongLong) {
2580 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002581 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002582
Chris Lattner67ca9252007-05-21 01:08:44 +00002583 // Does it fit in a unsigned int?
2584 if (ResultVal.isIntN(IntSize)) {
2585 // Does it fit in a signed int?
2586 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002587 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002588 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002589 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002590 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002593
Chris Lattner67ca9252007-05-21 01:08:44 +00002594 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002595 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002596 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002597
Chris Lattner67ca9252007-05-21 01:08:44 +00002598 // Does it fit in a unsigned long?
2599 if (ResultVal.isIntN(LongSize)) {
2600 // Does it fit in a signed long?
2601 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002602 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002603 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002604 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002605 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002606 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002607 }
2608
Chris Lattner67ca9252007-05-21 01:08:44 +00002609 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002610 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002611 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002612
Chris Lattner67ca9252007-05-21 01:08:44 +00002613 // Does it fit in a unsigned long long?
2614 if (ResultVal.isIntN(LongLongSize)) {
2615 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002616 // To be compatible with MSVC, hex integer literals ending with the
2617 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002618 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2619 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002620 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002622 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002623 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002624 }
2625 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002626
Chris Lattner67ca9252007-05-21 01:08:44 +00002627 // If we still couldn't decide a type, we probably have something that
2628 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002629 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002630 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002632 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002633 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002634
Chris Lattner55258cf2008-05-09 05:59:00 +00002635 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002636 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002637 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002638 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002639 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640
Chris Lattner1c20a172007-08-26 03:42:43 +00002641 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2642 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002643 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002644 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002645
2646 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002647}
2648
John McCalldadc5752010-08-24 06:29:42 +00002649ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002650 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002651 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002652 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002653}
2654
Chandler Carruth62da79c2011-05-26 08:53:12 +00002655static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2656 SourceLocation Loc,
2657 SourceRange ArgRange) {
2658 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2659 // scalar or vector data type argument..."
2660 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2661 // type (C99 6.2.5p18) or void.
2662 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2663 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2664 << T << ArgRange;
2665 return true;
2666 }
2667
2668 assert((T->isVoidType() || !T->isIncompleteType()) &&
2669 "Scalar types should always be complete");
2670 return false;
2671}
2672
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002673static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2674 SourceLocation Loc,
2675 SourceRange ArgRange,
2676 UnaryExprOrTypeTrait TraitKind) {
2677 // C99 6.5.3.4p1:
2678 if (T->isFunctionType()) {
2679 // alignof(function) is allowed as an extension.
2680 if (TraitKind == UETT_SizeOf)
2681 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2682 return false;
2683 }
2684
2685 // Allow sizeof(void)/alignof(void) as an extension.
2686 if (T->isVoidType()) {
2687 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2688 return false;
2689 }
2690
2691 return true;
2692}
2693
2694static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2695 SourceLocation Loc,
2696 SourceRange ArgRange,
2697 UnaryExprOrTypeTrait TraitKind) {
2698 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2699 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2700 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2701 << T << (TraitKind == UETT_SizeOf)
2702 << ArgRange;
2703 return true;
2704 }
2705
2706 return false;
2707}
2708
Chandler Carruth14502c22011-05-26 08:53:10 +00002709/// \brief Check the constrains on expression operands to unary type expression
2710/// and type traits.
2711///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002712/// Completes any types necessary and validates the constraints on the operand
2713/// expression. The logic mostly mirrors the type-based overload, but may modify
2714/// the expression as it completes the type for that expression through template
2715/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002716bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2717 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002718 QualType ExprTy = Op->getType();
2719
2720 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2721 // the result is the size of the referenced type."
2722 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2723 // result shall be the alignment of the referenced type."
2724 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2725 ExprTy = Ref->getPointeeType();
2726
2727 if (ExprKind == UETT_VecStep)
2728 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2729 Op->getSourceRange());
2730
2731 // Whitelist some types as extensions
2732 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2733 Op->getSourceRange(), ExprKind))
2734 return false;
2735
2736 if (RequireCompleteExprType(Op,
2737 PDiag(diag::err_sizeof_alignof_incomplete_type)
2738 << ExprKind << Op->getSourceRange(),
2739 std::make_pair(SourceLocation(), PDiag(0))))
2740 return true;
2741
2742 // Completeing the expression's type may have changed it.
2743 ExprTy = Op->getType();
2744 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2745 ExprTy = Ref->getPointeeType();
2746
2747 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2748 Op->getSourceRange(), ExprKind))
2749 return true;
2750
Nico Weber0870deb2011-06-15 02:47:03 +00002751 if (ExprKind == UETT_SizeOf) {
2752 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2753 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2754 QualType OType = PVD->getOriginalType();
2755 QualType Type = PVD->getType();
2756 if (Type->isPointerType() && OType->isArrayType()) {
2757 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2758 << Type << OType;
2759 Diag(PVD->getLocation(), diag::note_declared_at);
2760 }
2761 }
2762 }
2763 }
2764
Chandler Carruth7c430c02011-05-27 01:33:31 +00002765 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002766}
2767
2768/// \brief Check the constraints on operands to unary expression and type
2769/// traits.
2770///
2771/// This will complete any types necessary, and validate the various constraints
2772/// on those operands.
2773///
Steve Naroff71b59a92007-06-04 22:22:31 +00002774/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002775/// C99 6.3.2.1p[2-4] all state:
2776/// Except when it is the operand of the sizeof operator ...
2777///
2778/// C++ [expr.sizeof]p4
2779/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2780/// standard conversions are not applied to the operand of sizeof.
2781///
2782/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002783bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2784 SourceLocation OpLoc,
2785 SourceRange ExprRange,
2786 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002787 if (exprType->isDependentType())
2788 return false;
2789
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002790 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2791 // the result is the size of the referenced type."
2792 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2793 // result shall be the alignment of the referenced type."
2794 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2795 exprType = Ref->getPointeeType();
2796
Chandler Carruth62da79c2011-05-26 08:53:12 +00002797 if (ExprKind == UETT_VecStep)
2798 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002799
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002800 // Whitelist some types as extensions
2801 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2802 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002803 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002804
Chris Lattner62975a72009-04-24 00:30:45 +00002805 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002806 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002807 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002808 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002810 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2811 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002812 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002813
Chris Lattner62975a72009-04-24 00:30:45 +00002814 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002815}
2816
Chandler Carruth14502c22011-05-26 08:53:10 +00002817static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002818 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002819
Mike Stump11289f42009-09-09 15:08:12 +00002820 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002821 if (isa<DeclRefExpr>(E))
2822 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002823
2824 // Cannot know anything else if the expression is dependent.
2825 if (E->isTypeDependent())
2826 return false;
2827
Douglas Gregor71235ec2009-05-02 02:18:30 +00002828 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002829 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2830 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002831 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002832 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002833
2834 // Alignment of a field access is always okay, so long as it isn't a
2835 // bit-field.
2836 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002837 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002838 return false;
2839
Chandler Carruth14502c22011-05-26 08:53:10 +00002840 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002841}
2842
Chandler Carruth14502c22011-05-26 08:53:10 +00002843bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002844 E = E->IgnoreParens();
2845
2846 // Cannot know anything else if the expression is dependent.
2847 if (E->isTypeDependent())
2848 return false;
2849
Chandler Carruth14502c22011-05-26 08:53:10 +00002850 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002851}
2852
Douglas Gregor0950e412009-03-13 21:01:28 +00002853/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002854ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002855Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2856 SourceLocation OpLoc,
2857 UnaryExprOrTypeTrait ExprKind,
2858 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002859 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002860 return ExprError();
2861
John McCallbcd03502009-12-07 02:54:59 +00002862 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002863
Douglas Gregor0950e412009-03-13 21:01:28 +00002864 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002865 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002866 return ExprError();
2867
2868 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002869 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2870 Context.getSizeType(),
2871 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002872}
2873
2874/// \brief Build a sizeof or alignof expression given an expression
2875/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002876ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002877Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2878 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002879 ExprResult PE = CheckPlaceholderExpr(E);
2880 if (PE.isInvalid())
2881 return ExprError();
2882
2883 E = PE.get();
2884
Douglas Gregor0950e412009-03-13 21:01:28 +00002885 // Verify that the operand is valid.
2886 bool isInvalid = false;
2887 if (E->isTypeDependent()) {
2888 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002889 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002890 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002891 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002892 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002893 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002894 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002895 isInvalid = true;
2896 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002897 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002898 }
2899
2900 if (isInvalid)
2901 return ExprError();
2902
2903 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002904 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002905 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002906 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002907}
2908
Peter Collingbournee190dee2011-03-11 19:24:49 +00002909/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2910/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002911/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002912ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002913Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2914 UnaryExprOrTypeTrait ExprKind, bool isType,
2915 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002916 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002917 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002918
Sebastian Redl6f282892008-11-11 17:56:53 +00002919 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002920 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002921 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002922 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002923 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002924
Douglas Gregor0950e412009-03-13 21:01:28 +00002925 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002926 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002927 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002928}
2929
John Wiegley01296292011-04-08 18:41:53 +00002930static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002931 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002932 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002933 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002934
John McCall34376a62010-12-04 03:47:34 +00002935 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002936 if (V.get()->getObjectKind() != OK_Ordinary) {
2937 V = S.DefaultLvalueConversion(V.take());
2938 if (V.isInvalid())
2939 return QualType();
2940 }
John McCall34376a62010-12-04 03:47:34 +00002941
Chris Lattnere267f5d2007-08-26 05:39:26 +00002942 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002943 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002944 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002945
Chris Lattnere267f5d2007-08-26 05:39:26 +00002946 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002947 if (V.get()->getType()->isArithmeticType())
2948 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002949
John McCall36226622010-10-12 02:09:17 +00002950 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002951 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002952 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002953 if (PR.get() != V.get()) {
2954 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002955 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002956 }
2957
Chris Lattnere267f5d2007-08-26 05:39:26 +00002958 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002959 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002960 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002961 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002962}
2963
2964
Chris Lattnere168f762006-11-10 05:29:30 +00002965
John McCalldadc5752010-08-24 06:29:42 +00002966ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002967Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002968 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002969 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002970 switch (Kind) {
2971 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002972 case tok::plusplus: Opc = UO_PostInc; break;
2973 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002974 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002975
John McCallb268a282010-08-23 23:25:46 +00002976 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002977}
2978
John McCalldadc5752010-08-24 06:29:42 +00002979ExprResult
John McCallb268a282010-08-23 23:25:46 +00002980Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2981 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002982 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002983 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002984 if (Result.isInvalid()) return ExprError();
2985 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002986
John McCallb268a282010-08-23 23:25:46 +00002987 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002988
Douglas Gregor40412ac2008-11-19 17:17:41 +00002989 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002990 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002991 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002992 Context.DependentTy,
2993 VK_LValue, OK_Ordinary,
2994 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002995 }
2996
Mike Stump11289f42009-09-09 15:08:12 +00002997 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002998 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002999 LHSExp->getType()->isEnumeralType() ||
3000 RHSExp->getType()->isRecordType() ||
3001 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003002 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003003 }
3004
John McCallb268a282010-08-23 23:25:46 +00003005 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003006}
3007
3008
John McCalldadc5752010-08-24 06:29:42 +00003009ExprResult
John McCallb268a282010-08-23 23:25:46 +00003010Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3011 Expr *Idx, SourceLocation RLoc) {
3012 Expr *LHSExp = Base;
3013 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003014
Chris Lattner36d572b2007-07-16 00:14:47 +00003015 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003016 if (!LHSExp->getType()->getAs<VectorType>()) {
3017 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3018 if (Result.isInvalid())
3019 return ExprError();
3020 LHSExp = Result.take();
3021 }
3022 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3023 if (Result.isInvalid())
3024 return ExprError();
3025 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026
Chris Lattner36d572b2007-07-16 00:14:47 +00003027 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003028 ExprValueKind VK = VK_LValue;
3029 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003030
Steve Naroffc1aadb12007-03-28 21:49:40 +00003031 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003032 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003033 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003034 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003035 Expr *BaseExpr, *IndexExpr;
3036 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003037 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3038 BaseExpr = LHSExp;
3039 IndexExpr = RHSExp;
3040 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003041 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003042 BaseExpr = LHSExp;
3043 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003044 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003045 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003046 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003047 BaseExpr = RHSExp;
3048 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003049 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003050 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003051 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003052 BaseExpr = LHSExp;
3053 IndexExpr = RHSExp;
3054 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003055 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003056 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003057 // Handle the uncommon case of "123[Ptr]".
3058 BaseExpr = RHSExp;
3059 IndexExpr = LHSExp;
3060 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003061 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003062 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003063 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003064 VK = LHSExp->getValueKind();
3065 if (VK != VK_RValue)
3066 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003067
Chris Lattner36d572b2007-07-16 00:14:47 +00003068 // FIXME: need to deal with const...
3069 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003070 } else if (LHSTy->isArrayType()) {
3071 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003072 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003073 // wasn't promoted because of the C90 rule that doesn't
3074 // allow promoting non-lvalue arrays. Warn, then
3075 // force the promotion here.
3076 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3077 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003078 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3079 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003080 LHSTy = LHSExp->getType();
3081
3082 BaseExpr = LHSExp;
3083 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003084 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003085 } else if (RHSTy->isArrayType()) {
3086 // Same as previous, except for 123[f().a] case
3087 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3088 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003089 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3090 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003091 RHSTy = RHSExp->getType();
3092
3093 BaseExpr = RHSExp;
3094 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003095 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003096 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003097 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3098 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003099 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003100 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003101 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003102 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3103 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003104
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003105 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003106 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3107 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003108 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3109
Douglas Gregorac1fb652009-03-24 19:52:54 +00003110 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003111 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3112 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003113 // incomplete types are not object types.
3114 if (ResultType->isFunctionType()) {
3115 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3116 << ResultType << BaseExpr->getSourceRange();
3117 return ExprError();
3118 }
Mike Stump11289f42009-09-09 15:08:12 +00003119
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003120 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3121 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003122 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3123 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003124
3125 // C forbids expressions of unqualified void type from being l-values.
3126 // See IsCForbiddenLValueType.
3127 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003128 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003129 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003130 PDiag(diag::err_subscript_incomplete_type)
3131 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003132 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattner62975a72009-04-24 00:30:45 +00003134 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003135 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003136 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3137 << ResultType << BaseExpr->getSourceRange();
3138 return ExprError();
3139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
John McCall4bc41ae2010-11-18 19:01:18 +00003141 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003142 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003143
Mike Stump4e1f26a2009-02-19 03:04:26 +00003144 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003145 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003146}
3147
John McCalldadc5752010-08-24 06:29:42 +00003148ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003149 FunctionDecl *FD,
3150 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003151 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003152 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003153 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003154 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003155 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003156 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003157 return ExprError();
3158 }
3159
3160 if (Param->hasUninstantiatedDefaultArg()) {
3161 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003162
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003163 // Instantiate the expression.
3164 MultiLevelTemplateArgumentList ArgList
3165 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003166
Nico Weber44887f62010-11-29 18:19:25 +00003167 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003168 = ArgList.getInnermost();
3169 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3170 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003171
Nico Weber44887f62010-11-29 18:19:25 +00003172 ExprResult Result;
3173 {
3174 // C++ [dcl.fct.default]p5:
3175 // The names in the [default argument] expression are bound, and
3176 // the semantic constraints are checked, at the point where the
3177 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003178 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003179 Result = SubstExpr(UninstExpr, ArgList);
3180 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003181 if (Result.isInvalid())
3182 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003183
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003184 // Check the expression as an initializer for the parameter.
3185 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003186 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003187 InitializationKind Kind
3188 = InitializationKind::CreateCopy(Param->getLocation(),
3189 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3190 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003191
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003192 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3193 Result = InitSeq.Perform(*this, Entity, Kind,
3194 MultiExprArg(*this, &ResultE, 1));
3195 if (Result.isInvalid())
3196 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003197
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198 // Build the default argument expression.
3199 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3200 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003201 }
3202
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003203 // If the default expression creates temporaries, we need to
3204 // push them to the current stack of expression temporaries so they'll
3205 // be properly destroyed.
3206 // FIXME: We should really be rebuilding the default argument with new
3207 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003208 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3209 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3210 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3211 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3212 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003213 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003214 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003215
3216 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003217 // Just mark all of the declarations in this potentially-evaluated expression
3218 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003219 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003220 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003221}
3222
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003223/// ConvertArgumentsForCall - Converts the arguments specified in
3224/// Args/NumArgs to the parameter types of the function FDecl with
3225/// function prototype Proto. Call is the call expression itself, and
3226/// Fn is the function expression. For a C++ member function, this
3227/// routine does not attempt to convert the object argument. Returns
3228/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003229bool
3230Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003231 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003232 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003233 Expr **Args, unsigned NumArgs,
3234 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003235 // Bail out early if calling a builtin with custom typechecking.
3236 // We don't need to do this in the
3237 if (FDecl)
3238 if (unsigned ID = FDecl->getBuiltinID())
3239 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3240 return false;
3241
Mike Stump4e1f26a2009-02-19 03:04:26 +00003242 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003243 // assignment, to the types of the corresponding parameter, ...
3244 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003245 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003246
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003247 // If too few arguments are available (and we don't have default
3248 // arguments for the remaining parameters), don't make the call.
3249 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003250 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3251 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003252 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003253 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003254
3255 // Emit the location of the prototype.
3256 if (FDecl && !FDecl->getBuiltinID())
3257 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3258 << FDecl;
3259
3260 return true;
3261 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003262 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003263 }
3264
3265 // If too many are passed and not variadic, error on the extras and drop
3266 // them.
3267 if (NumArgs > NumArgsInProto) {
3268 if (!Proto->isVariadic()) {
3269 Diag(Args[NumArgsInProto]->getLocStart(),
3270 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003271 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003272 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003273 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3274 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003275
3276 // Emit the location of the prototype.
3277 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003278 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3279 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003280
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003281 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003282 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003283 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003284 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003285 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003287 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003288 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3289 if (Fn->getType()->isBlockPointerType())
3290 CallType = VariadicBlock; // Block
3291 else if (isa<MemberExpr>(Fn))
3292 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003293 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003294 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003295 if (Invalid)
3296 return true;
3297 unsigned TotalNumArgs = AllArgs.size();
3298 for (unsigned i = 0; i < TotalNumArgs; ++i)
3299 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003300
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003301 return false;
3302}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003303
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003304bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3305 FunctionDecl *FDecl,
3306 const FunctionProtoType *Proto,
3307 unsigned FirstProtoArg,
3308 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003309 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003310 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003311 unsigned NumArgsInProto = Proto->getNumArgs();
3312 unsigned NumArgsToCheck = NumArgs;
3313 bool Invalid = false;
3314 if (NumArgs != NumArgsInProto)
3315 // Use default arguments for missing arguments
3316 NumArgsToCheck = NumArgsInProto;
3317 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003318 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003319 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003320 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003321
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003322 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003323 if (ArgIx < NumArgs) {
3324 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003325
Eli Friedman3164fb12009-03-22 22:00:50 +00003326 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3327 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003328 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003330 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003331
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003332 // Pass the argument
3333 ParmVarDecl *Param = 0;
3334 if (FDecl && i < FDecl->getNumParams())
3335 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003336
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003337 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003338 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003339 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3340 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003341 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003342 SourceLocation(),
3343 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003344 if (ArgE.isInvalid())
3345 return true;
3346
3347 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003348 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003349 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003350
John McCalldadc5752010-08-24 06:29:42 +00003351 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003352 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003353 if (ArgExpr.isInvalid())
3354 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003355
Anders Carlsson355933d2009-08-25 03:49:14 +00003356 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003357 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003358
3359 // Check for array bounds violations for each argument to the call. This
3360 // check only triggers warnings when the argument isn't a more complex Expr
3361 // with its own checking, such as a BinaryOperator.
3362 CheckArrayAccess(Arg);
3363
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003364 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003365 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003366
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003367 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003368 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003369
3370 // Assume that extern "C" functions with variadic arguments that
3371 // return __unknown_anytype aren't *really* variadic.
3372 if (Proto->getResultType() == Context.UnknownAnyTy &&
3373 FDecl && FDecl->isExternC()) {
3374 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3375 ExprResult arg;
3376 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3377 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3378 else
3379 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3380 Invalid |= arg.isInvalid();
3381 AllArgs.push_back(arg.take());
3382 }
3383
3384 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3385 } else {
3386 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003387 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3388 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003389 Invalid |= Arg.isInvalid();
3390 AllArgs.push_back(Arg.take());
3391 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003392 }
3393 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003394 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003395}
3396
John McCall2979fe02011-04-12 00:42:48 +00003397/// Given a function expression of unknown-any type, try to rebuild it
3398/// to have a function type.
3399static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3400
Steve Naroff83895f72007-09-16 03:34:24 +00003401/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003402/// This provides the location of the left/right parens and a list of comma
3403/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003404ExprResult
John McCallb268a282010-08-23 23:25:46 +00003405Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003406 MultiExprArg args, SourceLocation RParenLoc,
3407 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003408 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003409
3410 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003411 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003412 if (Result.isInvalid()) return ExprError();
3413 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003414
John McCallb268a282010-08-23 23:25:46 +00003415 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003416
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003417 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003418 // If this is a pseudo-destructor expression, build the call immediately.
3419 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3420 if (NumArgs > 0) {
3421 // Pseudo-destructor calls should not have any arguments.
3422 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003423 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003424 SourceRange(Args[0]->getLocStart(),
3425 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003426
Douglas Gregorad8a3362009-09-04 17:36:40 +00003427 NumArgs = 0;
3428 }
Mike Stump11289f42009-09-09 15:08:12 +00003429
Douglas Gregorad8a3362009-09-04 17:36:40 +00003430 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003431 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003432 }
Mike Stump11289f42009-09-09 15:08:12 +00003433
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003434 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003435 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003436 // FIXME: Will need to cache the results of name lookup (including ADL) in
3437 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003438 bool Dependent = false;
3439 if (Fn->isTypeDependent())
3440 Dependent = true;
3441 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3442 Dependent = true;
3443
Peter Collingbourne41f85462011-02-09 21:07:24 +00003444 if (Dependent) {
3445 if (ExecConfig) {
3446 return Owned(new (Context) CUDAKernelCallExpr(
3447 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3448 Context.DependentTy, VK_RValue, RParenLoc));
3449 } else {
3450 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3451 Context.DependentTy, VK_RValue,
3452 RParenLoc));
3453 }
3454 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003455
3456 // Determine whether this is a call to an object (C++ [over.call.object]).
3457 if (Fn->getType()->isRecordType())
3458 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003459 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003460
John McCall2979fe02011-04-12 00:42:48 +00003461 if (Fn->getType() == Context.UnknownAnyTy) {
3462 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3463 if (result.isInvalid()) return ExprError();
3464 Fn = result.take();
3465 }
3466
John McCall0009fcc2011-04-26 20:42:42 +00003467 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003468 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003469 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003470 }
John McCall0009fcc2011-04-26 20:42:42 +00003471 }
John McCall10eae182009-11-30 22:42:35 +00003472
John McCall0009fcc2011-04-26 20:42:42 +00003473 // Check for overloaded calls. This can happen even in C due to extensions.
3474 if (Fn->getType() == Context.OverloadTy) {
3475 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3476
3477 // We aren't supposed to apply this logic if there's an '&' involved.
3478 if (!find.IsAddressOfOperand) {
3479 OverloadExpr *ovl = find.Expression;
3480 if (isa<UnresolvedLookupExpr>(ovl)) {
3481 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3482 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3483 RParenLoc, ExecConfig);
3484 } else {
John McCall2d74de92009-12-01 22:10:20 +00003485 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003486 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003487 }
3488 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003489 }
3490
Douglas Gregore254f902009-02-04 00:32:51 +00003491 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003492
Eli Friedmane14b1992009-12-26 03:35:45 +00003493 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003494
John McCall57500772009-12-16 12:17:52 +00003495 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003496 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3497 if (UnOp->getOpcode() == UO_AddrOf)
3498 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3499
John McCall57500772009-12-16 12:17:52 +00003500 if (isa<DeclRefExpr>(NakedFn))
3501 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003502 else if (isa<MemberExpr>(NakedFn))
3503 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003504
Peter Collingbourne41f85462011-02-09 21:07:24 +00003505 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3506 ExecConfig);
3507}
3508
3509ExprResult
3510Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3511 MultiExprArg execConfig, SourceLocation GGGLoc) {
3512 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3513 if (!ConfigDecl)
3514 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3515 << "cudaConfigureCall");
3516 QualType ConfigQTy = ConfigDecl->getType();
3517
3518 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3519 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3520
3521 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003522}
3523
Tanya Lattner55808c12011-06-04 00:47:47 +00003524/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3525///
3526/// __builtin_astype( value, dst type )
3527///
3528ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3529 SourceLocation BuiltinLoc,
3530 SourceLocation RParenLoc) {
3531 ExprValueKind VK = VK_RValue;
3532 ExprObjectKind OK = OK_Ordinary;
3533 QualType DstTy = GetTypeFromParser(destty);
3534 QualType SrcTy = expr->getType();
3535 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3536 return ExprError(Diag(BuiltinLoc,
3537 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003538 << DstTy
3539 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003540 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003541 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3542 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003543}
3544
John McCall57500772009-12-16 12:17:52 +00003545/// BuildResolvedCallExpr - Build a call to a resolved expression,
3546/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003547/// unary-convert to an expression of function-pointer or
3548/// block-pointer type.
3549///
3550/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003551ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003552Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3553 SourceLocation LParenLoc,
3554 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003555 SourceLocation RParenLoc,
3556 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003557 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3558
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003559 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003560 ExprResult Result = UsualUnaryConversions(Fn);
3561 if (Result.isInvalid())
3562 return ExprError();
3563 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003564
Chris Lattner08464942007-12-28 05:29:59 +00003565 // Make the call expr early, before semantic checks. This guarantees cleanup
3566 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003567 CallExpr *TheCall;
3568 if (Config) {
3569 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3570 cast<CallExpr>(Config),
3571 Args, NumArgs,
3572 Context.BoolTy,
3573 VK_RValue,
3574 RParenLoc);
3575 } else {
3576 TheCall = new (Context) CallExpr(Context, Fn,
3577 Args, NumArgs,
3578 Context.BoolTy,
3579 VK_RValue,
3580 RParenLoc);
3581 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003582
John McCallbebede42011-02-26 05:39:39 +00003583 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3584
3585 // Bail out early if calling a builtin with custom typechecking.
3586 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3587 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3588
John McCall31996342011-04-07 08:22:57 +00003589 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003590 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003591 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003592 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3593 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003594 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003595 if (FuncT == 0)
3596 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3597 << Fn->getType() << Fn->getSourceRange());
3598 } else if (const BlockPointerType *BPT =
3599 Fn->getType()->getAs<BlockPointerType>()) {
3600 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3601 } else {
John McCall31996342011-04-07 08:22:57 +00003602 // Handle calls to expressions of unknown-any type.
3603 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003604 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003605 if (rewrite.isInvalid()) return ExprError();
3606 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003607 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003608 goto retry;
3609 }
3610
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003611 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3612 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003613 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003614
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003615 if (getLangOptions().CUDA) {
3616 if (Config) {
3617 // CUDA: Kernel calls must be to global functions
3618 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3619 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3620 << FDecl->getName() << Fn->getSourceRange());
3621
3622 // CUDA: Kernel function must have 'void' return type
3623 if (!FuncT->getResultType()->isVoidType())
3624 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3625 << Fn->getType() << Fn->getSourceRange());
3626 }
3627 }
3628
Eli Friedman3164fb12009-03-22 22:00:50 +00003629 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003630 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003631 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003632 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003633 return ExprError();
3634
Chris Lattner08464942007-12-28 05:29:59 +00003635 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003636 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003637 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003638
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003639 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003640 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003641 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003642 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003643 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003644 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003645
Douglas Gregord8e97de2009-04-02 15:37:10 +00003646 if (FDecl) {
3647 // Check if we have too few/too many template arguments, based
3648 // on our knowledge of the function definition.
3649 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003650 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003651 const FunctionProtoType *Proto
3652 = Def->getType()->getAs<FunctionProtoType>();
3653 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003654 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3655 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003656 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003657
3658 // If the function we're calling isn't a function prototype, but we have
3659 // a function prototype from a prior declaratiom, use that prototype.
3660 if (!FDecl->hasPrototype())
3661 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003662 }
3663
Steve Naroff0b661582007-08-28 23:30:39 +00003664 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003665 for (unsigned i = 0; i != NumArgs; i++) {
3666 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003667
3668 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003669 InitializedEntity Entity
3670 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003671 Proto->getArgType(i),
3672 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003673 ExprResult ArgE = PerformCopyInitialization(Entity,
3674 SourceLocation(),
3675 Owned(Arg));
3676 if (ArgE.isInvalid())
3677 return true;
3678
3679 Arg = ArgE.takeAs<Expr>();
3680
3681 } else {
John Wiegley01296292011-04-08 18:41:53 +00003682 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3683
3684 if (ArgE.isInvalid())
3685 return true;
3686
3687 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003688 }
3689
Douglas Gregor83025412010-10-26 05:45:40 +00003690 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3691 Arg->getType(),
3692 PDiag(diag::err_call_incomplete_argument)
3693 << Arg->getSourceRange()))
3694 return ExprError();
3695
Chris Lattner08464942007-12-28 05:29:59 +00003696 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003697 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003698 }
Chris Lattner08464942007-12-28 05:29:59 +00003699
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003700 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3701 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003702 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3703 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003704
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003705 // Check for sentinels
3706 if (NDecl)
3707 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003708
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003709 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003710 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003711 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003712 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003713
John McCallbebede42011-02-26 05:39:39 +00003714 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003715 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003716 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003717 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003718 return ExprError();
3719 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003720
John McCallb268a282010-08-23 23:25:46 +00003721 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003722}
3723
John McCalldadc5752010-08-24 06:29:42 +00003724ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003725Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003726 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003727 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003728 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003729 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003730
3731 TypeSourceInfo *TInfo;
3732 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3733 if (!TInfo)
3734 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3735
John McCallb268a282010-08-23 23:25:46 +00003736 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003737}
3738
John McCalldadc5752010-08-24 06:29:42 +00003739ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003740Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003741 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003742 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003743
Eli Friedman37a186d2008-05-20 05:22:08 +00003744 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003745 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3746 PDiag(diag::err_illegal_decl_array_incomplete_type)
3747 << SourceRange(LParenLoc,
3748 literalExpr->getSourceRange().getEnd())))
3749 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003750 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003751 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3752 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003753 } else if (!literalType->isDependentType() &&
3754 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003755 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003756 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003757 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003758 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003759
Douglas Gregor85dabae2009-12-16 01:38:02 +00003760 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003761 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003762 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003763 = InitializationKind::CreateCStyleCast(LParenLoc,
3764 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003765 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003766 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003767 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003768 &literalType);
3769 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003770 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003771 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003772
Chris Lattner79413952008-12-04 23:50:19 +00003773 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003774 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003775 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003776 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003777 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003778
John McCall7decc9e2010-11-18 06:31:45 +00003779 // In C, compound literals are l-values for some reason.
3780 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3781
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003782 return MaybeBindToTemporary(
3783 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3784 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003785}
3786
John McCalldadc5752010-08-24 06:29:42 +00003787ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003788Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003789 SourceLocation RBraceLoc) {
3790 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003791 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003792
Steve Naroff30d242c2007-09-15 18:49:24 +00003793 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003794 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003795
Ted Kremenekac034612010-04-13 23:39:13 +00003796 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3797 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003798 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003799 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003800}
3801
John McCalld7646252010-11-14 08:17:51 +00003802/// Prepares for a scalar cast, performing all the necessary stages
3803/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003804static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003805 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3806 // Also, callers should have filtered out the invalid cases with
3807 // pointers. Everything else should be possible.
3808
John Wiegley01296292011-04-08 18:41:53 +00003809 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003810 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003811 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003812
John McCall8cb679e2010-11-15 09:13:47 +00003813 switch (SrcTy->getScalarTypeKind()) {
3814 case Type::STK_MemberPointer:
3815 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003816
John McCall8cb679e2010-11-15 09:13:47 +00003817 case Type::STK_Pointer:
3818 switch (DestTy->getScalarTypeKind()) {
3819 case Type::STK_Pointer:
3820 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003821 CK_AnyPointerToObjCPointerCast :
3822 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003823 case Type::STK_Bool:
3824 return CK_PointerToBoolean;
3825 case Type::STK_Integral:
3826 return CK_PointerToIntegral;
3827 case Type::STK_Floating:
3828 case Type::STK_FloatingComplex:
3829 case Type::STK_IntegralComplex:
3830 case Type::STK_MemberPointer:
3831 llvm_unreachable("illegal cast from pointer");
3832 }
3833 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003834
John McCall8cb679e2010-11-15 09:13:47 +00003835 case Type::STK_Bool: // casting from bool is like casting from an integer
3836 case Type::STK_Integral:
3837 switch (DestTy->getScalarTypeKind()) {
3838 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003839 if (Src.get()->isNullPointerConstant(S.Context,
3840 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003841 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003842 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003843 case Type::STK_Bool:
3844 return CK_IntegralToBoolean;
3845 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003846 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003847 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003848 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003849 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003850 Src = S.ImpCastExprToType(Src.take(),
3851 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003852 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003853 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003854 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003855 Src = S.ImpCastExprToType(Src.take(),
3856 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003857 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003858 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003859 case Type::STK_MemberPointer:
3860 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003861 }
3862 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003863
John McCall8cb679e2010-11-15 09:13:47 +00003864 case Type::STK_Floating:
3865 switch (DestTy->getScalarTypeKind()) {
3866 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003867 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003868 case Type::STK_Bool:
3869 return CK_FloatingToBoolean;
3870 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003871 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003872 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003873 Src = S.ImpCastExprToType(Src.take(),
3874 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003875 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003876 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003877 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003878 Src = S.ImpCastExprToType(Src.take(),
3879 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003880 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003881 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003882 case Type::STK_Pointer:
3883 llvm_unreachable("valid float->pointer cast?");
3884 case Type::STK_MemberPointer:
3885 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003886 }
3887 break;
3888
John McCall8cb679e2010-11-15 09:13:47 +00003889 case Type::STK_FloatingComplex:
3890 switch (DestTy->getScalarTypeKind()) {
3891 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003892 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003893 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003894 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003895 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003896 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003897 if (S.Context.hasSameType(ET, DestTy))
3898 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003899 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003900 return CK_FloatingCast;
3901 }
John McCall8cb679e2010-11-15 09:13:47 +00003902 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003903 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003904 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003905 Src = S.ImpCastExprToType(Src.take(),
3906 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003907 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003908 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003909 case Type::STK_Pointer:
3910 llvm_unreachable("valid complex float->pointer cast?");
3911 case Type::STK_MemberPointer:
3912 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003913 }
3914 break;
3915
John McCall8cb679e2010-11-15 09:13:47 +00003916 case Type::STK_IntegralComplex:
3917 switch (DestTy->getScalarTypeKind()) {
3918 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003919 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003920 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003921 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003922 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003923 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003924 if (S.Context.hasSameType(ET, DestTy))
3925 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003926 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003927 return CK_IntegralCast;
3928 }
John McCall8cb679e2010-11-15 09:13:47 +00003929 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003930 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003931 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003932 Src = S.ImpCastExprToType(Src.take(),
3933 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003934 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003935 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003936 case Type::STK_Pointer:
3937 llvm_unreachable("valid complex int->pointer cast?");
3938 case Type::STK_MemberPointer:
3939 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003940 }
3941 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003942 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003943
John McCalld7646252010-11-14 08:17:51 +00003944 llvm_unreachable("Unhandled scalar cast");
3945 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003946}
3947
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003948/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003949ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3950 QualType castType, Expr *castExpr,
3951 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003952 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003953 if (castExpr->getType() == Context.UnknownAnyTy)
3954 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3955
Sebastian Redl9f831db2009-07-25 15:41:38 +00003956 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003957 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003958 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003959 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003960 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003961
John McCall3aef3d82011-04-10 19:13:55 +00003962 assert(!castExpr->getType()->isPlaceholderType());
3963
John McCall7decc9e2010-11-18 06:31:45 +00003964 // We only support r-value casts in C.
3965 VK = VK_RValue;
3966
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003967 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3968 // type needs to be scalar.
3969 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003970 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003971 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3972 if (castExprRes.isInvalid())
3973 return ExprError();
3974 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003975
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003976 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003977 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003978 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003979 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003980
John Wiegley01296292011-04-08 18:41:53 +00003981 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3982 if (castExprRes.isInvalid())
3983 return ExprError();
3984 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003985
Eli Friedmane98194d2010-07-17 20:43:49 +00003986 if (RequireCompleteType(TyR.getBegin(), castType,
3987 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003988 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003989
Anders Carlssonef918ac2009-10-16 02:35:04 +00003990 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003991 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003992 (castType->isStructureType() || castType->isUnionType())) {
3993 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003994 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003995 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3996 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003997 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003998 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003999 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004000
Anders Carlsson525b76b2009-10-16 02:48:28 +00004001 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004002 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004003 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004004 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004005 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004006 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004007 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004008 castExpr->getType()) &&
4009 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004010 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4011 << castExpr->getSourceRange();
4012 break;
4013 }
4014 }
John Wiegley01296292011-04-08 18:41:53 +00004015 if (Field == FieldEnd) {
4016 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004017 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004018 return ExprError();
4019 }
John McCalle3027922010-08-25 11:45:40 +00004020 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004021 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004022 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004023
Anders Carlsson525b76b2009-10-16 02:48:28 +00004024 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004025 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004026 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004027 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004028 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004029
John McCalld7646252010-11-14 08:17:51 +00004030 // The type we're casting to is known to be a scalar or vector.
4031
4032 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004033 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004034 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004035 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004036 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004037 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004038 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004039 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004040
4041 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004042 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004043
Anton Yartsev28ccef72011-03-27 09:32:40 +00004044 if (castType->isVectorType()) {
4045 if (castType->getAs<VectorType>()->getVectorKind() ==
4046 VectorType::AltiVecVector &&
4047 (castExpr->getType()->isIntegerType() ||
4048 castExpr->getType()->isFloatingType())) {
4049 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004050 return Owned(castExpr);
4051 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4052 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004053 } else
John Wiegley01296292011-04-08 18:41:53 +00004054 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004055 }
John Wiegley01296292011-04-08 18:41:53 +00004056 if (castExpr->getType()->isVectorType()) {
4057 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4058 return ExprError();
4059 else
4060 return Owned(castExpr);
4061 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004062
John McCalld7646252010-11-14 08:17:51 +00004063 // The source and target types are both scalars, i.e.
4064 // - arithmetic types (fundamental, enum, and complex)
4065 // - all kinds of pointers
4066 // Note that member pointers were filtered out with C++, above.
4067
John Wiegley01296292011-04-08 18:41:53 +00004068 if (isa<ObjCSelectorExpr>(castExpr)) {
4069 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4070 return ExprError();
4071 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072
John McCalld7646252010-11-14 08:17:51 +00004073 // If either type is a pointer, the other type has to be either an
4074 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004075 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004076 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004077 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004078 castExprType->isArithmeticType()) {
4079 Diag(castExpr->getLocStart(),
4080 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004081 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004082 return ExprError();
4083 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004084 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004085 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4086 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004087 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004088 return ExprError();
4089 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004090 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004091
John McCall31168b02011-06-15 23:02:42 +00004092 if (getLangOptions().ObjCAutoRefCount) {
4093 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4094 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4095 castType, castExpr, CCK_CStyleCast);
4096
4097 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4098 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4099 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4100 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4101 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4102 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4103 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4104 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004105 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004106 << castExprType << castType << AA_Casting
4107 << castExpr->getSourceRange();
4108
4109 return ExprError();
4110 }
4111 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004112 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004113 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4114 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004115 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004116 << castExprType << castType
4117 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004118 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004119 }
4120 }
4121
John Wiegley01296292011-04-08 18:41:53 +00004122 castExprRes = Owned(castExpr);
4123 Kind = PrepareScalarCast(*this, castExprRes, castType);
4124 if (castExprRes.isInvalid())
4125 return ExprError();
4126 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004127
John McCalld7646252010-11-14 08:17:51 +00004128 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004129 CheckCastAlign(castExpr, castType, TyR);
4130
John Wiegley01296292011-04-08 18:41:53 +00004131 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004132}
4133
Anders Carlsson525b76b2009-10-16 02:48:28 +00004134bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004135 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004136 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004137
Anders Carlssonde71adf2007-11-27 05:51:55 +00004138 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004139 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004140 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004141 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004142 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004143 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004144 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004145 } else
4146 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004147 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004148 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004149
John McCalle3027922010-08-25 11:45:40 +00004150 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004151 return false;
4152}
4153
John Wiegley01296292011-04-08 18:41:53 +00004154ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4155 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004156 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004157
Anders Carlsson43d70f82009-10-16 05:23:41 +00004158 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004159
Nate Begemanc8961a42009-06-27 22:05:55 +00004160 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4161 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004162 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004163 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4164 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004165 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004166 return ExprError();
4167 }
John McCalle3027922010-08-25 11:45:40 +00004168 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004169 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004170 }
4171
Nate Begemanbd956c42009-06-28 02:36:38 +00004172 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004173 // conversion will take place first from scalar to elt type, and then
4174 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004175 if (SrcTy->isPointerType())
4176 return Diag(R.getBegin(),
4177 diag::err_invalid_conversion_between_vector_and_scalar)
4178 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004179
4180 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004181 ExprResult CastExprRes = Owned(CastExpr);
4182 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4183 if (CastExprRes.isInvalid())
4184 return ExprError();
4185 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004186
John McCalle3027922010-08-25 11:45:40 +00004187 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004188 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004189}
4190
John McCalldadc5752010-08-24 06:29:42 +00004191ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004192Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4193 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004194 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004195 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004196 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004197
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004198 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4199 if (D.isInvalidType())
4200 return ExprError();
4201
4202 if (getLangOptions().CPlusPlus) {
4203 // Check that there are no default arguments (C++ only).
4204 CheckExtraCXXDefaultArguments(D);
4205 }
4206
4207 QualType castType = castTInfo->getType();
4208 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004209
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004210 bool isVectorLiteral = false;
4211
4212 // Check for an altivec or OpenCL literal,
4213 // i.e. all the elements are integer constants.
4214 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4215 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4216 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4217 if (PLE && PLE->getNumExprs() == 0) {
4218 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4219 return ExprError();
4220 }
4221 if (PE || PLE->getNumExprs() == 1) {
4222 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4223 if (!E->getType()->isVectorType())
4224 isVectorLiteral = true;
4225 }
4226 else
4227 isVectorLiteral = true;
4228 }
4229
4230 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4231 // then handle it as such.
4232 if (isVectorLiteral)
4233 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4234
Nate Begeman5ec4b312009-08-10 23:49:36 +00004235 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004236 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4237 // sequence of BinOp comma operators.
4238 if (isa<ParenListExpr>(castExpr)) {
4239 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4240 if (Result.isInvalid()) return ExprError();
4241 castExpr = Result.take();
4242 }
John McCallebe54742010-01-15 18:56:44 +00004243
John McCallb268a282010-08-23 23:25:46 +00004244 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004245}
4246
John McCalldadc5752010-08-24 06:29:42 +00004247ExprResult
John McCallebe54742010-01-15 18:56:44 +00004248Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004249 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004250 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004251 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004252 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004253 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004254 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4255 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004256 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004257 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004258 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004259
Richard Trieucfc491d2011-08-02 04:35:43 +00004260 return Owned(CStyleCastExpr::Create(
4261 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4262 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004263}
4264
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004265ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4266 SourceLocation RParenLoc, Expr *E,
4267 TypeSourceInfo *TInfo) {
4268 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4269 "Expected paren or paren list expression");
4270
4271 Expr **exprs;
4272 unsigned numExprs;
4273 Expr *subExpr;
4274 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4275 exprs = PE->getExprs();
4276 numExprs = PE->getNumExprs();
4277 } else {
4278 subExpr = cast<ParenExpr>(E)->getSubExpr();
4279 exprs = &subExpr;
4280 numExprs = 1;
4281 }
4282
4283 QualType Ty = TInfo->getType();
4284 assert(Ty->isVectorType() && "Expected vector type");
4285
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004286 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004287 const VectorType *VTy = Ty->getAs<VectorType>();
4288 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4289
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004290 // '(...)' form of vector initialization in AltiVec: the number of
4291 // initializers must be one or must match the size of the vector.
4292 // If a single value is specified in the initializer then it will be
4293 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004294 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004295 // The number of initializers must be one or must match the size of the
4296 // vector. If a single value is specified in the initializer then it will
4297 // be replicated to all the components of the vector
4298 if (numExprs == 1) {
4299 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4300 ExprResult Literal = Owned(exprs[0]);
4301 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4302 PrepareScalarCast(*this, Literal, ElemTy));
4303 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4304 }
4305 else if (numExprs < numElems) {
4306 Diag(E->getExprLoc(),
4307 diag::err_incorrect_number_of_vector_initializers);
4308 return ExprError();
4309 }
4310 else
4311 for (unsigned i = 0, e = numExprs; i != e; ++i)
4312 initExprs.push_back(exprs[i]);
4313 }
Tanya Lattner83559382011-07-15 23:07:01 +00004314 else {
4315 // For OpenCL, when the number of initializers is a single value,
4316 // it will be replicated to all components of the vector.
4317 if (getLangOptions().OpenCL &&
4318 VTy->getVectorKind() == VectorType::GenericVector &&
4319 numExprs == 1) {
4320 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4321 ExprResult Literal = Owned(exprs[0]);
4322 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4323 PrepareScalarCast(*this, Literal, ElemTy));
4324 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4325 }
4326
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004327 for (unsigned i = 0, e = numExprs; i != e; ++i)
4328 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004329 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004330 // FIXME: This means that pretty-printing the final AST will produce curly
4331 // braces instead of the original commas.
4332 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4333 &initExprs[0],
4334 initExprs.size(), RParenLoc);
4335 initE->setType(Ty);
4336 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4337}
4338
Nate Begeman5ec4b312009-08-10 23:49:36 +00004339/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4340/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004341ExprResult
John McCallb268a282010-08-23 23:25:46 +00004342Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004343 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4344 if (!E)
4345 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004346
John McCalldadc5752010-08-24 06:29:42 +00004347 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004348
Nate Begeman5ec4b312009-08-10 23:49:36 +00004349 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004350 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4351 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004352
John McCallb268a282010-08-23 23:25:46 +00004353 if (Result.isInvalid()) return ExprError();
4354
4355 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004356}
4357
John McCalldadc5752010-08-24 06:29:42 +00004358ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004359 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004360 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004361 unsigned nexprs = Val.size();
4362 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004363 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4364 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004365 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004366 expr = new (Context) ParenExpr(L, R, exprs[0]);
4367 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004368 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4369 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004370 return Owned(expr);
4371}
4372
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004373/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004374/// constant and the other is not a pointer. Returns true if a diagnostic is
4375/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004376bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004377 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004378 Expr *NullExpr = LHSExpr;
4379 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004380 Expr::NullPointerConstantKind NullKind =
4381 NullExpr->isNullPointerConstant(Context,
4382 Expr::NPC_ValueDependentIsNotNull);
4383
4384 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004385 NullExpr = RHSExpr;
4386 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004387 NullKind =
4388 NullExpr->isNullPointerConstant(Context,
4389 Expr::NPC_ValueDependentIsNotNull);
4390 }
4391
4392 if (NullKind == Expr::NPCK_NotNull)
4393 return false;
4394
4395 if (NullKind == Expr::NPCK_ZeroInteger) {
4396 // In this case, check to make sure that we got here from a "NULL"
4397 // string in the source code.
4398 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004399 SourceLocation loc = NullExpr->getExprLoc();
4400 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004401 return false;
4402 }
4403
4404 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4405 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4406 << NonPointerExpr->getType() << DiagType
4407 << NonPointerExpr->getSourceRange();
4408 return true;
4409}
4410
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004411/// \brief Return false if the condition expression is valid, true otherwise.
4412static bool checkCondition(Sema &S, Expr *Cond) {
4413 QualType CondTy = Cond->getType();
4414
4415 // C99 6.5.15p2
4416 if (CondTy->isScalarType()) return false;
4417
4418 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4419 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4420 return false;
4421
4422 // Emit the proper error message.
4423 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4424 diag::err_typecheck_cond_expect_scalar :
4425 diag::err_typecheck_cond_expect_scalar_or_vector)
4426 << CondTy;
4427 return true;
4428}
4429
4430/// \brief Return false if the two expressions can be converted to a vector,
4431/// true otherwise
4432static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4433 ExprResult &RHS,
4434 QualType CondTy) {
4435 // Both operands should be of scalar type.
4436 if (!LHS.get()->getType()->isScalarType()) {
4437 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4438 << CondTy;
4439 return true;
4440 }
4441 if (!RHS.get()->getType()->isScalarType()) {
4442 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4443 << CondTy;
4444 return true;
4445 }
4446
4447 // Implicity convert these scalars to the type of the condition.
4448 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4449 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4450 return false;
4451}
4452
4453/// \brief Handle when one or both operands are void type.
4454static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4455 ExprResult &RHS) {
4456 Expr *LHSExpr = LHS.get();
4457 Expr *RHSExpr = RHS.get();
4458
4459 if (!LHSExpr->getType()->isVoidType())
4460 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4461 << RHSExpr->getSourceRange();
4462 if (!RHSExpr->getType()->isVoidType())
4463 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4464 << LHSExpr->getSourceRange();
4465 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4466 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4467 return S.Context.VoidTy;
4468}
4469
4470/// \brief Return false if the NullExpr can be promoted to PointerTy,
4471/// true otherwise.
4472static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4473 QualType PointerTy) {
4474 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4475 !NullExpr.get()->isNullPointerConstant(S.Context,
4476 Expr::NPC_ValueDependentIsNull))
4477 return true;
4478
4479 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4480 return false;
4481}
4482
4483/// \brief Checks compatibility between two pointers and return the resulting
4484/// type.
4485static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4486 ExprResult &RHS,
4487 SourceLocation Loc) {
4488 QualType LHSTy = LHS.get()->getType();
4489 QualType RHSTy = RHS.get()->getType();
4490
4491 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4492 // Two identical pointers types are always compatible.
4493 return LHSTy;
4494 }
4495
4496 QualType lhptee, rhptee;
4497
4498 // Get the pointee types.
4499 if (LHSTy->isBlockPointerType()) {
4500 lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4501 rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4502 } else {
4503 lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4504 rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4505 }
4506
4507 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4508 rhptee.getUnqualifiedType())) {
4509 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4510 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4511 << RHS.get()->getSourceRange();
4512 // In this situation, we assume void* type. No especially good
4513 // reason, but this is what gcc does, and we do have to pick
4514 // to get a consistent AST.
4515 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4516 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4517 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4518 return incompatTy;
4519 }
4520
4521 // The pointer types are compatible.
4522 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4523 // differently qualified versions of compatible types, the result type is
4524 // a pointer to an appropriately qualified version of the *composite*
4525 // type.
4526 // FIXME: Need to calculate the composite type.
4527 // FIXME: Need to add qualifiers
4528
4529 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4530 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4531 return LHSTy;
4532}
4533
4534/// \brief Return the resulting type when the operands are both block pointers.
4535static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4536 ExprResult &LHS,
4537 ExprResult &RHS,
4538 SourceLocation Loc) {
4539 QualType LHSTy = LHS.get()->getType();
4540 QualType RHSTy = RHS.get()->getType();
4541
4542 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4543 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4544 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4545 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4546 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4547 return destType;
4548 }
4549 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4550 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4551 << RHS.get()->getSourceRange();
4552 return QualType();
4553 }
4554
4555 // We have 2 block pointer types.
4556 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4557}
4558
4559/// \brief Return the resulting type when the operands are both pointers.
4560static QualType
4561checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4562 ExprResult &RHS,
4563 SourceLocation Loc) {
4564 // get the pointer types
4565 QualType LHSTy = LHS.get()->getType();
4566 QualType RHSTy = RHS.get()->getType();
4567
4568 // get the "pointed to" types
4569 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4570 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4571
4572 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4573 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4574 // Figure out necessary qualifiers (C99 6.5.15p6)
4575 QualType destPointee
4576 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4577 QualType destType = S.Context.getPointerType(destPointee);
4578 // Add qualifiers if necessary.
4579 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4580 // Promote to void*.
4581 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4582 return destType;
4583 }
4584 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4585 QualType destPointee
4586 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4587 QualType destType = S.Context.getPointerType(destPointee);
4588 // Add qualifiers if necessary.
4589 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4590 // Promote to void*.
4591 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4592 return destType;
4593 }
4594
4595 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4596}
4597
4598/// \brief Return false if the first expression is not an integer and the second
4599/// expression is not a pointer, true otherwise.
4600static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4601 Expr* PointerExpr, SourceLocation Loc,
4602 bool isIntFirstExpr) {
4603 if (!PointerExpr->getType()->isPointerType() ||
4604 !Int.get()->getType()->isIntegerType())
4605 return false;
4606
4607 Expr *Expr1 = isIntFirstExpr ? Int.get() : PointerExpr;
4608 Expr *Expr2 = isIntFirstExpr ? PointerExpr : Int.get();
4609
4610 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4611 << Expr1->getType() << Expr2->getType()
4612 << Expr1->getSourceRange() << Expr2->getSourceRange();
4613 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4614 CK_IntegralToPointer);
4615 return true;
4616}
4617
Richard Trieud33e46e2011-09-06 20:06:39 +00004618/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4619/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004620/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004621QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4622 ExprResult &RHS, ExprValueKind &VK,
4623 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004624 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004625
Richard Trieud33e46e2011-09-06 20:06:39 +00004626 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4627 if (!LHSResult.isUsable()) return QualType();
4628 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004629
Richard Trieud33e46e2011-09-06 20:06:39 +00004630 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4631 if (!RHSResult.isUsable()) return QualType();
4632 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004633
Sebastian Redl1a99f442009-04-16 17:51:27 +00004634 // C++ is sufficiently different to merit its own checker.
4635 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004636 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004637
4638 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004639 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004640
John Wiegley01296292011-04-08 18:41:53 +00004641 Cond = UsualUnaryConversions(Cond.take());
4642 if (Cond.isInvalid())
4643 return QualType();
4644 LHS = UsualUnaryConversions(LHS.take());
4645 if (LHS.isInvalid())
4646 return QualType();
4647 RHS = UsualUnaryConversions(RHS.take());
4648 if (RHS.isInvalid())
4649 return QualType();
4650
4651 QualType CondTy = Cond.get()->getType();
4652 QualType LHSTy = LHS.get()->getType();
4653 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004654
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004655 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004656 if (checkCondition(*this, Cond.get()))
4657 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004658
Chris Lattnere2949f42008-01-06 22:42:25 +00004659 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004660 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004661 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004662
Nate Begemanabb5a732010-09-20 22:41:17 +00004663 // OpenCL: If the condition is a vector, and both operands are scalar,
4664 // attempt to implicity convert them to the vector type to act like the
4665 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004666 if (getLangOptions().OpenCL && CondTy->isVectorType())
4667 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004668 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004669
Chris Lattnere2949f42008-01-06 22:42:25 +00004670 // If both operands have arithmetic type, do the usual arithmetic conversions
4671 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004672 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4673 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004674 if (LHS.isInvalid() || RHS.isInvalid())
4675 return QualType();
4676 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004677 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004678
Chris Lattnere2949f42008-01-06 22:42:25 +00004679 // If both operands are the same structure or union type, the result is that
4680 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004681 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4682 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004683 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004684 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004685 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004686 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004687 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004688 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004689
Chris Lattnere2949f42008-01-06 22:42:25 +00004690 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004691 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004692 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004693 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004694 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004695
Steve Naroff039ad3c2008-01-08 01:11:38 +00004696 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4697 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004698 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4699 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004700
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004701 // All objective-c pointer type analysis is done here.
4702 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4703 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004704 if (LHS.isInvalid() || RHS.isInvalid())
4705 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004706 if (!compositeType.isNull())
4707 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004708
4709
Steve Naroff05efa972009-07-01 14:36:47 +00004710 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004711 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4712 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4713 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004714
Steve Naroff05efa972009-07-01 14:36:47 +00004715 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004716 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4717 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4718 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004719
John McCalle84af4e2010-11-13 01:35:44 +00004720 // GCC compatibility: soften pointer/integer mismatch. Note that
4721 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004722 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4723 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004724 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004725 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4726 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004727 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004728
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004729 // Emit a better diagnostic if one of the expressions is a null pointer
4730 // constant and the other is not a pointer type. In this case, the user most
4731 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004732 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004733 return QualType();
4734
Chris Lattnere2949f42008-01-06 22:42:25 +00004735 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004736 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004737 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4738 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004739 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004740}
4741
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004742/// FindCompositeObjCPointerType - Helper method to find composite type of
4743/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004744QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004745 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004746 QualType LHSTy = LHS.get()->getType();
4747 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004748
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 // Handle things like Class and struct objc_class*. Here we case the result
4750 // to the pseudo-builtin, because that will be implicitly cast back to the
4751 // redefinition type if an attempt is made to access its fields.
4752 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004753 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004754 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004755 return LHSTy;
4756 }
4757 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004758 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004759 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004760 return RHSTy;
4761 }
4762 // And the same for struct objc_object* / id
4763 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004764 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004765 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004766 return LHSTy;
4767 }
4768 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004769 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004770 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004771 return RHSTy;
4772 }
4773 // And the same for struct objc_selector* / SEL
4774 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004775 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004776 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004777 return LHSTy;
4778 }
4779 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004780 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004781 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004782 return RHSTy;
4783 }
4784 // Check constraints for Objective-C object pointers types.
4785 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004786
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004787 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4788 // Two identical object pointer types are always compatible.
4789 return LHSTy;
4790 }
4791 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4792 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4793 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004794
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004795 // If both operands are interfaces and either operand can be
4796 // assigned to the other, use that type as the composite
4797 // type. This allows
4798 // xxx ? (A*) a : (B*) b
4799 // where B is a subclass of A.
4800 //
4801 // Additionally, as for assignment, if either type is 'id'
4802 // allow silent coercion. Finally, if the types are
4803 // incompatible then make sure to use 'id' as the composite
4804 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004805
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004806 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4807 // It could return the composite type.
4808 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4809 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4810 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4811 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4812 } else if ((LHSTy->isObjCQualifiedIdType() ||
4813 RHSTy->isObjCQualifiedIdType()) &&
4814 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4815 // Need to handle "id<xx>" explicitly.
4816 // GCC allows qualified id and any Objective-C type to devolve to
4817 // id. Currently localizing to here until clear this should be
4818 // part of ObjCQualifiedIdTypesAreCompatible.
4819 compositeType = Context.getObjCIdType();
4820 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4821 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004822 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004823 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4824 ;
4825 else {
4826 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4827 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004828 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004829 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004830 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4831 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004832 return incompatTy;
4833 }
4834 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004835 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4836 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004837 return compositeType;
4838 }
4839 // Check Objective-C object pointer types and 'void *'
4840 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4841 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4842 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4843 QualType destPointee
4844 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4845 QualType destType = Context.getPointerType(destPointee);
4846 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004847 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004848 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004849 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004850 return destType;
4851 }
4852 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4853 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4854 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4855 QualType destPointee
4856 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4857 QualType destType = Context.getPointerType(destPointee);
4858 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004859 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004860 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004861 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004862 return destType;
4863 }
4864 return QualType();
4865}
4866
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004867/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004868/// ParenRange in parentheses.
4869static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004870 const PartialDiagnostic &Note,
4871 SourceRange ParenRange) {
4872 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4873 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4874 EndLoc.isValid()) {
4875 Self.Diag(Loc, Note)
4876 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4877 << FixItHint::CreateInsertion(EndLoc, ")");
4878 } else {
4879 // We can't display the parentheses, so just show the bare note.
4880 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004881 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004882}
4883
4884static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4885 return Opc >= BO_Mul && Opc <= BO_Shr;
4886}
4887
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004888/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4889/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004890/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4891/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004892static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004893 Expr **RHSExprs) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004894 E = E->IgnoreParenImpCasts();
4895 E = E->IgnoreConversionOperator();
4896 E = E->IgnoreParenImpCasts();
4897
4898 // Built-in binary operator.
4899 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4900 if (IsArithmeticOp(OP->getOpcode())) {
4901 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004902 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004903 return true;
4904 }
4905 }
4906
4907 // Overloaded operator.
4908 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4909 if (Call->getNumArgs() != 2)
4910 return false;
4911
4912 // Make sure this is really a binary operator that is safe to pass into
4913 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4914 OverloadedOperatorKind OO = Call->getOperator();
4915 if (OO < OO_Plus || OO > OO_Arrow)
4916 return false;
4917
4918 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4919 if (IsArithmeticOp(OpKind)) {
4920 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004921 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004922 return true;
4923 }
4924 }
4925
4926 return false;
4927}
4928
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004929static bool IsLogicOp(BinaryOperatorKind Opc) {
4930 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4931}
4932
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004933/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4934/// or is a logical expression such as (x==y) which has int type, but is
4935/// commonly interpreted as boolean.
4936static bool ExprLooksBoolean(Expr *E) {
4937 E = E->IgnoreParenImpCasts();
4938
4939 if (E->getType()->isBooleanType())
4940 return true;
4941 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4942 return IsLogicOp(OP->getOpcode());
4943 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4944 return OP->getOpcode() == UO_LNot;
4945
4946 return false;
4947}
4948
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004949/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4950/// and binary operator are mixed in a way that suggests the programmer assumed
4951/// the conditional operator has higher precedence, for example:
4952/// "int x = a + someBinaryCondition ? 1 : 2".
4953static void DiagnoseConditionalPrecedence(Sema &Self,
4954 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004955 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00004956 Expr *LHSExpr,
4957 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004958 BinaryOperatorKind CondOpcode;
4959 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004960
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004961 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004962 return;
4963 if (!ExprLooksBoolean(CondRHS))
4964 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004965
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004966 // The condition is an arithmetic binary expression, with a right-
4967 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004968
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004969 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004970 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004971 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004972
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004973 SuggestParentheses(Self, OpLoc,
4974 Self.PDiag(diag::note_precedence_conditional_silence)
4975 << BinaryOperator::getOpcodeStr(CondOpcode),
4976 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004977
4978 SuggestParentheses(Self, OpLoc,
4979 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00004980 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004981}
4982
Steve Naroff83895f72007-09-16 03:34:24 +00004983/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004984/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004985ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004986 SourceLocation ColonLoc,
4987 Expr *CondExpr, Expr *LHSExpr,
4988 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004989 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4990 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004991 OpaqueValueExpr *opaqueValue = 0;
4992 Expr *commonExpr = 0;
4993 if (LHSExpr == 0) {
4994 commonExpr = CondExpr;
4995
4996 // We usually want to apply unary conversions *before* saving, except
4997 // in the special case of a C++ l-value conditional.
4998 if (!(getLangOptions().CPlusPlus
4999 && !commonExpr->isTypeDependent()
5000 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5001 && commonExpr->isGLValue()
5002 && commonExpr->isOrdinaryOrBitFieldObject()
5003 && RHSExpr->isOrdinaryOrBitFieldObject()
5004 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005005 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5006 if (commonRes.isInvalid())
5007 return ExprError();
5008 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005009 }
5010
5011 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5012 commonExpr->getType(),
5013 commonExpr->getValueKind(),
5014 commonExpr->getObjectKind());
5015 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005016 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005017
John McCall7decc9e2010-11-18 06:31:45 +00005018 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005019 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005020 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5021 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005022 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005023 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5024 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005025 return ExprError();
5026
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005027 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5028 RHS.get());
5029
John McCallc07a0c72011-02-17 10:25:35 +00005030 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005031 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5032 LHS.take(), ColonLoc,
5033 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005034
5035 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005036 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005037 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5038 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005039}
5040
John McCallaba90822011-01-31 23:13:11 +00005041// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005042// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005043// routine is it effectively iqnores the qualifiers on the top level pointee.
5044// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5045// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005046static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005047checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5048 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5049 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005050
Steve Naroff1f4d7272007-05-11 04:00:31 +00005051 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005052 const Type *lhptee, *rhptee;
5053 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005054 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5055 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005056
John McCallaba90822011-01-31 23:13:11 +00005057 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005058
5059 // C99 6.5.16.1p1: This following citation is common to constraints
5060 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5061 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005062 Qualifiers lq;
5063
John McCall31168b02011-06-15 23:02:42 +00005064 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5065 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5066 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5067 // Ignore lifetime for further calculation.
5068 lhq.removeObjCLifetime();
5069 rhq.removeObjCLifetime();
5070 }
5071
John McCall4fff8f62011-02-01 00:10:29 +00005072 if (!lhq.compatiblyIncludes(rhq)) {
5073 // Treat address-space mismatches as fatal. TODO: address subspaces
5074 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5075 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5076
John McCall31168b02011-06-15 23:02:42 +00005077 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005078 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005079 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5080 .compatiblyIncludes(
5081 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005082 && (lhptee->isVoidType() || rhptee->isVoidType()))
5083 ; // keep old
5084
John McCall31168b02011-06-15 23:02:42 +00005085 // Treat lifetime mismatches as fatal.
5086 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5087 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5088
John McCall4fff8f62011-02-01 00:10:29 +00005089 // For GCC compatibility, other qualifier mismatches are treated
5090 // as still compatible in C.
5091 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5092 }
Steve Naroff3f597292007-05-11 22:18:03 +00005093
Mike Stump4e1f26a2009-02-19 03:04:26 +00005094 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5095 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005096 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005097 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005098 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005099 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005100
Chris Lattner0a788432008-01-03 22:56:36 +00005101 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005102 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005103 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005104 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005105
Chris Lattner0a788432008-01-03 22:56:36 +00005106 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005107 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005108 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005109
5110 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005111 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005112 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005113 }
John McCall4fff8f62011-02-01 00:10:29 +00005114
Mike Stump4e1f26a2009-02-19 03:04:26 +00005115 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005116 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005117 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5118 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005119 // Check if the pointee types are compatible ignoring the sign.
5120 // We explicitly check for char so that we catch "char" vs
5121 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005122 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005123 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005124 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005125 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005126
Chris Lattnerec3a1562009-10-17 20:33:28 +00005127 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005128 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005129 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005130 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005131
John McCall4fff8f62011-02-01 00:10:29 +00005132 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005133 // Types are compatible ignoring the sign. Qualifier incompatibility
5134 // takes priority over sign incompatibility because the sign
5135 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005136 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005137 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005138
John McCallaba90822011-01-31 23:13:11 +00005139 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005140 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005141
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005142 // If we are a multi-level pointer, it's possible that our issue is simply
5143 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5144 // the eventual target type is the same and the pointers have the same
5145 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005146 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005147 do {
John McCall4fff8f62011-02-01 00:10:29 +00005148 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5149 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005150 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005151
John McCall4fff8f62011-02-01 00:10:29 +00005152 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005153 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005154 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005155
Eli Friedman80160bd2009-03-22 23:59:44 +00005156 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005157 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005158 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005159 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005160}
5161
John McCallaba90822011-01-31 23:13:11 +00005162/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005163/// block pointer types are compatible or whether a block and normal pointer
5164/// are compatible. It is more restrict than comparing two function pointer
5165// types.
John McCallaba90822011-01-31 23:13:11 +00005166static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005167checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5168 QualType RHSType) {
5169 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5170 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005171
Steve Naroff081c7422008-09-04 15:10:53 +00005172 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005173
Steve Naroff081c7422008-09-04 15:10:53 +00005174 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005175 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5176 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005177
John McCallaba90822011-01-31 23:13:11 +00005178 // In C++, the types have to match exactly.
5179 if (S.getLangOptions().CPlusPlus)
5180 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005181
John McCallaba90822011-01-31 23:13:11 +00005182 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005183
Steve Naroff081c7422008-09-04 15:10:53 +00005184 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005185 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5186 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005187
Richard Trieua871b972011-09-06 20:21:22 +00005188 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005189 return Sema::IncompatibleBlockPointer;
5190
Steve Naroff081c7422008-09-04 15:10:53 +00005191 return ConvTy;
5192}
5193
John McCallaba90822011-01-31 23:13:11 +00005194/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005195/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005196static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005197checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5198 QualType RHSType) {
5199 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5200 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005201
Richard Trieua871b972011-09-06 20:21:22 +00005202 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005203 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005204 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5205 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005206 return Sema::IncompatiblePointer;
5207 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005208 }
Richard Trieua871b972011-09-06 20:21:22 +00005209 if (RHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005210 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005211 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5212 !LHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005213 return Sema::IncompatiblePointer;
5214 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005215 }
Richard Trieua871b972011-09-06 20:21:22 +00005216 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5217 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005218
John McCallaba90822011-01-31 23:13:11 +00005219 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5220 return Sema::CompatiblePointerDiscardsQualifiers;
5221
Richard Trieua871b972011-09-06 20:21:22 +00005222 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005223 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005224 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005225 return Sema::IncompatibleObjCQualifiedId;
5226 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005227}
5228
John McCall29600e12010-11-16 02:32:08 +00005229Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005230Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005231 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005232 // Fake up an opaque expression. We don't actually care about what
5233 // cast operations are required, so if CheckAssignmentConstraints
5234 // adds casts to this they'll be wasted, but fortunately that doesn't
5235 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005236 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5237 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005238 CastKind K = CK_Invalid;
5239
Richard Trieua871b972011-09-06 20:21:22 +00005240 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005241}
5242
Mike Stump4e1f26a2009-02-19 03:04:26 +00005243/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5244/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005245/// pointers. Here are some objectionable examples that GCC considers warnings:
5246///
5247/// int a, *pint;
5248/// short *pshort;
5249/// struct foo *pfoo;
5250///
5251/// pint = pshort; // warning: assignment from incompatible pointer type
5252/// a = pint; // warning: assignment makes integer from pointer without a cast
5253/// pint = a; // warning: assignment makes pointer from integer without a cast
5254/// pint = pfoo; // warning: assignment from incompatible pointer type
5255///
5256/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005258///
John McCall8cb679e2010-11-15 09:13:47 +00005259/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005260Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005261Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005262 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005263 QualType RHSType = RHS.get()->getType();
5264 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005265
Chris Lattnera52c2f22008-01-04 23:18:45 +00005266 // Get canonical types. We're not formatting these types, just comparing
5267 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005268 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5269 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005270
John McCalle5255932011-01-31 22:28:28 +00005271 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005272 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005273 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005274 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005275 }
5276
Douglas Gregor6b754842008-10-28 00:22:11 +00005277 // If the left-hand side is a reference type, then we are in a
5278 // (rare!) case where we've allowed the use of references in C,
5279 // e.g., as a parameter type in a built-in function. In this case,
5280 // just make sure that the type referenced is compatible with the
5281 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005282 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005283 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005284 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5285 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005286 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005287 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005288 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005289 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005290 }
John McCalle5255932011-01-31 22:28:28 +00005291
Nate Begemanbd956c42009-06-28 02:36:38 +00005292 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5293 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005294 if (LHSType->isExtVectorType()) {
5295 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005296 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005297 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005298 // CK_VectorSplat does T -> vector T, so first cast to the
5299 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005300 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5301 if (elType != RHSType) {
5302 Kind = PrepareScalarCast(*this, RHS, elType);
5303 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005304 }
5305 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005306 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005307 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
John McCalle5255932011-01-31 22:28:28 +00005310 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005311 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5312 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005313 // Allow assignments of an AltiVec vector type to an equivalent GCC
5314 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005315 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005316 Kind = CK_BitCast;
5317 return Compatible;
5318 }
5319
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005320 // If we are allowing lax vector conversions, and LHS and RHS are both
5321 // vectors, the total size only needs to be the same. This is a bitcast;
5322 // no bits are changed but the result type is different.
5323 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005324 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005325 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005326 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005327 }
Chris Lattner881a2122008-01-04 23:32:24 +00005328 }
5329 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005330 }
Eli Friedman3360d892008-05-30 18:07:22 +00005331
John McCalle5255932011-01-31 22:28:28 +00005332 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005333 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5334 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5335 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005336 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005337 }
Eli Friedman3360d892008-05-30 18:07:22 +00005338
John McCalle5255932011-01-31 22:28:28 +00005339 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005340 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005341 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005342 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005343 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005344 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005345 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005346
John McCalle5255932011-01-31 22:28:28 +00005347 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005348 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005349 Kind = CK_IntegralToPointer; // FIXME: null?
5350 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005351 }
John McCalle5255932011-01-31 22:28:28 +00005352
5353 // C pointers are not compatible with ObjC object pointers,
5354 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005355 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005356 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005357 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005358 Kind = CK_AnyPointerToObjCPointerCast;
5359 return Compatible;
5360 }
5361
5362 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005363 if (RHSType->isObjCClassType() &&
5364 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005365 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005366 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005367 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005368 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005369
John McCalle5255932011-01-31 22:28:28 +00005370 Kind = CK_BitCast;
5371 return IncompatiblePointer;
5372 }
5373
5374 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005375 if (RHSType->getAs<BlockPointerType>()) {
5376 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005377 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005378 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005379 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005380 }
John McCalle5255932011-01-31 22:28:28 +00005381
Steve Naroff081c7422008-09-04 15:10:53 +00005382 return Incompatible;
5383 }
5384
John McCalle5255932011-01-31 22:28:28 +00005385 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005386 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005387 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005388 if (RHSType->isBlockPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005389 Kind = CK_AnyPointerToBlockPointerCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005390 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005391 }
5392
5393 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005394 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005395 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005396 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005397 }
5398
John McCalle5255932011-01-31 22:28:28 +00005399 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005400 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005401 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005402 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005403 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005404
John McCalle5255932011-01-31 22:28:28 +00005405 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005406 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005407 if (RHSPT->getPointeeType()->isVoidType()) {
5408 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005409 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005410 }
John McCall8cb679e2010-11-15 09:13:47 +00005411
Chris Lattnera52c2f22008-01-04 23:18:45 +00005412 return Incompatible;
5413 }
5414
John McCalle5255932011-01-31 22:28:28 +00005415 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005416 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005417 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005418 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005419 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005420 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005421 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005422 if (getLangOptions().ObjCAutoRefCount &&
5423 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005424 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005425 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005426 return result;
John McCalle5255932011-01-31 22:28:28 +00005427 }
5428
5429 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005430 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005431 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005432 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005433 }
5434
John McCalle5255932011-01-31 22:28:28 +00005435 // In general, C pointers are not compatible with ObjC object pointers,
5436 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005437 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005438 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005439 if (RHSType->isVoidPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005440 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005441 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005442 }
5443
5444 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005445 if (LHSType->isObjCClassType() &&
5446 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005447 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005448 Kind = CK_BitCast;
5449 return Compatible;
5450 }
5451
5452 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005453 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005454 }
John McCalle5255932011-01-31 22:28:28 +00005455
5456 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005457 if (RHSType->isBlockPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005458 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005459 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005460 }
5461
Steve Naroff7cae42b2009-07-10 23:34:53 +00005462 return Incompatible;
5463 }
John McCalle5255932011-01-31 22:28:28 +00005464
5465 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005466 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005467 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005469 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005470 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005471 }
Eli Friedman3360d892008-05-30 18:07:22 +00005472
John McCalle5255932011-01-31 22:28:28 +00005473 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005474 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005475 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005476 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478
Chris Lattnera52c2f22008-01-04 23:18:45 +00005479 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005480 }
John McCalle5255932011-01-31 22:28:28 +00005481
5482 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005483 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005484 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005485 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005486 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005487 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005488 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489
John McCalle5255932011-01-31 22:28:28 +00005490 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005491 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005492 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005493 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005494 }
5495
Steve Naroff7cae42b2009-07-10 23:34:53 +00005496 return Incompatible;
5497 }
Eli Friedman3360d892008-05-30 18:07:22 +00005498
John McCalle5255932011-01-31 22:28:28 +00005499 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005500 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5501 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005502 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005503 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005504 }
Bill Wendling216423b2007-05-30 06:30:29 +00005505 }
John McCalle5255932011-01-31 22:28:28 +00005506
Steve Naroff98cf3e92007-06-06 18:38:38 +00005507 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005508}
5509
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005510/// \brief Constructs a transparent union from an expression that is
5511/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005512static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5513 ExprResult &EResult, QualType UnionType,
5514 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005515 // Build an initializer list that designates the appropriate member
5516 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005517 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005518 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005519 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005520 SourceLocation());
5521 Initializer->setType(UnionType);
5522 Initializer->setInitializedFieldInUnion(Field);
5523
5524 // Build a compound literal constructing a value of the transparent
5525 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005526 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005527 EResult = S.Owned(
5528 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5529 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005530}
5531
5532Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005533Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005534 ExprResult &RHS) {
5535 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005536
Mike Stump11289f42009-09-09 15:08:12 +00005537 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005538 // transparent_union GCC extension.
5539 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005540 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005541 return Incompatible;
5542
5543 // The field to initialize within the transparent union.
5544 RecordDecl *UD = UT->getDecl();
5545 FieldDecl *InitField = 0;
5546 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005547 for (RecordDecl::field_iterator it = UD->field_begin(),
5548 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005549 it != itend; ++it) {
5550 if (it->getType()->isPointerType()) {
5551 // If the transparent union contains a pointer type, we allow:
5552 // 1) void pointer
5553 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005554 if (RHSType->isPointerType())
5555 if (RHSType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5556 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005557 InitField = *it;
5558 break;
5559 }
Mike Stump11289f42009-09-09 15:08:12 +00005560
Richard Trieueb299142011-09-06 20:40:12 +00005561 if (RHS.get()->isNullPointerConstant(Context,
5562 Expr::NPC_ValueDependentIsNull)) {
5563 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5564 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005565 InitField = *it;
5566 break;
5567 }
5568 }
5569
John McCall8cb679e2010-11-15 09:13:47 +00005570 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005571 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005572 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005573 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005574 InitField = *it;
5575 break;
5576 }
5577 }
5578
5579 if (!InitField)
5580 return Incompatible;
5581
Richard Trieueb299142011-09-06 20:40:12 +00005582 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005583 return Compatible;
5584}
5585
Chris Lattner9bad62c2008-01-04 18:04:52 +00005586Sema::AssignConvertType
Richard Trieueb299142011-09-06 20:40:12 +00005587Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005588 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005589 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005590 // C++ 5.17p3: If the left operand is not of class type, the
5591 // expression is implicitly converted (C++ 4) to the
5592 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005593 ExprResult Res = PerformImplicitConversion(RHS.get(),
5594 LHSType.getUnqualifiedType(),
John Wiegley01296292011-04-08 18:41:53 +00005595 AA_Assigning);
5596 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005597 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005598 Sema::AssignConvertType result = Compatible;
5599 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005600 !CheckObjCARCUnavailableWeakConversion(LHSType,
5601 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005602 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005603 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005604 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005605 }
5606
5607 // FIXME: Currently, we fall through and treat C++ classes like C
5608 // structures.
John McCall34376a62010-12-04 03:47:34 +00005609 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005610
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005611 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5612 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005613 if ((LHSType->isPointerType() ||
5614 LHSType->isObjCObjectPointerType() ||
5615 LHSType->isBlockPointerType())
5616 && RHS.get()->isNullPointerConstant(Context,
5617 Expr::NPC_ValueDependentIsNull)) {
5618 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005619 return Compatible;
5620 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005621
Chris Lattnere6dcd502007-10-16 02:55:40 +00005622 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005623 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005624 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005625 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005626 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005627 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005628 if (!LHSType->isReferenceType()) {
5629 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5630 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005631 return Incompatible;
5632 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005633
John McCall8cb679e2010-11-15 09:13:47 +00005634 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005635 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005636 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005638 // C99 6.5.16.1p2: The value of the right operand is converted to the
5639 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005640 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5641 // so that we can use references in built-in functions even in C.
5642 // The getNonReferenceType() call makes sure that the resulting expression
5643 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005644 if (result != Incompatible && RHS.get()->getType() != LHSType)
5645 RHS = ImpCastExprToType(RHS.take(),
5646 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005647 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005648}
5649
Richard Trieueb299142011-09-06 20:40:12 +00005650QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5651 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005652 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005653 << LHS.get()->getType() << RHS.get()->getType()
5654 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005655 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005656}
5657
Richard Trieu859d23f2011-09-06 21:01:04 +00005658QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Eli Friedman1408bc92011-06-23 18:10:35 +00005659 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005660 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005661 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005662 QualType LHSType =
5663 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5664 QualType RHSType =
5665 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005666
Nate Begeman191a6b12008-07-14 18:02:46 +00005667 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005668 if (LHSType == RHSType)
5669 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005670
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005671 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005672 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5673 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5674 if (LHSType->isExtVectorType()) {
5675 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5676 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005677 }
5678
5679 if (!isCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005680 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5681 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005682 }
5683
Eli Friedman1408bc92011-06-23 18:10:35 +00005684 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005685 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005686 // If we are allowing lax vector conversions, and LHS and RHS are both
5687 // vectors, the total size only needs to be the same. This is a
5688 // bitcast; no bits are changed but the result type is different.
5689 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005690 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5691 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005692 }
5693
Nate Begemanbd956c42009-06-28 02:36:38 +00005694 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5695 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5696 bool swapped = false;
Richard Trieu859d23f2011-09-06 21:01:04 +00005697 if (RHSType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005698 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005699 std::swap(RHS, LHS);
5700 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005701 }
Mike Stump11289f42009-09-09 15:08:12 +00005702
Nate Begeman886448d2009-06-28 19:12:57 +00005703 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005704 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005705 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005706 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5707 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005708 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005709 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005710 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005711 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5712 if (swapped) std::swap(RHS, LHS);
5713 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005714 }
5715 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005716 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5717 RHSType->isRealFloatingType()) {
5718 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005719 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005720 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005721 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005722 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5723 if (swapped) std::swap(RHS, LHS);
5724 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005725 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005726 }
5727 }
Mike Stump11289f42009-09-09 15:08:12 +00005728
Nate Begeman886448d2009-06-28 19:12:57 +00005729 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005730 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005731 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005732 << LHS.get()->getType() << RHS.get()->getType()
5733 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005734 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005735}
5736
Richard Trieu859d23f2011-09-06 21:01:04 +00005737QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005738 SourceLocation Loc,
5739 bool isCompAssign, bool isDiv) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005740 if (LHS.get()->getType()->isVectorType() ||
5741 RHS.get()->getType()->isVectorType())
5742 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005743
Richard Trieu859d23f2011-09-06 21:01:04 +00005744 QualType compType = UsualArithmeticConversions(LHS, RHS, isCompAssign);
5745 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005746 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005747
Richard Trieu859d23f2011-09-06 21:01:04 +00005748 if (!LHS.get()->getType()->isArithmeticType() ||
5749 !RHS.get()->getType()->isArithmeticType())
5750 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005751
Chris Lattnerfaa54172010-01-12 21:23:57 +00005752 // Check for division by zero.
5753 if (isDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005754 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005755 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005756 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5757 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005758
Chris Lattnerfaa54172010-01-12 21:23:57 +00005759 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005760}
5761
Chris Lattnerfaa54172010-01-12 21:23:57 +00005762QualType Sema::CheckRemainderOperands(
Richard Trieu859d23f2011-09-06 21:01:04 +00005763 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool isCompAssign) {
5764 if (LHS.get()->getType()->isVectorType() ||
5765 RHS.get()->getType()->isVectorType()) {
5766 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5767 RHS.get()->getType()->hasIntegerRepresentation())
5768 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign);
5769 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005770 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005771
Richard Trieu859d23f2011-09-06 21:01:04 +00005772 QualType compType = UsualArithmeticConversions(LHS, RHS, isCompAssign);
5773 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005774 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005775
Richard Trieu859d23f2011-09-06 21:01:04 +00005776 if (!LHS.get()->getType()->isIntegerType() ||
5777 !RHS.get()->getType()->isIntegerType())
5778 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005779
Chris Lattnerfaa54172010-01-12 21:23:57 +00005780 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005782 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005783 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5784 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005785
Chris Lattnerfaa54172010-01-12 21:23:57 +00005786 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005787}
5788
Chandler Carruthc9332212011-06-27 08:02:19 +00005789/// \brief Diagnose invalid arithmetic on two void pointers.
5790static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005791 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005792 S.Diag(Loc, S.getLangOptions().CPlusPlus
5793 ? diag::err_typecheck_pointer_arith_void_type
5794 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005795 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5796 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005797}
5798
5799/// \brief Diagnose invalid arithmetic on a void pointer.
5800static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5801 Expr *Pointer) {
5802 S.Diag(Loc, S.getLangOptions().CPlusPlus
5803 ? diag::err_typecheck_pointer_arith_void_type
5804 : diag::ext_gnu_void_ptr)
5805 << 0 /* one pointer */ << Pointer->getSourceRange();
5806}
5807
5808/// \brief Diagnose invalid arithmetic on two function pointers.
5809static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5810 Expr *LHS, Expr *RHS) {
5811 assert(LHS->getType()->isAnyPointerType());
5812 assert(RHS->getType()->isAnyPointerType());
5813 S.Diag(Loc, S.getLangOptions().CPlusPlus
5814 ? diag::err_typecheck_pointer_arith_function_type
5815 : diag::ext_gnu_ptr_func_arith)
5816 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5817 // We only show the second type if it differs from the first.
5818 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5819 RHS->getType())
5820 << RHS->getType()->getPointeeType()
5821 << LHS->getSourceRange() << RHS->getSourceRange();
5822}
5823
5824/// \brief Diagnose invalid arithmetic on a function pointer.
5825static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5826 Expr *Pointer) {
5827 assert(Pointer->getType()->isAnyPointerType());
5828 S.Diag(Loc, S.getLangOptions().CPlusPlus
5829 ? diag::err_typecheck_pointer_arith_function_type
5830 : diag::ext_gnu_ptr_func_arith)
5831 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5832 << 0 /* one pointer, so only one type */
5833 << Pointer->getSourceRange();
5834}
5835
Richard Trieuaba22802011-09-02 02:15:37 +00005836/// \brief Warn if Operand is incomplete pointer type
5837///
5838/// \returns True if pointer has incomplete type
5839static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5840 Expr *Operand) {
5841 if ((Operand->getType()->isPointerType() &&
5842 !Operand->getType()->isDependentType()) ||
5843 Operand->getType()->isObjCObjectPointerType()) {
5844 QualType PointeeTy = Operand->getType()->getPointeeType();
5845 if (S.RequireCompleteType(
5846 Loc, PointeeTy,
5847 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5848 << PointeeTy << Operand->getSourceRange()))
5849 return true;
5850 }
5851 return false;
5852}
5853
Chandler Carruthc9332212011-06-27 08:02:19 +00005854/// \brief Check the validity of an arithmetic pointer operand.
5855///
5856/// If the operand has pointer type, this code will check for pointer types
5857/// which are invalid in arithmetic operations. These will be diagnosed
5858/// appropriately, including whether or not the use is supported as an
5859/// extension.
5860///
5861/// \returns True when the operand is valid to use (even if as an extension).
5862static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5863 Expr *Operand) {
5864 if (!Operand->getType()->isAnyPointerType()) return true;
5865
5866 QualType PointeeTy = Operand->getType()->getPointeeType();
5867 if (PointeeTy->isVoidType()) {
5868 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5869 return !S.getLangOptions().CPlusPlus;
5870 }
5871 if (PointeeTy->isFunctionType()) {
5872 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5873 return !S.getLangOptions().CPlusPlus;
5874 }
5875
Richard Trieuaba22802011-09-02 02:15:37 +00005876 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005877
5878 return true;
5879}
5880
5881/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5882/// operands.
5883///
5884/// This routine will diagnose any invalid arithmetic on pointer operands much
5885/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5886/// for emitting a single diagnostic even for operations where both LHS and RHS
5887/// are (potentially problematic) pointers.
5888///
5889/// \returns True when the operand is valid to use (even if as an extension).
5890static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005891 Expr *LHSExpr, Expr *RHSExpr) {
5892 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5893 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005894 if (!isLHSPointer && !isRHSPointer) return true;
5895
5896 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00005897 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5898 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005899
5900 // Check for arithmetic on pointers to incomplete types.
5901 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5902 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5903 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005904 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
5905 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
5906 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005907
5908 return !S.getLangOptions().CPlusPlus;
5909 }
5910
5911 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5912 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5913 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005914 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
5915 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
5916 RHSExpr);
5917 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005918
5919 return !S.getLangOptions().CPlusPlus;
5920 }
5921
Richard Trieu4ae7e972011-09-06 21:13:51 +00005922 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
5923 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00005924
Chandler Carruthc9332212011-06-27 08:02:19 +00005925 return true;
5926}
5927
Richard Trieub10c6312011-09-01 22:53:23 +00005928/// \brief Check bad cases where we step over interface counts.
5929static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5930 SourceLocation OpLoc,
5931 Expr *Op) {
5932 assert(Op->getType()->isAnyPointerType());
5933 QualType PointeeTy = Op->getType()->getPointeeType();
5934 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5935 return true;
5936
5937 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5938 << PointeeTy << Op->getSourceRange();
5939 return false;
5940}
5941
5942/// \brief Warn when two pointers are incompatible.
5943static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005944 Expr *LHSExpr, Expr *RHSExpr) {
5945 assert(LHSExpr->getType()->isAnyPointerType());
5946 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00005947 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005948 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
5949 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00005950}
5951
Chris Lattnerfaa54172010-01-12 21:23:57 +00005952QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00005953 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
5954 if (LHS.get()->getType()->isVectorType() ||
5955 RHS.get()->getType()->isVectorType()) {
5956 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005957 if (CompLHSTy) *CompLHSTy = compType;
5958 return compType;
5959 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005960
Richard Trieu4ae7e972011-09-06 21:13:51 +00005961 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
5962 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005963 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005964
Steve Naroffe4718892007-04-27 18:30:00 +00005965 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00005966 if (LHS.get()->getType()->isArithmeticType() &&
5967 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005968 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005969 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005970 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005971
Eli Friedman8e122982008-05-18 18:08:51 +00005972 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00005973 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005974 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005975 std::swap(PExp, IExp);
5976
Steve Naroff6b712a72009-07-14 18:25:06 +00005977 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005978 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005979 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5980 return QualType();
5981
Chris Lattner12bdebb2009-04-24 23:50:08 +00005982 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00005983 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
Chris Lattner12bdebb2009-04-24 23:50:08 +00005984 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005985
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005986 // Check array bounds for pointer arithemtic
5987 CheckArrayAccess(PExp, IExp);
5988
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005989 if (CompLHSTy) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005990 QualType LHSTy = Context.isPromotableBitField(LHS.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005991 if (LHSTy.isNull()) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005992 LHSTy = LHS.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005993 if (LHSTy->isPromotableIntegerType())
5994 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005995 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005996 *CompLHSTy = LHSTy;
5997 }
Eli Friedman8e122982008-05-18 18:08:51 +00005998 return PExp->getType();
5999 }
6000 }
6001
Richard Trieu4ae7e972011-09-06 21:13:51 +00006002 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006003}
6004
Chris Lattner2a3569b2008-04-07 05:30:13 +00006005// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006006QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006007 SourceLocation Loc,
6008 QualType* CompLHSTy) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006009 if (LHS.get()->getType()->isVectorType() ||
6010 RHS.get()->getType()->isVectorType()) {
6011 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006012 if (CompLHSTy) *CompLHSTy = compType;
6013 return compType;
6014 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006015
Richard Trieu4ae7e972011-09-06 21:13:51 +00006016 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6017 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006018 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006019
Chris Lattner4d62f422007-12-09 21:53:25 +00006020 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006021
Chris Lattner4d62f422007-12-09 21:53:25 +00006022 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006023 if (LHS.get()->getType()->isArithmeticType() &&
6024 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006025 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006026 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006027 }
Mike Stump11289f42009-09-09 15:08:12 +00006028
Chris Lattner4d62f422007-12-09 21:53:25 +00006029 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006030 if (LHS.get()->getType()->isAnyPointerType()) {
6031 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006032
Chris Lattner12bdebb2009-04-24 23:50:08 +00006033 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006034 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006035 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006036
Chris Lattner4d62f422007-12-09 21:53:25 +00006037 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006038 if (RHS.get()->getType()->isIntegerType()) {
6039 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006040 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006041
Richard Trieu4ae7e972011-09-06 21:13:51 +00006042 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006043 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6044 OK_Ordinary, IExpr->getExprLoc());
6045 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006046 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006047
Richard Trieu4ae7e972011-09-06 21:13:51 +00006048 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6049 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006050 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006051
Chris Lattner4d62f422007-12-09 21:53:25 +00006052 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006053 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006054 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006055 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006056
Eli Friedman168fe152009-05-16 13:54:38 +00006057 if (getLangOptions().CPlusPlus) {
6058 // Pointee types must be the same: C++ [expr.add]
6059 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006060 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006061 }
6062 } else {
6063 // Pointee types must be compatible C99 6.5.6p3
6064 if (!Context.typesAreCompatible(
6065 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6066 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006067 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006068 return QualType();
6069 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006070 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006071
Chandler Carruthc9332212011-06-27 08:02:19 +00006072 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006073 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006074 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006075
Richard Trieu4ae7e972011-09-06 21:13:51 +00006076 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006077 return Context.getPointerDiffType();
6078 }
6079 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006080
Richard Trieu4ae7e972011-09-06 21:13:51 +00006081 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006082}
6083
Douglas Gregor0bf31402010-10-08 23:50:27 +00006084static bool isScopedEnumerationType(QualType T) {
6085 if (const EnumType *ET = dyn_cast<EnumType>(T))
6086 return ET->getDecl()->isScoped();
6087 return false;
6088}
6089
Richard Trieue4a19fb2011-09-06 21:21:28 +00006090static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006091 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006092 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006093 llvm::APSInt Right;
6094 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006095 if (RHS.get()->isValueDependent() ||
6096 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006097 return;
6098
6099 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006100 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006101 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006102 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006103 return;
6104 }
6105 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006106 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006107 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006108 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006109 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006110 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006111 return;
6112 }
6113 if (Opc != BO_Shl)
6114 return;
6115
6116 // When left shifting an ICE which is signed, we can check for overflow which
6117 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6118 // integers have defined behavior modulo one more than the maximum value
6119 // representable in the result type, so never warn for those.
6120 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006121 if (LHS.get()->isValueDependent() ||
6122 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6123 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006124 return;
6125 llvm::APInt ResultBits =
6126 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6127 if (LeftBits.uge(ResultBits))
6128 return;
6129 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6130 Result = Result.shl(Right);
6131
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006132 // Print the bit representation of the signed integer as an unsigned
6133 // hexadecimal number.
6134 llvm::SmallString<40> HexResult;
6135 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6136
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006137 // If we are only missing a sign bit, this is less likely to result in actual
6138 // bugs -- if the result is cast back to an unsigned type, it will have the
6139 // expected value. Thus we place this behind a different warning that can be
6140 // turned off separately if needed.
6141 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006142 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006143 << HexResult.str() << LHSType
6144 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006145 return;
6146 }
6147
6148 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006149 << HexResult.str() << Result.getMinSignedBits() << LHSType
6150 << Left.getBitWidth() << LHS.get()->getSourceRange()
6151 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006152}
6153
Chris Lattner2a3569b2008-04-07 05:30:13 +00006154// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006155QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006156 SourceLocation Loc, unsigned Opc,
6157 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006158 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006159 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6160 !RHS.get()->getType()->hasIntegerRepresentation())
6161 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006162
Douglas Gregor0bf31402010-10-08 23:50:27 +00006163 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6164 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006165 if (isScopedEnumerationType(LHS.get()->getType()) ||
6166 isScopedEnumerationType(RHS.get()->getType())) {
6167 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006168 }
6169
Nate Begemane46ee9a2009-10-25 02:26:48 +00006170 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006171 if (LHS.get()->getType()->isVectorType() ||
6172 RHS.get()->getType()->isVectorType())
6173 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006174
Chris Lattner5c11c412007-12-12 05:47:28 +00006175 // Shifts don't perform usual arithmetic conversions, they just do integer
6176 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006177
John McCall57cdd882010-12-16 19:28:59 +00006178 // For the LHS, do usual unary conversions, but then reset them away
6179 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006180 ExprResult OldLHS = LHS;
6181 LHS = UsualUnaryConversions(LHS.take());
6182 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006183 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006184 QualType LHSType = LHS.get()->getType();
6185 if (isCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006186
6187 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006188 RHS = UsualUnaryConversions(RHS.take());
6189 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006190 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006191
Ryan Flynnf53fab82009-08-07 16:20:20 +00006192 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006193 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006194
Chris Lattner5c11c412007-12-12 05:47:28 +00006195 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006196 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006197}
6198
Chandler Carruth17773fc2010-07-10 12:30:03 +00006199static bool IsWithinTemplateSpecialization(Decl *D) {
6200 if (DeclContext *DC = D->getDeclContext()) {
6201 if (isa<ClassTemplateSpecializationDecl>(DC))
6202 return true;
6203 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6204 return FD->isFunctionTemplateSpecialization();
6205 }
6206 return false;
6207}
6208
Richard Trieueea56f72011-09-02 03:48:46 +00006209/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006210static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6211 ExprResult &RHS) {
6212 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6213 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006214
6215 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6216 if (!LHSEnumType)
6217 return;
6218 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6219 if (!RHSEnumType)
6220 return;
6221
6222 // Ignore anonymous enums.
6223 if (!LHSEnumType->getDecl()->getIdentifier())
6224 return;
6225 if (!RHSEnumType->getDecl()->getIdentifier())
6226 return;
6227
6228 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6229 return;
6230
6231 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6232 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006233 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006234}
6235
Richard Trieudd82a5c2011-09-02 02:55:45 +00006236/// \brief Diagnose bad pointer comparisons.
6237static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006238 ExprResult &LHS, ExprResult &RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006239 bool isError) {
6240 S.Diag(Loc, isError ? diag::err_typecheck_comparison_of_distinct_pointers
6241 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006242 << LHS.get()->getType() << RHS.get()->getType()
6243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006244}
6245
6246/// \brief Returns false if the pointers are converted to a composite type,
6247/// true otherwise.
6248static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006249 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006250 // C++ [expr.rel]p2:
6251 // [...] Pointer conversions (4.10) and qualification
6252 // conversions (4.4) are performed on pointer operands (or on
6253 // a pointer operand and a null pointer constant) to bring
6254 // them to their composite pointer type. [...]
6255 //
6256 // C++ [expr.eq]p1 uses the same notion for (in)equality
6257 // comparisons of pointers.
6258
6259 // C++ [expr.eq]p2:
6260 // In addition, pointers to members can be compared, or a pointer to
6261 // member and a null pointer constant. Pointer to member conversions
6262 // (4.11) and qualification conversions (4.4) are performed to bring
6263 // them to a common type. If one operand is a null pointer constant,
6264 // the common type is the type of the other operand. Otherwise, the
6265 // common type is a pointer to member type similar (4.4) to the type
6266 // of one of the operands, with a cv-qualification signature (4.4)
6267 // that is the union of the cv-qualification signatures of the operand
6268 // types.
6269
Richard Trieu1762d7c2011-09-06 21:27:33 +00006270 QualType LHSType = LHS.get()->getType();
6271 QualType RHSType = RHS.get()->getType();
6272 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6273 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006274
6275 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006276 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006277 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006278 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006279 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006280 return true;
6281 }
6282
6283 if (NonStandardCompositeType)
6284 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006285 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6286 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006287
Richard Trieu1762d7c2011-09-06 21:27:33 +00006288 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6289 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006290 return false;
6291}
6292
6293static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006294 ExprResult &LHS,
6295 ExprResult &RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006296 bool isError) {
6297 S.Diag(Loc,isError ? diag::err_typecheck_comparison_of_fptr_to_void
6298 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006299 << LHS.get()->getType() << RHS.get()->getType()
6300 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006301}
6302
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006303// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006304QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006305 SourceLocation Loc, unsigned OpaqueOpc,
6306 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006307 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006308
Chris Lattner9a152e22009-12-05 05:40:13 +00006309 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006310 if (LHS.get()->getType()->isVectorType() ||
6311 RHS.get()->getType()->isVectorType())
6312 return CheckVectorCompareOperands(LHS, RHS, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006313
Richard Trieub80728f2011-09-06 21:43:51 +00006314 QualType LHSType = LHS.get()->getType();
6315 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006316
Richard Trieub80728f2011-09-06 21:43:51 +00006317 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6318 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006319
Richard Trieub80728f2011-09-06 21:43:51 +00006320 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006321
Richard Trieub80728f2011-09-06 21:43:51 +00006322 if (!LHSType->hasFloatingRepresentation() &&
6323 !(LHSType->isBlockPointerType() && isRelational) &&
6324 !LHS.get()->getLocStart().isMacroID() &&
6325 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006326 // For non-floating point types, check for self-comparisons of the form
6327 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6328 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006329 //
6330 // NOTE: Don't warn about comparison expressions resulting from macro
6331 // expansion. Also don't warn about comparisons which are only self
6332 // comparisons within a template specialization. The warnings should catch
6333 // obvious cases in the definition of the template anyways. The idea is to
6334 // warn when the typed comparison operator will always evaluate to the same
6335 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006336 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006337 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006338 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006339 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006340 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006341 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006342 << (Opc == BO_EQ
6343 || Opc == BO_LE
6344 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006345 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006346 !DRL->getDecl()->getType()->isReferenceType() &&
6347 !DRR->getDecl()->getType()->isReferenceType()) {
6348 // what is it always going to eval to?
6349 char always_evals_to;
6350 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006351 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006352 always_evals_to = 0; // false
6353 break;
John McCalle3027922010-08-25 11:45:40 +00006354 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006355 always_evals_to = 1; // true
6356 break;
6357 default:
6358 // best we can say is 'a constant'
6359 always_evals_to = 2; // e.g. array1 <= array2
6360 break;
6361 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006362 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006363 << 1 // array
6364 << always_evals_to);
6365 }
6366 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006367 }
Mike Stump11289f42009-09-09 15:08:12 +00006368
Chris Lattner222b8bd2009-03-08 19:39:53 +00006369 if (isa<CastExpr>(LHSStripped))
6370 LHSStripped = LHSStripped->IgnoreParenCasts();
6371 if (isa<CastExpr>(RHSStripped))
6372 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006373
Chris Lattner222b8bd2009-03-08 19:39:53 +00006374 // Warn about comparisons against a string constant (unless the other
6375 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006376 Expr *literalString = 0;
6377 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006378 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006379 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006380 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006381 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006382 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006383 } else if ((isa<StringLiteral>(RHSStripped) ||
6384 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006385 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006386 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006387 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006388 literalStringStripped = RHSStripped;
6389 }
6390
6391 if (literalString) {
6392 std::string resultComparison;
6393 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006394 case BO_LT: resultComparison = ") < 0"; break;
6395 case BO_GT: resultComparison = ") > 0"; break;
6396 case BO_LE: resultComparison = ") <= 0"; break;
6397 case BO_GE: resultComparison = ") >= 0"; break;
6398 case BO_EQ: resultComparison = ") == 0"; break;
6399 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006400 default: assert(false && "Invalid comparison operator");
6401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006402
Ted Kremenek3427fac2011-02-23 01:52:04 +00006403 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006404 PDiag(diag::warn_stringcompare)
6405 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006406 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006407 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006408 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006409
Douglas Gregorec170db2010-06-08 19:50:34 +00006410 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006411 if (LHS.get()->getType()->isArithmeticType() &&
6412 RHS.get()->getType()->isArithmeticType()) {
6413 UsualArithmeticConversions(LHS, RHS);
6414 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006415 return QualType();
6416 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006417 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006418 LHS = UsualUnaryConversions(LHS.take());
6419 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006420 return QualType();
6421
Richard Trieub80728f2011-09-06 21:43:51 +00006422 RHS = UsualUnaryConversions(RHS.take());
6423 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006424 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006425 }
6426
Richard Trieub80728f2011-09-06 21:43:51 +00006427 LHSType = LHS.get()->getType();
6428 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006429
Douglas Gregorca63811b2008-11-19 03:25:36 +00006430 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006431 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006432
Chris Lattnerb620c342007-08-26 01:18:55 +00006433 if (isRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006434 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006435 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006436 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006437 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006438 if (LHSType->hasFloatingRepresentation())
6439 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006440
Richard Trieub80728f2011-09-06 21:43:51 +00006441 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006442 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006443 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006444
Richard Trieub80728f2011-09-06 21:43:51 +00006445 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006446 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006447 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006448 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006449
Douglas Gregorf267edd2010-06-15 21:38:40 +00006450 // All of the following pointer-related warnings are GCC extensions, except
6451 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006452 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006453 QualType LCanPointeeTy =
Richard Trieub80728f2011-09-06 21:43:51 +00006454 Context.getCanonicalType(LHSType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006455 QualType RCanPointeeTy =
Richard Trieub80728f2011-09-06 21:43:51 +00006456 Context.getCanonicalType(RHSType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006457
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006458 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006459 if (LCanPointeeTy == RCanPointeeTy)
6460 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006461 if (!isRelational &&
6462 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6463 // Valid unless comparison between non-null pointer and function pointer
6464 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006465 // In a SFINAE context, we treat this as a hard error to maintain
6466 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006467 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6468 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006469 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006470 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006471
6472 if (isSFINAEContext())
6473 return QualType();
6474
Richard Trieub80728f2011-09-06 21:43:51 +00006475 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006476 return ResultTy;
6477 }
6478 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006479
Richard Trieub80728f2011-09-06 21:43:51 +00006480 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006481 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006482 else
6483 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006484 }
Eli Friedman16c209612009-08-23 00:27:47 +00006485 // C99 6.5.9p2 and C99 6.5.8p2
6486 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6487 RCanPointeeTy.getUnqualifiedType())) {
6488 // Valid unless a relational comparison of function pointers
6489 if (isRelational && LCanPointeeTy->isFunctionType()) {
6490 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006491 << LHSType << RHSType << LHS.get()->getSourceRange()
6492 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006493 }
6494 } else if (!isRelational &&
6495 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6496 // Valid unless comparison between non-null pointer and function pointer
6497 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006498 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006499 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006500 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006501 } else {
6502 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006503 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006504 }
John McCall7684dde2011-03-11 04:25:25 +00006505 if (LCanPointeeTy != RCanPointeeTy) {
6506 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006507 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006508 else
Richard Trieub80728f2011-09-06 21:43:51 +00006509 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006510 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006511 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006512 }
Mike Stump11289f42009-09-09 15:08:12 +00006513
Sebastian Redl576fd422009-05-10 18:38:11 +00006514 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006515 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006516 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006517 return ResultTy;
6518
Mike Stump11289f42009-09-09 15:08:12 +00006519 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006520 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006521 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006522 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006523 (!isRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006524 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6525 RHS = ImpCastExprToType(RHS.take(), LHSType,
6526 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006527 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006528 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006529 return ResultTy;
6530 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006531 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006532 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006533 (!isRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006534 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6535 LHS = ImpCastExprToType(LHS.take(), RHSType,
6536 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006537 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006538 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006539 return ResultTy;
6540 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006541
6542 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006543 if (!isRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006544 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6545 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006546 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006547 else
6548 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006549 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006550
6551 // Handle scoped enumeration types specifically, since they don't promote
6552 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006553 if (LHS.get()->getType()->isEnumeralType() &&
6554 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6555 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006556 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006557 }
Mike Stump11289f42009-09-09 15:08:12 +00006558
Steve Naroff081c7422008-09-04 15:10:53 +00006559 // Handle block pointer types.
Richard Trieub80728f2011-09-06 21:43:51 +00006560 if (!isRelational && LHSType->isBlockPointerType() &&
6561 RHSType->isBlockPointerType()) {
6562 QualType lpointee = LHSType->getAs<BlockPointerType>()->getPointeeType();
6563 QualType rpointee = RHSType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006564
Steve Naroff081c7422008-09-04 15:10:53 +00006565 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006566 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006567 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006568 << LHSType << RHSType << LHS.get()->getSourceRange()
6569 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006570 }
Richard Trieub80728f2011-09-06 21:43:51 +00006571 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006572 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006573 }
John Wiegley01296292011-04-08 18:41:53 +00006574
Steve Naroffe18f94c2008-09-28 01:11:11 +00006575 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006576 if (!isRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006577 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6578 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006579 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006580 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006581 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006582 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006583 ->getPointeeType()->isVoidType())))
6584 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006585 << LHSType << RHSType << LHS.get()->getSourceRange()
6586 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006587 }
John McCall7684dde2011-03-11 04:25:25 +00006588 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006589 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006590 else
Richard Trieub80728f2011-09-06 21:43:51 +00006591 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006592 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006593 }
Steve Naroff081c7422008-09-04 15:10:53 +00006594
Richard Trieub80728f2011-09-06 21:43:51 +00006595 if (LHSType->isObjCObjectPointerType() ||
6596 RHSType->isObjCObjectPointerType()) {
6597 const PointerType *LPT = LHSType->getAs<PointerType>();
6598 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006599 if (LPT || RPT) {
6600 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6601 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006602
Steve Naroff753567f2008-11-17 19:49:16 +00006603 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006604 !Context.typesAreCompatible(LHSType, RHSType)) {
6605 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006606 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006607 }
John McCall7684dde2011-03-11 04:25:25 +00006608 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006609 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006610 else
Richard Trieub80728f2011-09-06 21:43:51 +00006611 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006612 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006613 }
Richard Trieub80728f2011-09-06 21:43:51 +00006614 if (LHSType->isObjCObjectPointerType() &&
6615 RHSType->isObjCObjectPointerType()) {
6616 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6617 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006618 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006619 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006620 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006621 else
Richard Trieub80728f2011-09-06 21:43:51 +00006622 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006623 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006624 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006625 }
Richard Trieub80728f2011-09-06 21:43:51 +00006626 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6627 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006628 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006629 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006630 if ((LHSIsNull && LHSType->isIntegerType()) ||
6631 (RHSIsNull && RHSType->isIntegerType())) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006632 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006633 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006634 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006635 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006636 else if (getLangOptions().CPlusPlus) {
6637 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6638 isError = true;
6639 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006640 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006641
Chris Lattnerd99bd522009-08-23 00:03:44 +00006642 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006643 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006644 << LHSType << RHSType << LHS.get()->getSourceRange()
6645 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006646 if (isError)
6647 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006648 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006649
Richard Trieub80728f2011-09-06 21:43:51 +00006650 if (LHSType->isIntegerType())
6651 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006652 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006653 else
Richard Trieub80728f2011-09-06 21:43:51 +00006654 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006655 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006656 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006657 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006658
Steve Naroff4b191572008-09-04 16:56:14 +00006659 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006660 if (!isRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006661 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6662 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006663 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006664 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006665 if (!isRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006666 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6667 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006668 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006669 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006670
Richard Trieub80728f2011-09-06 21:43:51 +00006671 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006672}
6673
Nate Begeman191a6b12008-07-14 18:02:46 +00006674/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006675/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006676/// like a scalar comparison, a vector comparison produces a vector of integer
6677/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006678QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006679 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006680 bool isRelational) {
6681 // Check to make sure we're operating on vectors of the same type and width,
6682 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006683 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006684 if (vType.isNull())
6685 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006686
Richard Trieubcce2f72011-09-07 01:19:57 +00006687 QualType LHSType = LHS.get()->getType();
6688 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006689
Anton Yartsev530deb92011-03-27 15:36:07 +00006690 // If AltiVec, the comparison results in a numeric type, i.e.
6691 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006692 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006693 return Context.getLogicalOperationType();
6694
Nate Begeman191a6b12008-07-14 18:02:46 +00006695 // For non-floating point types, check for self-comparisons of the form
6696 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6697 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006698 if (!LHSType->hasFloatingRepresentation()) {
6699 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6700 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006701 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006702 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006703 PDiag(diag::warn_comparison_always)
6704 << 0 // self-
6705 << 2 // "a constant"
6706 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006707 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006708
Nate Begeman191a6b12008-07-14 18:02:46 +00006709 // Check for comparisons of floating point operands using != and ==.
Richard Trieubcce2f72011-09-07 01:19:57 +00006710 if (!isRelational && LHSType->hasFloatingRepresentation()) {
6711 assert (RHSType->hasFloatingRepresentation());
6712 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006713 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006714
Nate Begeman191a6b12008-07-14 18:02:46 +00006715 // Return the type for the comparison, which is the same as vector type for
6716 // integer vectors, or an integer type of identical size and number of
6717 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006718 if (LHSType->hasIntegerRepresentation())
6719 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006720
Richard Trieubcce2f72011-09-07 01:19:57 +00006721 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006722 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006723 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006724 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006725 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006726 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6727
Mike Stump4e1f26a2009-02-19 03:04:26 +00006728 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006729 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006730 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6731}
6732
Steve Naroff218bc2b2007-05-04 21:54:46 +00006733inline QualType Sema::CheckBitwiseOperands(
Richard Trieubcce2f72011-09-07 01:19:57 +00006734 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool isCompAssign) {
6735 if (LHS.get()->getType()->isVectorType() ||
6736 RHS.get()->getType()->isVectorType()) {
6737 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6738 RHS.get()->getType()->hasIntegerRepresentation())
6739 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006740
Richard Trieubcce2f72011-09-07 01:19:57 +00006741 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006742 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006743
Richard Trieubcce2f72011-09-07 01:19:57 +00006744 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6745 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieucfc491d2011-08-02 04:35:43 +00006746 isCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006747 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006748 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006749 LHS = LHSResult.take();
6750 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006751
Richard Trieubcce2f72011-09-07 01:19:57 +00006752 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6753 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006754 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006755 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006756}
6757
Steve Naroff218bc2b2007-05-04 21:54:46 +00006758inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006759 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006760
6761 // Diagnose cases where the user write a logical and/or but probably meant a
6762 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6763 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006764 if (LHS.get()->getType()->isIntegerType() &&
6765 !LHS.get()->getType()->isBooleanType() &&
6766 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006767 // Don't warn in macros or template instantiations.
6768 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006769 // If the RHS can be constant folded, and if it constant folds to something
6770 // that isn't 0 or 1 (which indicate a potential logical operation that
6771 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006772 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006773 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006774 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6775 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006776 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6777 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006778 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006779 << (Opc == BO_LAnd ? "&&" : "||");
6780 // Suggest replacing the logical operator with the bitwise version
6781 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6782 << (Opc == BO_LAnd ? "&" : "|")
6783 << FixItHint::CreateReplacement(SourceRange(
6784 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6785 getLangOptions())),
6786 Opc == BO_LAnd ? "&" : "|");
6787 if (Opc == BO_LAnd)
6788 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6789 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6790 << FixItHint::CreateRemoval(
6791 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006792 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006793 0, getSourceManager(),
6794 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006795 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006796 }
Chris Lattner938533d2010-07-24 01:10:11 +00006797 }
Chris Lattner8406c512010-07-13 19:41:32 +00006798
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006799 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006800 LHS = UsualUnaryConversions(LHS.take());
6801 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006802 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006803
Richard Trieubcce2f72011-09-07 01:19:57 +00006804 RHS = UsualUnaryConversions(RHS.take());
6805 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006806 return QualType();
6807
Richard Trieubcce2f72011-09-07 01:19:57 +00006808 if (!LHS.get()->getType()->isScalarType() ||
6809 !RHS.get()->getType()->isScalarType())
6810 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006811
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006812 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006813 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006814
John McCall4a2429a2010-06-04 00:29:51 +00006815 // The following is safe because we only use this method for
6816 // non-overloadable operands.
6817
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006818 // C++ [expr.log.and]p1
6819 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006820 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006821 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6822 if (LHSRes.isInvalid())
6823 return InvalidOperands(Loc, LHS, RHS);
6824 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006825
Richard Trieubcce2f72011-09-07 01:19:57 +00006826 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6827 if (RHSRes.isInvalid())
6828 return InvalidOperands(Loc, LHS, RHS);
6829 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006830
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006831 // C++ [expr.log.and]p2
6832 // C++ [expr.log.or]p2
6833 // The result is a bool.
6834 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006835}
6836
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006837/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6838/// is a read-only property; return true if so. A readonly property expression
6839/// depends on various declarations and thus must be treated specially.
6840///
Mike Stump11289f42009-09-09 15:08:12 +00006841static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006842 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6843 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006844 if (PropExpr->isImplicitProperty()) return false;
6845
6846 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6847 QualType BaseType = PropExpr->isSuperReceiver() ?
6848 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006849 PropExpr->getBase()->getType();
6850
John McCallb7bd14f2010-12-02 01:19:52 +00006851 if (const ObjCObjectPointerType *OPT =
6852 BaseType->getAsObjCInterfacePointerType())
6853 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6854 if (S.isPropertyReadonly(PDecl, IFace))
6855 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006856 }
6857 return false;
6858}
6859
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006860static bool IsConstProperty(Expr *E, Sema &S) {
6861 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6862 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6863 if (PropExpr->isImplicitProperty()) return false;
6864
6865 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6866 QualType T = PDecl->getType();
6867 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006868 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006869 CanQualType CT = S.Context.getCanonicalType(T);
6870 return CT.isConstQualified();
6871 }
6872 return false;
6873}
6874
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006875static bool IsReadonlyMessage(Expr *E, Sema &S) {
6876 if (E->getStmtClass() != Expr::MemberExprClass)
6877 return false;
6878 const MemberExpr *ME = cast<MemberExpr>(E);
6879 NamedDecl *Member = ME->getMemberDecl();
6880 if (isa<FieldDecl>(Member)) {
6881 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6882 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6883 return false;
6884 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6885 }
6886 return false;
6887}
6888
Chris Lattner30bd3272008-11-18 01:22:49 +00006889/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6890/// emit an error and return true. If so, return false.
6891static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006892 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006893 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006894 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006895 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6896 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006897 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6898 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006899 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6900 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006901 if (IsLV == Expr::MLV_Valid)
6902 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006903
Chris Lattner30bd3272008-11-18 01:22:49 +00006904 unsigned Diag = 0;
6905 bool NeedType = false;
6906 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006907 case Expr::MLV_ConstQualified:
6908 Diag = diag::err_typecheck_assign_const;
6909
John McCalld4631322011-06-17 06:42:21 +00006910 // In ARC, use some specialized diagnostics for occasions where we
6911 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006912 if (S.getLangOptions().ObjCAutoRefCount) {
6913 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6914 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6915 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6916
John McCalld4631322011-06-17 06:42:21 +00006917 // Use the normal diagnostic if it's pseudo-__strong but the
6918 // user actually wrote 'const'.
6919 if (var->isARCPseudoStrong() &&
6920 (!var->getTypeSourceInfo() ||
6921 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6922 // There are two pseudo-strong cases:
6923 // - self
John McCall31168b02011-06-15 23:02:42 +00006924 ObjCMethodDecl *method = S.getCurMethodDecl();
6925 if (method && var == method->getSelfDecl())
6926 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006927
6928 // - fast enumeration variables
6929 else
John McCall31168b02011-06-15 23:02:42 +00006930 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006931
John McCall31168b02011-06-15 23:02:42 +00006932 SourceRange Assign;
6933 if (Loc != OrigLoc)
6934 Assign = SourceRange(OrigLoc, OrigLoc);
6935 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6936 // We need to preserve the AST regardless, so migration tool
6937 // can do its job.
6938 return false;
6939 }
6940 }
6941 }
6942
6943 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006944 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006945 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6946 NeedType = true;
6947 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006948 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006949 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6950 NeedType = true;
6951 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006952 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006953 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6954 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006955 case Expr::MLV_Valid:
6956 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006957 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006958 case Expr::MLV_MemberFunction:
6959 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006960 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6961 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006962 case Expr::MLV_IncompleteType:
6963 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006964 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006965 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006966 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006967 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006968 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6969 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006970 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006971 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6972 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006973 case Expr::MLV_ReadonlyProperty:
6974 Diag = diag::error_readonly_property_assignment;
6975 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006976 case Expr::MLV_NoSetterProperty:
6977 Diag = diag::error_nosetter_property_assignment;
6978 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006979 case Expr::MLV_InvalidMessageExpression:
6980 Diag = diag::error_readonly_message_assignment;
6981 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006982 case Expr::MLV_SubObjCPropertySetting:
6983 Diag = diag::error_no_subobject_property_setting;
6984 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006985 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006986
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006987 SourceRange Assign;
6988 if (Loc != OrigLoc)
6989 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006990 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006991 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006992 else
Mike Stump11289f42009-09-09 15:08:12 +00006993 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006994 return true;
6995}
6996
6997
6998
6999// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007000QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007001 SourceLocation Loc,
7002 QualType CompoundType) {
7003 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007004 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007005 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007006
Richard Trieuda4f43a62011-09-07 01:33:52 +00007007 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007008 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7009 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007010 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007011 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007012 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007013 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007014 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7015 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007016 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7017 if (LHSResult.isInvalid())
7018 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007019 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007020 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007021 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007022 if (RHS.isInvalid())
7023 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007024 // Special case of NSObject attributes on c-style pointer types.
7025 if (ConvTy == IncompatiblePointer &&
7026 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007027 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007028 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007029 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007030 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007031
John McCall7decc9e2010-11-18 06:31:45 +00007032 if (ConvTy == Compatible &&
7033 getLangOptions().ObjCNonFragileABI &&
7034 LHSType->isObjCObjectType())
7035 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7036 << LHSType;
7037
Chris Lattnerea714382008-08-21 18:04:13 +00007038 // If the RHS is a unary plus or minus, check to see if they = and + are
7039 // right next to each other. If so, the user may have typo'd "x =+ 4"
7040 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007041 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007042 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7043 RHSCheck = ICE->getSubExpr();
7044 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007045 if ((UO->getOpcode() == UO_Plus ||
7046 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007047 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007048 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007049 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7050 // And there is a space or other character before the subexpr of the
7051 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007052 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7053 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007054 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007055 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007056 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007057 }
Chris Lattnerea714382008-08-21 18:04:13 +00007058 }
John McCall31168b02011-06-15 23:02:42 +00007059
7060 if (ConvTy == Compatible) {
7061 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007062 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007063 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007064 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007065 }
Chris Lattnerea714382008-08-21 18:04:13 +00007066 } else {
7067 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007068 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007069 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007070
Chris Lattner326f7572008-11-18 01:30:42 +00007071 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007072 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007073 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007074
Richard Trieuda4f43a62011-09-07 01:33:52 +00007075 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007076
Steve Naroff98cf3e92007-06-06 18:38:38 +00007077 // C99 6.5.16p3: The type of an assignment expression is the type of the
7078 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007079 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007080 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7081 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007082 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007083 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007084 return (getLangOptions().CPlusPlus
7085 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007086}
7087
Chris Lattner326f7572008-11-18 01:30:42 +00007088// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007089static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007090 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007091 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007092
John McCall3aef3d82011-04-10 19:13:55 +00007093 LHS = S.CheckPlaceholderExpr(LHS.take());
7094 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007095 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007096 return QualType();
7097
John McCall73d36182010-10-12 07:14:40 +00007098 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7099 // operands, but not unary promotions.
7100 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007101
John McCall34376a62010-12-04 03:47:34 +00007102 // So we treat the LHS as a ignored value, and in C++ we allow the
7103 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007104 LHS = S.IgnoredValueConversions(LHS.take());
7105 if (LHS.isInvalid())
7106 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007107
7108 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007109 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7110 if (RHS.isInvalid())
7111 return QualType();
7112 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007113 S.RequireCompleteType(Loc, RHS.get()->getType(),
7114 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007115 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007116
John Wiegley01296292011-04-08 18:41:53 +00007117 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007118}
7119
Steve Naroff7a5af782007-07-13 16:58:59 +00007120/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7121/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007122static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7123 ExprValueKind &VK,
7124 SourceLocation OpLoc,
7125 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007126 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007127 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007128
Chris Lattner6b0cf142008-11-21 07:05:48 +00007129 QualType ResType = Op->getType();
7130 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007131
John McCall4bc41ae2010-11-18 19:01:18 +00007132 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007133 // Decrement of bool is not allowed.
7134 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007135 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007136 return QualType();
7137 }
7138 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007139 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007140 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007141 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007142 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007143 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007144 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007145 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007146
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007147 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007148 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007149 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007150 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007151 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007152 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007153 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007154 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007155 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007156 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007157 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7158 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007159 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7160 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007161 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007162 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007163 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007164 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007165 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007166 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007167 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007168 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007169 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007170 // In C++, a prefix increment is the same type as the operand. Otherwise
7171 // (in C or with postfix), the increment is the unqualified type of the
7172 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007173 if (isPrefix && S.getLangOptions().CPlusPlus) {
7174 VK = VK_LValue;
7175 return ResType;
7176 } else {
7177 VK = VK_RValue;
7178 return ResType.getUnqualifiedType();
7179 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007180}
7181
John Wiegley01296292011-04-08 18:41:53 +00007182ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007183 assert(E->getValueKind() == VK_LValue &&
7184 E->getObjectKind() == OK_ObjCProperty);
7185 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7186
Douglas Gregor33823722011-06-11 01:09:30 +00007187 QualType T = E->getType();
7188 QualType ReceiverType;
7189 if (PRE->isObjectReceiver())
7190 ReceiverType = PRE->getBase()->getType();
7191 else if (PRE->isSuperReceiver())
7192 ReceiverType = PRE->getSuperReceiverType();
7193 else
7194 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7195
John McCall34376a62010-12-04 03:47:34 +00007196 ExprValueKind VK = VK_RValue;
7197 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007198 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007199 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007200 T = getMessageSendResultType(ReceiverType, GetterMethod,
7201 PRE->isClassReceiver(),
7202 PRE->isSuperReceiver());
7203 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007204 }
7205 else {
7206 Diag(PRE->getLocation(), diag::err_getter_not_found)
7207 << PRE->getBase()->getType();
7208 }
John McCall34376a62010-12-04 03:47:34 +00007209 }
Douglas Gregor33823722011-06-11 01:09:30 +00007210
7211 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007212 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007213
7214 ExprResult Result = MaybeBindToTemporary(E);
7215 if (!Result.isInvalid())
7216 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007217
7218 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007219}
7220
Richard Trieucfc491d2011-08-02 04:35:43 +00007221void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7222 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007223 assert(LHS.get()->getValueKind() == VK_LValue &&
7224 LHS.get()->getObjectKind() == OK_ObjCProperty);
7225 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007226
John McCall31168b02011-06-15 23:02:42 +00007227 bool Consumed = false;
7228
John Wiegley01296292011-04-08 18:41:53 +00007229 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007230 // If using property-dot syntax notation for assignment, and there is a
7231 // setter, RHS expression is being passed to the setter argument. So,
7232 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007233 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007234 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7235 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007236 Consumed = (getLangOptions().ObjCAutoRefCount &&
7237 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007238
7239 // Otherwise, if the getter returns an l-value, just call that.
7240 } else {
John Wiegley01296292011-04-08 18:41:53 +00007241 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007242 ExprValueKind VK = Expr::getValueKindForType(Result);
7243 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007244 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7245 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007246 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007247 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007248 }
John McCall31168b02011-06-15 23:02:42 +00007249 } else if (getLangOptions().ObjCAutoRefCount) {
7250 const ObjCMethodDecl *setter
7251 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7252 if (setter) {
7253 ObjCMethodDecl::param_iterator P = setter->param_begin();
7254 LHSTy = (*P)->getType();
7255 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7256 }
John McCall34376a62010-12-04 03:47:34 +00007257 }
7258
John McCall31168b02011-06-15 23:02:42 +00007259 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7260 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007261 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007262 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007263 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007264 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007265 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007266 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7267 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7268 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007269 }
7270}
7271
7272
Anders Carlsson806700f2008-02-01 07:15:58 +00007273/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007274/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007275/// where the declaration is needed for type checking. We only need to
7276/// handle cases when the expression references a function designator
7277/// or is an lvalue. Here are some examples:
7278/// - &(x) => x
7279/// - &*****f => f for f a function designator.
7280/// - &s.xx => s
7281/// - &s.zz[1].yy -> s, if zz is an array
7282/// - *(x + 1) -> x, if x is an array
7283/// - &"123"[2] -> 0
7284/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007285static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007286 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007287 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007288 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007289 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007290 // If this is an arrow operator, the address is an offset from
7291 // the base's value, so the object the base refers to is
7292 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007293 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007294 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007295 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007296 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007297 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007298 // FIXME: This code shouldn't be necessary! We should catch the implicit
7299 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007300 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7301 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7302 if (ICE->getSubExpr()->getType()->isArrayType())
7303 return getPrimaryDecl(ICE->getSubExpr());
7304 }
7305 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007306 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007307 case Stmt::UnaryOperatorClass: {
7308 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007309
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007310 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007311 case UO_Real:
7312 case UO_Imag:
7313 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007314 return getPrimaryDecl(UO->getSubExpr());
7315 default:
7316 return 0;
7317 }
7318 }
Steve Naroff47500512007-04-19 23:00:49 +00007319 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007320 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007321 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007322 // If the result of an implicit cast is an l-value, we care about
7323 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007324 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007325 default:
7326 return 0;
7327 }
7328}
7329
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007330/// \brief Diagnose invalid operand for address of operations.
7331///
7332/// \param Type The type of operand which cannot have its address taken.
7333/// 0:bit-field 1:vector element 2:property expression 3:register variable
7334static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7335 Expr *E, unsigned Type) {
7336 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7337}
7338
Steve Naroff47500512007-04-19 23:00:49 +00007339/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007340/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007341/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007342/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007343/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007344/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007345/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007346static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7347 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007348 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007349 return S.Context.DependentTy;
7350 if (OrigOp->getType() == S.Context.OverloadTy)
7351 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007352 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7353 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007354 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7355 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7356 << OrigOp->getSourceRange();
7357 return QualType();
7358 }
John McCall8d08b9b2010-08-27 09:08:28 +00007359
John McCall2979fe02011-04-12 00:42:48 +00007360 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007361
John McCall8d08b9b2010-08-27 09:08:28 +00007362 // Make sure to ignore parentheses in subsequent checks
7363 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007364
John McCall4bc41ae2010-11-18 19:01:18 +00007365 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007366 // Implement C99-only parts of addressof rules.
7367 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007368 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007369 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7370 // (assuming the deref expression is valid).
7371 return uOp->getSubExpr()->getType();
7372 }
7373 // Technically, there should be a check for array subscript
7374 // expressions here, but the result of one is always an lvalue anyway.
7375 }
John McCallf3a88602011-02-03 08:15:49 +00007376 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007377 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007378
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007379 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007380 bool sfinae = S.isSFINAEContext();
7381 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7382 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007383 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007384 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007385 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007386 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007387 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007388 } else if (lval == Expr::LV_MemberFunction) {
7389 // If it's an instance method, make a member pointer.
7390 // The expression must have exactly the form &A::foo.
7391
7392 // If the underlying expression isn't a decl ref, give up.
7393 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007394 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007395 << OrigOp->getSourceRange();
7396 return QualType();
7397 }
7398 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7399 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7400
7401 // The id-expression was parenthesized.
7402 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007403 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007404 << OrigOp->getSourceRange();
7405
7406 // The method was named without a qualifier.
7407 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007408 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007409 << op->getSourceRange();
7410 }
7411
John McCall4bc41ae2010-11-18 19:01:18 +00007412 return S.Context.getMemberPointerType(op->getType(),
7413 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007414 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007415 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007416 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007417 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007418 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007419 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007420 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007421 return QualType();
7422 }
John McCall086a4642010-11-24 05:12:34 +00007423 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007424 // The operand cannot be a bit-field
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007425 diagnoseAddressOfInvalidType(S, OpLoc, op, /*bit-field*/ 0);
7426 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007427 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007428 // The operand cannot be an element of a vector
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007429 diagnoseAddressOfInvalidType(S, OpLoc, op, /*vector element*/ 1);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007430 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007431 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007432 // cannot take address of a property expression.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007433 diagnoseAddressOfInvalidType(S, OpLoc, op, /*property expression*/ 2);
Fariborz Jahanian385db802009-07-07 18:50:52 +00007434 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007435 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007436 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007437 // with the register storage-class specifier.
7438 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007439 // in C++ it is not error to take address of a register
7440 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007441 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007442 !S.getLangOptions().CPlusPlus) {
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007443 diagnoseAddressOfInvalidType(S, OpLoc, op, /*register variable*/ 3);
Steve Naroff35d85152007-05-07 00:24:15 +00007444 return QualType();
7445 }
John McCalld14a8642009-11-21 08:51:07 +00007446 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007447 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007448 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007449 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007450 // Could be a pointer to member, though, if there is an explicit
7451 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007452 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007453 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007454 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007455 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007456 S.Diag(OpLoc,
7457 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007458 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007459 return QualType();
7460 }
Mike Stump11289f42009-09-09 15:08:12 +00007461
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007462 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7463 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007464 return S.Context.getMemberPointerType(op->getType(),
7465 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007466 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007467 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007468 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007469 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007470 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007471
Eli Friedmance7f9002009-05-16 23:27:50 +00007472 if (lval == Expr::LV_IncompleteVoidType) {
7473 // Taking the address of a void variable is technically illegal, but we
7474 // allow it in cases which are otherwise valid.
7475 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007476 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007477 }
7478
Steve Naroff47500512007-04-19 23:00:49 +00007479 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007480 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007481 return S.Context.getObjCObjectPointerType(op->getType());
7482 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007483}
7484
Chris Lattner9156f1b2010-07-05 19:17:26 +00007485/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007486static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7487 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007488 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007489 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007490
John Wiegley01296292011-04-08 18:41:53 +00007491 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7492 if (ConvResult.isInvalid())
7493 return QualType();
7494 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007495 QualType OpTy = Op->getType();
7496 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007497
7498 if (isa<CXXReinterpretCastExpr>(Op)) {
7499 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7500 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7501 Op->getSourceRange());
7502 }
7503
Chris Lattner9156f1b2010-07-05 19:17:26 +00007504 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7505 // is an incomplete type or void. It would be possible to warn about
7506 // dereferencing a void pointer, but it's completely well-defined, and such a
7507 // warning is unlikely to catch any mistakes.
7508 if (const PointerType *PT = OpTy->getAs<PointerType>())
7509 Result = PT->getPointeeType();
7510 else if (const ObjCObjectPointerType *OPT =
7511 OpTy->getAs<ObjCObjectPointerType>())
7512 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007513 else {
John McCall3aef3d82011-04-10 19:13:55 +00007514 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007515 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007516 if (PR.take() != Op)
7517 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007518 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007519
Chris Lattner9156f1b2010-07-05 19:17:26 +00007520 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007521 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007522 << OpTy << Op->getSourceRange();
7523 return QualType();
7524 }
John McCall4bc41ae2010-11-18 19:01:18 +00007525
7526 // Dereferences are usually l-values...
7527 VK = VK_LValue;
7528
7529 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007530 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007531 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007532
7533 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007534}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007535
John McCalle3027922010-08-25 11:45:40 +00007536static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007537 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007538 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007539 switch (Kind) {
7540 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007541 case tok::periodstar: Opc = BO_PtrMemD; break;
7542 case tok::arrowstar: Opc = BO_PtrMemI; break;
7543 case tok::star: Opc = BO_Mul; break;
7544 case tok::slash: Opc = BO_Div; break;
7545 case tok::percent: Opc = BO_Rem; break;
7546 case tok::plus: Opc = BO_Add; break;
7547 case tok::minus: Opc = BO_Sub; break;
7548 case tok::lessless: Opc = BO_Shl; break;
7549 case tok::greatergreater: Opc = BO_Shr; break;
7550 case tok::lessequal: Opc = BO_LE; break;
7551 case tok::less: Opc = BO_LT; break;
7552 case tok::greaterequal: Opc = BO_GE; break;
7553 case tok::greater: Opc = BO_GT; break;
7554 case tok::exclaimequal: Opc = BO_NE; break;
7555 case tok::equalequal: Opc = BO_EQ; break;
7556 case tok::amp: Opc = BO_And; break;
7557 case tok::caret: Opc = BO_Xor; break;
7558 case tok::pipe: Opc = BO_Or; break;
7559 case tok::ampamp: Opc = BO_LAnd; break;
7560 case tok::pipepipe: Opc = BO_LOr; break;
7561 case tok::equal: Opc = BO_Assign; break;
7562 case tok::starequal: Opc = BO_MulAssign; break;
7563 case tok::slashequal: Opc = BO_DivAssign; break;
7564 case tok::percentequal: Opc = BO_RemAssign; break;
7565 case tok::plusequal: Opc = BO_AddAssign; break;
7566 case tok::minusequal: Opc = BO_SubAssign; break;
7567 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7568 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7569 case tok::ampequal: Opc = BO_AndAssign; break;
7570 case tok::caretequal: Opc = BO_XorAssign; break;
7571 case tok::pipeequal: Opc = BO_OrAssign; break;
7572 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007573 }
7574 return Opc;
7575}
7576
John McCalle3027922010-08-25 11:45:40 +00007577static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007578 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007579 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007580 switch (Kind) {
7581 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007582 case tok::plusplus: Opc = UO_PreInc; break;
7583 case tok::minusminus: Opc = UO_PreDec; break;
7584 case tok::amp: Opc = UO_AddrOf; break;
7585 case tok::star: Opc = UO_Deref; break;
7586 case tok::plus: Opc = UO_Plus; break;
7587 case tok::minus: Opc = UO_Minus; break;
7588 case tok::tilde: Opc = UO_Not; break;
7589 case tok::exclaim: Opc = UO_LNot; break;
7590 case tok::kw___real: Opc = UO_Real; break;
7591 case tok::kw___imag: Opc = UO_Imag; break;
7592 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007593 }
7594 return Opc;
7595}
7596
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007597/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7598/// This warning is only emitted for builtin assignment operations. It is also
7599/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007600static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007601 SourceLocation OpLoc) {
7602 if (!S.ActiveTemplateInstantiations.empty())
7603 return;
7604 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7605 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007606 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7607 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7608 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7609 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7610 if (!LHSDeclRef || !RHSDeclRef ||
7611 LHSDeclRef->getLocation().isMacroID() ||
7612 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007613 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007614 const ValueDecl *LHSDecl =
7615 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7616 const ValueDecl *RHSDecl =
7617 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7618 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007619 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007620 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007621 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007622 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007623 if (RefTy->getPointeeType().isVolatileQualified())
7624 return;
7625
7626 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007627 << LHSDeclRef->getType()
7628 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007629}
7630
Richard Trieueea56f72011-09-02 03:48:46 +00007631// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7632// expression. These are mainly cases where the null pointer is used as an
7633// integer instead of a pointer.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007634static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
Richard Trieueea56f72011-09-02 03:48:46 +00007635 SourceLocation Loc, bool isCompare) {
7636 // The canonical way to check for a GNU null is with isNullPointerConstant,
7637 // but we use a bit of a hack here for speed; this is a relatively
7638 // hot path, and isNullPointerConstant is slow.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007639 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7640 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
Richard Trieueea56f72011-09-02 03:48:46 +00007641
7642 // Detect when a NULL constant is used improperly in an expression. These
7643 // are mainly cases where the null pointer is used as an integer instead
7644 // of a pointer.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007645 if (!LHSNull && !RHSNull)
Richard Trieueea56f72011-09-02 03:48:46 +00007646 return;
7647
Richard Trieuda4f43a62011-09-07 01:33:52 +00007648 QualType LHSType = LHS.get()->getType();
7649 QualType RHSType = RHS.get()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00007650
7651 // Avoid analyzing cases where the result will either be invalid (and
7652 // diagnosed as such) or entirely valid and not something to warn about.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007653 if (LHSType->isBlockPointerType() || LHSType->isMemberPointerType() ||
7654 LHSType->isFunctionType() || RHSType->isBlockPointerType() ||
7655 RHSType->isMemberPointerType() || RHSType->isFunctionType())
Richard Trieueea56f72011-09-02 03:48:46 +00007656 return;
7657
7658 // Comparison operations would not make sense with a null pointer no matter
7659 // what the other expression is.
7660 if (!isCompare) {
7661 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007662 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7663 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
Richard Trieueea56f72011-09-02 03:48:46 +00007664 return;
7665 }
7666
7667 // The rest of the operations only make sense with a null pointer
7668 // if the other expression is a pointer.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007669 if (LHSNull == RHSNull || LHSType->isAnyPointerType() ||
7670 LHSType->canDecayToPointerType() || RHSType->isAnyPointerType() ||
7671 RHSType->canDecayToPointerType())
Richard Trieueea56f72011-09-02 03:48:46 +00007672 return;
7673
7674 S.Diag(Loc, diag::warn_null_in_comparison_operation)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007675 << LHSNull /* LHS is NULL */
7676 << (LHSNull ? RHS.get()->getType() : LHS.get()->getType())
7677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00007678}
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007679/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7680/// operator @p Opc at location @c TokLoc. This routine only supports
7681/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007682ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007683 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007684 Expr *lhsExpr, Expr *rhsExpr) {
7685 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007686 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007687 // The following two variables are used for compound assignment operators
7688 QualType CompLHSTy; // Type of LHS after promotions for computation
7689 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007690 ExprValueKind VK = VK_RValue;
7691 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007692
Douglas Gregor1beec452011-03-12 01:48:56 +00007693 // Check if a 'foo<int>' involved in a binary op, identifies a single
7694 // function unambiguously (i.e. an lvalue ala 13.4)
7695 // But since an assignment can trigger target based overload, exclude it in
7696 // our blind search. i.e:
7697 // template<class T> void f(); template<class T, class U> void f(U);
7698 // f<int> == 0; // resolve f<int> blindly
7699 // void (*p)(int); p = f<int>; // resolve f<int> using target
7700 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007701 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007702 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007703 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007704
John McCall3aef3d82011-04-10 19:13:55 +00007705 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007706 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007707 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007708 }
7709
Richard Trieueea56f72011-09-02 03:48:46 +00007710 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7711 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7712 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7713 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7714 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7715 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign)
7716 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/false);
7717 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7718 Opc == BO_EQ || Opc == BO_NE)
7719 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/true);
Richard Trieu701fb362011-06-16 21:36:56 +00007720
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007721 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007722 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007723 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007724 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007725 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7726 VK = lhs.get()->getValueKind();
7727 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007728 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007729 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007730 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007731 break;
John McCalle3027922010-08-25 11:45:40 +00007732 case BO_PtrMemD:
7733 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007734 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007735 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007736 break;
John McCalle3027922010-08-25 11:45:40 +00007737 case BO_Mul:
7738 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007739 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007740 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007741 break;
John McCalle3027922010-08-25 11:45:40 +00007742 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007743 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7744 break;
John McCalle3027922010-08-25 11:45:40 +00007745 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007746 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7747 break;
John McCalle3027922010-08-25 11:45:40 +00007748 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007749 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7750 break;
John McCalle3027922010-08-25 11:45:40 +00007751 case BO_Shl:
7752 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007753 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007754 break;
John McCalle3027922010-08-25 11:45:40 +00007755 case BO_LE:
7756 case BO_LT:
7757 case BO_GE:
7758 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007759 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007760 break;
John McCalle3027922010-08-25 11:45:40 +00007761 case BO_EQ:
7762 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007763 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007764 break;
John McCalle3027922010-08-25 11:45:40 +00007765 case BO_And:
7766 case BO_Xor:
7767 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007768 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7769 break;
John McCalle3027922010-08-25 11:45:40 +00007770 case BO_LAnd:
7771 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007772 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007773 break;
John McCalle3027922010-08-25 11:45:40 +00007774 case BO_MulAssign:
7775 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007776 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007777 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007778 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007779 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7780 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007781 break;
John McCalle3027922010-08-25 11:45:40 +00007782 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007783 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7784 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007785 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7786 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007787 break;
John McCalle3027922010-08-25 11:45:40 +00007788 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007789 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007790 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7791 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007792 break;
John McCalle3027922010-08-25 11:45:40 +00007793 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007794 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007795 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7796 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007797 break;
John McCalle3027922010-08-25 11:45:40 +00007798 case BO_ShlAssign:
7799 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007800 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007801 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007802 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7803 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007804 break;
John McCalle3027922010-08-25 11:45:40 +00007805 case BO_AndAssign:
7806 case BO_XorAssign:
7807 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007808 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7809 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007810 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7811 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007812 break;
John McCalle3027922010-08-25 11:45:40 +00007813 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007814 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007815 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7816 VK = rhs.get()->getValueKind();
7817 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007818 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007819 break;
7820 }
John Wiegley01296292011-04-08 18:41:53 +00007821 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007822 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007823
7824 // Check for array bounds violations for both sides of the BinaryOperator
7825 CheckArrayAccess(lhs.get());
7826 CheckArrayAccess(rhs.get());
7827
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007828 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007829 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7830 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007831 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7832 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007833 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007834 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007835 }
John Wiegley01296292011-04-08 18:41:53 +00007836 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7837 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007838 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007839}
7840
Sebastian Redl44615072009-10-27 12:10:02 +00007841/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7842/// operators are mixed in a way that suggests that the programmer forgot that
7843/// comparison operators have higher precedence. The most typical example of
7844/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007845static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007846 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007847 typedef BinaryOperator BinOp;
7848 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7849 rhsopc = static_cast<BinOp::Opcode>(-1);
7850 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007851 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007852 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007853 rhsopc = BO->getOpcode();
7854
7855 // Subs are not binary operators.
7856 if (lhsopc == -1 && rhsopc == -1)
7857 return;
7858
7859 // Bitwise operations are sometimes used as eager logical ops.
7860 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007861 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7862 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007863 return;
7864
Richard Trieu73088052011-08-10 22:41:34 +00007865 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7866 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7867 if (!isLeftComp && !isRightComp) return;
7868
7869 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7870 : SourceRange(OpLoc, rhs->getLocEnd());
7871 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7872 : BinOp::getOpcodeStr(rhsopc);
7873 SourceRange ParensRange = isLeftComp ?
7874 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7875 rhs->getLocEnd())
7876 : SourceRange(lhs->getLocStart(),
7877 cast<BinOp>(rhs)->getLHS()->getLocStart());
7878
7879 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7880 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7881 SuggestParentheses(Self, OpLoc,
7882 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7883 rhs->getSourceRange());
7884 SuggestParentheses(Self, OpLoc,
7885 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7886 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007887}
7888
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007889/// \brief It accepts a '&' expr that is inside a '|' one.
7890/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7891/// in parentheses.
7892static void
7893EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7894 BinaryOperator *Bop) {
7895 assert(Bop->getOpcode() == BO_And);
7896 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7897 << Bop->getSourceRange() << OpLoc;
7898 SuggestParentheses(Self, Bop->getOperatorLoc(),
7899 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7900 Bop->getSourceRange());
7901}
7902
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007903/// \brief It accepts a '&&' expr that is inside a '||' one.
7904/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7905/// in parentheses.
7906static void
7907EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007908 BinaryOperator *Bop) {
7909 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007910 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7911 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007912 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007913 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007914 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007915}
7916
7917/// \brief Returns true if the given expression can be evaluated as a constant
7918/// 'true'.
7919static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7920 bool Res;
7921 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7922}
7923
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007924/// \brief Returns true if the given expression can be evaluated as a constant
7925/// 'false'.
7926static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7927 bool Res;
7928 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7929}
7930
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007931/// \brief Look for '&&' in the left hand of a '||' expr.
7932static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007933 Expr *OrLHS, Expr *OrRHS) {
7934 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007935 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007936 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7937 if (EvaluatesAsFalse(S, OrRHS))
7938 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007939 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7940 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7941 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7942 } else if (Bop->getOpcode() == BO_LOr) {
7943 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7944 // If it's "a || b && 1 || c" we didn't warn earlier for
7945 // "a || b && 1", but warn now.
7946 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7947 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7948 }
7949 }
7950 }
7951}
7952
7953/// \brief Look for '&&' in the right hand of a '||' expr.
7954static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007955 Expr *OrLHS, Expr *OrRHS) {
7956 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007957 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007958 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7959 if (EvaluatesAsFalse(S, OrLHS))
7960 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007961 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7962 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7963 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007964 }
7965 }
7966}
7967
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007968/// \brief Look for '&' in the left or right hand of a '|' expr.
7969static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7970 Expr *OrArg) {
7971 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7972 if (Bop->getOpcode() == BO_And)
7973 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7974 }
7975}
7976
Sebastian Redl43028242009-10-26 15:24:15 +00007977/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007978/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007979static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007980 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007981 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007982 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007983 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7984
7985 // Diagnose "arg1 & arg2 | arg3"
7986 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7987 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7988 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7989 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007990
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007991 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7992 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007993 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007994 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7995 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007996 }
Sebastian Redl43028242009-10-26 15:24:15 +00007997}
7998
Steve Naroff218bc2b2007-05-04 21:54:46 +00007999// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008000ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008001 tok::TokenKind Kind,
8002 Expr *lhs, Expr *rhs) {
8003 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008004 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8005 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008006
Sebastian Redl43028242009-10-26 15:24:15 +00008007 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8008 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8009
Douglas Gregor5287f092009-11-05 00:51:44 +00008010 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8011}
8012
John McCalldadc5752010-08-24 06:29:42 +00008013ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008014 BinaryOperatorKind Opc,
8015 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008016 if (getLangOptions().CPlusPlus) {
8017 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008018
John McCall622114c2010-12-06 05:26:58 +00008019 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8020 UseBuiltinOperator = false;
8021 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8022 UseBuiltinOperator = true;
8023 } else {
8024 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8025 !rhs->getType()->isOverloadableType();
8026 }
8027
8028 if (!UseBuiltinOperator) {
8029 // Find all of the overloaded operators visible from this
8030 // point. We perform both an operator-name lookup from the local
8031 // scope and an argument-dependent lookup based on the types of
8032 // the arguments.
8033 UnresolvedSet<16> Functions;
8034 OverloadedOperatorKind OverOp
8035 = BinaryOperator::getOverloadedOperator(Opc);
8036 if (S && OverOp != OO_None)
8037 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8038 Functions);
8039
8040 // Build the (potentially-overloaded, potentially-dependent)
8041 // binary operation.
8042 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8043 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008044 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008045
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008046 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008047 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008048}
8049
John McCalldadc5752010-08-24 06:29:42 +00008050ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008051 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008052 Expr *InputExpr) {
8053 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008054 ExprValueKind VK = VK_RValue;
8055 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008056 QualType resultType;
8057 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008058 case UO_PreInc:
8059 case UO_PreDec:
8060 case UO_PostInc:
8061 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008062 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008063 Opc == UO_PreInc ||
8064 Opc == UO_PostInc,
8065 Opc == UO_PreInc ||
8066 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008067 break;
John McCalle3027922010-08-25 11:45:40 +00008068 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008069 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008070 break;
John McCall31996342011-04-07 08:22:57 +00008071 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008072 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008073 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008074 Input = move(resolved);
8075 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8076 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008077 break;
John McCall31996342011-04-07 08:22:57 +00008078 }
John McCalle3027922010-08-25 11:45:40 +00008079 case UO_Plus:
8080 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008081 Input = UsualUnaryConversions(Input.take());
8082 if (Input.isInvalid()) return ExprError();
8083 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008084 if (resultType->isDependentType())
8085 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008086 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8087 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008088 break;
8089 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8090 resultType->isEnumeralType())
8091 break;
8092 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008093 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008094 resultType->isPointerType())
8095 break;
John McCall36226622010-10-12 02:09:17 +00008096 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008097 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008098 if (Input.isInvalid()) return ExprError();
8099 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008100 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008101
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008102 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008103 << resultType << Input.get()->getSourceRange());
8104
John McCalle3027922010-08-25 11:45:40 +00008105 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008106 Input = UsualUnaryConversions(Input.take());
8107 if (Input.isInvalid()) return ExprError();
8108 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008109 if (resultType->isDependentType())
8110 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008111 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8112 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8113 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008114 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008115 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008116 else if (resultType->hasIntegerRepresentation())
8117 break;
8118 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008119 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008120 if (Input.isInvalid()) return ExprError();
8121 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008122 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008123 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008124 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008125 }
Steve Naroff35d85152007-05-07 00:24:15 +00008126 break;
John Wiegley01296292011-04-08 18:41:53 +00008127
John McCalle3027922010-08-25 11:45:40 +00008128 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008129 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008130 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8131 if (Input.isInvalid()) return ExprError();
8132 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008133 if (resultType->isDependentType())
8134 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008135 if (resultType->isScalarType()) {
8136 // C99 6.5.3.3p1: ok, fallthrough;
8137 if (Context.getLangOptions().CPlusPlus) {
8138 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8139 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008140 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8141 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008142 }
John McCall36226622010-10-12 02:09:17 +00008143 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008144 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008145 if (Input.isInvalid()) return ExprError();
8146 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008147 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008148 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008149 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008150 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008151
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008152 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008153 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008154 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008155 break;
John McCalle3027922010-08-25 11:45:40 +00008156 case UO_Real:
8157 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008158 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008159 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008160 if (Input.isInvalid()) return ExprError();
8161 if (Input.get()->getValueKind() != VK_RValue &&
8162 Input.get()->getObjectKind() == OK_Ordinary)
8163 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008164 break;
John McCalle3027922010-08-25 11:45:40 +00008165 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008166 resultType = Input.get()->getType();
8167 VK = Input.get()->getValueKind();
8168 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008169 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008170 }
John Wiegley01296292011-04-08 18:41:53 +00008171 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008172 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008173
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008174 // Check for array bounds violations in the operand of the UnaryOperator,
8175 // except for the '*' and '&' operators that have to be handled specially
8176 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8177 // that are explicitly defined as valid by the standard).
8178 if (Opc != UO_AddrOf && Opc != UO_Deref)
8179 CheckArrayAccess(Input.get());
8180
John Wiegley01296292011-04-08 18:41:53 +00008181 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008182 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008183}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008184
John McCalldadc5752010-08-24 06:29:42 +00008185ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008186 UnaryOperatorKind Opc,
8187 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008188 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008189 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008190 // Find all of the overloaded operators visible from this
8191 // point. We perform both an operator-name lookup from the local
8192 // scope and an argument-dependent lookup based on the types of
8193 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008194 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008195 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008196 if (S && OverOp != OO_None)
8197 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8198 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008199
John McCallb268a282010-08-23 23:25:46 +00008200 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008201 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008202
John McCallb268a282010-08-23 23:25:46 +00008203 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008204}
8205
Douglas Gregor5287f092009-11-05 00:51:44 +00008206// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008207ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008208 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008209 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008210}
8211
Steve Naroff66356bd2007-09-16 14:56:35 +00008212/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008213ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008214 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008215 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008216 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008217 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008218 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008219}
8220
John McCall31168b02011-06-15 23:02:42 +00008221/// Given the last statement in a statement-expression, check whether
8222/// the result is a producing expression (like a call to an
8223/// ns_returns_retained function) and, if so, rebuild it to hoist the
8224/// release out of the full-expression. Otherwise, return null.
8225/// Cannot fail.
8226static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8227 // Should always be wrapped with one of these.
8228 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8229 if (!cleanups) return 0;
8230
8231 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8232 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8233 return 0;
8234
8235 // Splice out the cast. This shouldn't modify any interesting
8236 // features of the statement.
8237 Expr *producer = cast->getSubExpr();
8238 assert(producer->getType() == cast->getType());
8239 assert(producer->getValueKind() == cast->getValueKind());
8240 cleanups->setSubExpr(producer);
8241 return cleanups;
8242}
8243
John McCalldadc5752010-08-24 06:29:42 +00008244ExprResult
John McCallb268a282010-08-23 23:25:46 +00008245Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008246 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008247 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8248 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8249
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008250 bool isFileScope
8251 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008252 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008253 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008254
Chris Lattner366727f2007-07-24 16:58:17 +00008255 // FIXME: there are a variety of strange constraints to enforce here, for
8256 // example, it is not possible to goto into a stmt expression apparently.
8257 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008258
Chris Lattner366727f2007-07-24 16:58:17 +00008259 // If there are sub stmts in the compound stmt, take the type of the last one
8260 // as the type of the stmtexpr.
8261 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008262 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008263 if (!Compound->body_empty()) {
8264 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008265 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008266 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008267 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8268 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008269 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008270 }
John McCall31168b02011-06-15 23:02:42 +00008271
John Wiegley01296292011-04-08 18:41:53 +00008272 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008273 // Do function/array conversion on the last expression, but not
8274 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008275 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8276 if (LastExpr.isInvalid())
8277 return ExprError();
8278 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008279
John Wiegley01296292011-04-08 18:41:53 +00008280 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008281 // In ARC, if the final expression ends in a consume, splice
8282 // the consume out and bind it later. In the alternate case
8283 // (when dealing with a retainable type), the result
8284 // initialization will create a produce. In both cases the
8285 // result will be +1, and we'll need to balance that out with
8286 // a bind.
8287 if (Expr *rebuiltLastStmt
8288 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8289 LastExpr = rebuiltLastStmt;
8290 } else {
8291 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008292 InitializedEntity::InitializeResult(LPLoc,
8293 Ty,
8294 false),
8295 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008296 LastExpr);
8297 }
8298
John Wiegley01296292011-04-08 18:41:53 +00008299 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008300 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008301 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008302 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008303 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008304 else
John Wiegley01296292011-04-08 18:41:53 +00008305 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008306 StmtExprMayBindToTemp = true;
8307 }
8308 }
8309 }
Chris Lattner944d3062008-07-26 19:51:01 +00008310 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008311
Eli Friedmanba961a92009-03-23 00:24:07 +00008312 // FIXME: Check that expression type is complete/non-abstract; statement
8313 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008314 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8315 if (StmtExprMayBindToTemp)
8316 return MaybeBindToTemporary(ResStmtExpr);
8317 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008318}
Steve Naroff78864672007-08-01 22:05:33 +00008319
John McCalldadc5752010-08-24 06:29:42 +00008320ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008321 TypeSourceInfo *TInfo,
8322 OffsetOfComponent *CompPtr,
8323 unsigned NumComponents,
8324 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008325 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008326 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008327 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008328
Chris Lattnerf17bd422007-08-30 17:45:32 +00008329 // We must have at least one component that refers to the type, and the first
8330 // one is known to be a field designator. Verify that the ArgTy represents
8331 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008332 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008333 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8334 << ArgTy << TypeRange);
8335
8336 // Type must be complete per C99 7.17p3 because a declaring a variable
8337 // with an incomplete type would be ill-formed.
8338 if (!Dependent
8339 && RequireCompleteType(BuiltinLoc, ArgTy,
8340 PDiag(diag::err_offsetof_incomplete_type)
8341 << TypeRange))
8342 return ExprError();
8343
Chris Lattner78502cf2007-08-31 21:49:13 +00008344 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8345 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008346 // FIXME: This diagnostic isn't actually visible because the location is in
8347 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008348 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008349 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8350 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008351
8352 bool DidWarnAboutNonPOD = false;
8353 QualType CurrentType = ArgTy;
8354 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008355 SmallVector<OffsetOfNode, 4> Comps;
8356 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008357 for (unsigned i = 0; i != NumComponents; ++i) {
8358 const OffsetOfComponent &OC = CompPtr[i];
8359 if (OC.isBrackets) {
8360 // Offset of an array sub-field. TODO: Should we allow vector elements?
8361 if (!CurrentType->isDependentType()) {
8362 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8363 if(!AT)
8364 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8365 << CurrentType);
8366 CurrentType = AT->getElementType();
8367 } else
8368 CurrentType = Context.DependentTy;
8369
8370 // The expression must be an integral expression.
8371 // FIXME: An integral constant expression?
8372 Expr *Idx = static_cast<Expr*>(OC.U.E);
8373 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8374 !Idx->getType()->isIntegerType())
8375 return ExprError(Diag(Idx->getLocStart(),
8376 diag::err_typecheck_subscript_not_integer)
8377 << Idx->getSourceRange());
8378
8379 // Record this array index.
8380 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8381 Exprs.push_back(Idx);
8382 continue;
8383 }
8384
8385 // Offset of a field.
8386 if (CurrentType->isDependentType()) {
8387 // We have the offset of a field, but we can't look into the dependent
8388 // type. Just record the identifier of the field.
8389 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8390 CurrentType = Context.DependentTy;
8391 continue;
8392 }
8393
8394 // We need to have a complete type to look into.
8395 if (RequireCompleteType(OC.LocStart, CurrentType,
8396 diag::err_offsetof_incomplete_type))
8397 return ExprError();
8398
8399 // Look for the designated field.
8400 const RecordType *RC = CurrentType->getAs<RecordType>();
8401 if (!RC)
8402 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8403 << CurrentType);
8404 RecordDecl *RD = RC->getDecl();
8405
8406 // C++ [lib.support.types]p5:
8407 // The macro offsetof accepts a restricted set of type arguments in this
8408 // International Standard. type shall be a POD structure or a POD union
8409 // (clause 9).
8410 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8411 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008412 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008413 PDiag(diag::warn_offsetof_non_pod_type)
8414 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8415 << CurrentType))
8416 DidWarnAboutNonPOD = true;
8417 }
8418
8419 // Look for the field.
8420 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8421 LookupQualifiedName(R, RD);
8422 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008423 IndirectFieldDecl *IndirectMemberDecl = 0;
8424 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008425 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008426 MemberDecl = IndirectMemberDecl->getAnonField();
8427 }
8428
Douglas Gregor882211c2010-04-28 22:16:22 +00008429 if (!MemberDecl)
8430 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8431 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8432 OC.LocEnd));
8433
Douglas Gregor10982ea2010-04-28 22:36:06 +00008434 // C99 7.17p3:
8435 // (If the specified member is a bit-field, the behavior is undefined.)
8436 //
8437 // We diagnose this as an error.
8438 if (MemberDecl->getBitWidth()) {
8439 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8440 << MemberDecl->getDeclName()
8441 << SourceRange(BuiltinLoc, RParenLoc);
8442 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8443 return ExprError();
8444 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008445
8446 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008447 if (IndirectMemberDecl)
8448 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008449
Douglas Gregord1702062010-04-29 00:18:15 +00008450 // If the member was found in a base class, introduce OffsetOfNodes for
8451 // the base class indirections.
8452 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8453 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008454 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008455 CXXBasePath &Path = Paths.front();
8456 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8457 B != BEnd; ++B)
8458 Comps.push_back(OffsetOfNode(B->Base));
8459 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008460
Francois Pichet783dd6e2010-11-21 06:08:52 +00008461 if (IndirectMemberDecl) {
8462 for (IndirectFieldDecl::chain_iterator FI =
8463 IndirectMemberDecl->chain_begin(),
8464 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8465 assert(isa<FieldDecl>(*FI));
8466 Comps.push_back(OffsetOfNode(OC.LocStart,
8467 cast<FieldDecl>(*FI), OC.LocEnd));
8468 }
8469 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008470 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008471
Douglas Gregor882211c2010-04-28 22:16:22 +00008472 CurrentType = MemberDecl->getType().getNonReferenceType();
8473 }
8474
8475 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8476 TInfo, Comps.data(), Comps.size(),
8477 Exprs.data(), Exprs.size(), RParenLoc));
8478}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008479
John McCalldadc5752010-08-24 06:29:42 +00008480ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008481 SourceLocation BuiltinLoc,
8482 SourceLocation TypeLoc,
8483 ParsedType argty,
8484 OffsetOfComponent *CompPtr,
8485 unsigned NumComponents,
8486 SourceLocation RPLoc) {
8487
Douglas Gregor882211c2010-04-28 22:16:22 +00008488 TypeSourceInfo *ArgTInfo;
8489 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8490 if (ArgTy.isNull())
8491 return ExprError();
8492
Eli Friedman06dcfd92010-08-05 10:15:45 +00008493 if (!ArgTInfo)
8494 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8495
8496 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8497 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008498}
8499
8500
John McCalldadc5752010-08-24 06:29:42 +00008501ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008502 Expr *CondExpr,
8503 Expr *LHSExpr, Expr *RHSExpr,
8504 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008505 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8506
John McCall7decc9e2010-11-18 06:31:45 +00008507 ExprValueKind VK = VK_RValue;
8508 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008509 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008510 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008511 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008512 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008513 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008514 } else {
8515 // The conditional expression is required to be a constant expression.
8516 llvm::APSInt condEval(32);
8517 SourceLocation ExpLoc;
8518 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008519 return ExprError(Diag(ExpLoc,
8520 diag::err_typecheck_choose_expr_requires_constant)
8521 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008522
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008523 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008524 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8525
8526 resType = ActiveExpr->getType();
8527 ValueDependent = ActiveExpr->isValueDependent();
8528 VK = ActiveExpr->getValueKind();
8529 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008530 }
8531
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008532 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008533 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008534 resType->isDependentType(),
8535 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008536}
8537
Steve Naroffc540d662008-09-03 18:15:37 +00008538//===----------------------------------------------------------------------===//
8539// Clang Extensions.
8540//===----------------------------------------------------------------------===//
8541
8542/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008543void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008544 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8545 PushBlockScope(BlockScope, Block);
8546 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008547 if (BlockScope)
8548 PushDeclContext(BlockScope, Block);
8549 else
8550 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008551}
8552
Mike Stump82f071f2009-02-04 22:31:32 +00008553void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008554 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008555 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008556 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008557
John McCall8cb7bdf2010-06-04 23:28:52 +00008558 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008559 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008560
John McCall3882ace2011-01-05 12:14:39 +00008561 // GetTypeForDeclarator always produces a function type for a block
8562 // literal signature. Furthermore, it is always a FunctionProtoType
8563 // unless the function was written with a typedef.
8564 assert(T->isFunctionType() &&
8565 "GetTypeForDeclarator made a non-function block signature");
8566
8567 // Look for an explicit signature in that function type.
8568 FunctionProtoTypeLoc ExplicitSignature;
8569
8570 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8571 if (isa<FunctionProtoTypeLoc>(tmp)) {
8572 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8573
8574 // Check whether that explicit signature was synthesized by
8575 // GetTypeForDeclarator. If so, don't save that as part of the
8576 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008577 if (ExplicitSignature.getLocalRangeBegin() ==
8578 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008579 // This would be much cheaper if we stored TypeLocs instead of
8580 // TypeSourceInfos.
8581 TypeLoc Result = ExplicitSignature.getResultLoc();
8582 unsigned Size = Result.getFullDataSize();
8583 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8584 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8585
8586 ExplicitSignature = FunctionProtoTypeLoc();
8587 }
John McCalla3ccba02010-06-04 11:21:44 +00008588 }
Mike Stump11289f42009-09-09 15:08:12 +00008589
John McCall3882ace2011-01-05 12:14:39 +00008590 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8591 CurBlock->FunctionType = T;
8592
8593 const FunctionType *Fn = T->getAs<FunctionType>();
8594 QualType RetTy = Fn->getResultType();
8595 bool isVariadic =
8596 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8597
John McCall8e346702010-06-04 19:02:56 +00008598 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008599
John McCalla3ccba02010-06-04 11:21:44 +00008600 // Don't allow returning a objc interface by value.
8601 if (RetTy->isObjCObjectType()) {
8602 Diag(ParamInfo.getSourceRange().getBegin(),
8603 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8604 return;
8605 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008606
John McCalla3ccba02010-06-04 11:21:44 +00008607 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008608 // return type. TODO: what should we do with declarators like:
8609 // ^ * { ... }
8610 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008611 if (RetTy != Context.DependentTy)
8612 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008613
John McCalla3ccba02010-06-04 11:21:44 +00008614 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008615 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008616 if (ExplicitSignature) {
8617 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8618 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008619 if (Param->getIdentifier() == 0 &&
8620 !Param->isImplicit() &&
8621 !Param->isInvalidDecl() &&
8622 !getLangOptions().CPlusPlus)
8623 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008624 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008625 }
John McCalla3ccba02010-06-04 11:21:44 +00008626
8627 // Fake up parameter variables if we have a typedef, like
8628 // ^ fntype { ... }
8629 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8630 for (FunctionProtoType::arg_type_iterator
8631 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8632 ParmVarDecl *Param =
8633 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8634 ParamInfo.getSourceRange().getBegin(),
8635 *I);
John McCall8e346702010-06-04 19:02:56 +00008636 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008637 }
Steve Naroffc540d662008-09-03 18:15:37 +00008638 }
John McCalla3ccba02010-06-04 11:21:44 +00008639
John McCall8e346702010-06-04 19:02:56 +00008640 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008641 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008642 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008643 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8644 CurBlock->TheDecl->param_end(),
8645 /*CheckParameterNames=*/false);
8646 }
8647
John McCalla3ccba02010-06-04 11:21:44 +00008648 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008649 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008650
John McCall8e346702010-06-04 19:02:56 +00008651 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008652 Diag(ParamInfo.getAttributes()->getLoc(),
8653 diag::warn_attribute_sentinel_not_variadic) << 1;
8654 // FIXME: remove the attribute.
8655 }
8656
8657 // Put the parameter variables in scope. We can bail out immediately
8658 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008659 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008660 return;
8661
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008662 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008663 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8664 (*AI)->setOwningFunction(CurBlock->TheDecl);
8665
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008666 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008667 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008668 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008669
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008670 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008671 }
John McCallf7b2fb52010-01-22 00:28:27 +00008672 }
Steve Naroffc540d662008-09-03 18:15:37 +00008673}
8674
8675/// ActOnBlockError - If there is an error parsing a block, this callback
8676/// is invoked to pop the information about the block from the action impl.
8677void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008678 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008679 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008680 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008681}
8682
8683/// ActOnBlockStmtExpr - This is called when the body of a block statement
8684/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008685ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008686 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008687 // If blocks are disabled, emit an error.
8688 if (!LangOpts.Blocks)
8689 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008690
Douglas Gregor9a28e842010-03-01 23:15:13 +00008691 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008692
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008693 PopDeclContext();
8694
Steve Naroffc540d662008-09-03 18:15:37 +00008695 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008696 if (!BSI->ReturnType.isNull())
8697 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008698
Mike Stump3bf1ab42009-07-28 22:04:01 +00008699 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008700 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008701
John McCallc63de662011-02-02 13:00:07 +00008702 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008703 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8704 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008705
John McCall8e346702010-06-04 19:02:56 +00008706 // If the user wrote a function type in some form, try to use that.
8707 if (!BSI->FunctionType.isNull()) {
8708 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8709
8710 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8711 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8712
8713 // Turn protoless block types into nullary block types.
8714 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008715 FunctionProtoType::ExtProtoInfo EPI;
8716 EPI.ExtInfo = Ext;
8717 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008718
8719 // Otherwise, if we don't need to change anything about the function type,
8720 // preserve its sugar structure.
8721 } else if (FTy->getResultType() == RetTy &&
8722 (!NoReturn || FTy->getNoReturnAttr())) {
8723 BlockTy = BSI->FunctionType;
8724
8725 // Otherwise, make the minimal modifications to the function type.
8726 } else {
8727 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008728 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8729 EPI.TypeQuals = 0; // FIXME: silently?
8730 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008731 BlockTy = Context.getFunctionType(RetTy,
8732 FPT->arg_type_begin(),
8733 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008734 EPI);
John McCall8e346702010-06-04 19:02:56 +00008735 }
8736
8737 // If we don't have a function type, just build one from nothing.
8738 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008739 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008740 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008741 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008742 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008743
John McCall8e346702010-06-04 19:02:56 +00008744 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8745 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008746 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008747
Chris Lattner45542ea2009-04-19 05:28:12 +00008748 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008749 if (getCurFunction()->NeedsScopeChecking() &&
8750 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008751 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008752
Chris Lattner60f84492011-02-17 23:58:47 +00008753 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008754
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008755 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8756 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8757 const VarDecl *variable = ci->getVariable();
8758 QualType T = variable->getType();
8759 QualType::DestructionKind destructKind = T.isDestructedType();
8760 if (destructKind != QualType::DK_none)
8761 getCurFunction()->setHasBranchProtectedScope();
8762 }
8763
Douglas Gregor49695f02011-09-06 20:46:03 +00008764 computeNRVO(Body, getCurBlock());
8765
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008766 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8767 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8768 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8769
Douglas Gregor9a28e842010-03-01 23:15:13 +00008770 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008771}
8772
John McCalldadc5752010-08-24 06:29:42 +00008773ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008774 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008775 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008776 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008777 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008778 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008779}
8780
John McCalldadc5752010-08-24 06:29:42 +00008781ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008782 Expr *E, TypeSourceInfo *TInfo,
8783 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008784 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008785
Eli Friedman121ba0c2008-08-09 23:32:40 +00008786 // Get the va_list type
8787 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008788 if (VaListType->isArrayType()) {
8789 // Deal with implicit array decay; for example, on x86-64,
8790 // va_list is an array, but it's supposed to decay to
8791 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008792 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008793 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008794 ExprResult Result = UsualUnaryConversions(E);
8795 if (Result.isInvalid())
8796 return ExprError();
8797 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008798 } else {
8799 // Otherwise, the va_list argument must be an l-value because
8800 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008801 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008802 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008803 return ExprError();
8804 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008805
Douglas Gregorad3150c2009-05-19 23:10:31 +00008806 if (!E->isTypeDependent() &&
8807 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008808 return ExprError(Diag(E->getLocStart(),
8809 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008810 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008811 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008812
David Majnemerc75d1a12011-06-14 05:17:32 +00008813 if (!TInfo->getType()->isDependentType()) {
8814 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8815 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8816 << TInfo->getTypeLoc().getSourceRange()))
8817 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008818
David Majnemerc75d1a12011-06-14 05:17:32 +00008819 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8820 TInfo->getType(),
8821 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8822 << TInfo->getTypeLoc().getSourceRange()))
8823 return ExprError();
8824
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008825 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008826 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008827 TInfo->getType()->isObjCLifetimeType()
8828 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8829 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008830 << TInfo->getType()
8831 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008832 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008833
8834 // Check for va_arg where arguments of the given type will be promoted
8835 // (i.e. this va_arg is guaranteed to have undefined behavior).
8836 QualType PromoteType;
8837 if (TInfo->getType()->isPromotableIntegerType()) {
8838 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8839 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8840 PromoteType = QualType();
8841 }
8842 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8843 PromoteType = Context.DoubleTy;
8844 if (!PromoteType.isNull())
8845 Diag(TInfo->getTypeLoc().getBeginLoc(),
8846 diag::warn_second_parameter_to_va_arg_never_compatible)
8847 << TInfo->getType()
8848 << PromoteType
8849 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008850 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008851
Abramo Bagnara27db2392010-08-10 10:06:15 +00008852 QualType T = TInfo->getType().getNonLValueExprType(Context);
8853 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008854}
8855
John McCalldadc5752010-08-24 06:29:42 +00008856ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008857 // The type of __null will be int or long, depending on the size of
8858 // pointers on the target.
8859 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008860 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8861 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008862 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008863 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008864 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008865 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008866 Ty = Context.LongLongTy;
8867 else {
8868 assert(!"I don't know size of pointer!");
8869 Ty = Context.IntTy;
8870 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008871
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008872 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008873}
8874
Alexis Huntc46382e2010-04-28 23:02:27 +00008875static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008876 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008877 if (!SemaRef.getLangOptions().ObjC1)
8878 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008879
Anders Carlssonace5d072009-11-10 04:46:30 +00008880 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8881 if (!PT)
8882 return;
8883
8884 // Check if the destination is of type 'id'.
8885 if (!PT->isObjCIdType()) {
8886 // Check if the destination is the 'NSString' interface.
8887 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8888 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8889 return;
8890 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008891
Anders Carlssonace5d072009-11-10 04:46:30 +00008892 // Strip off any parens and casts.
8893 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008894 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008895 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008896
Douglas Gregora771f462010-03-31 17:46:05 +00008897 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008898}
8899
Chris Lattner9bad62c2008-01-04 18:04:52 +00008900bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8901 SourceLocation Loc,
8902 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008903 Expr *SrcExpr, AssignmentAction Action,
8904 bool *Complained) {
8905 if (Complained)
8906 *Complained = false;
8907
Chris Lattner9bad62c2008-01-04 18:04:52 +00008908 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008909 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008910 bool isInvalid = false;
8911 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008912 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008913 ConversionFixItGenerator ConvHints;
8914 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008915
Chris Lattner9bad62c2008-01-04 18:04:52 +00008916 switch (ConvTy) {
8917 default: assert(0 && "Unknown conversion type");
8918 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008919 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008920 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008921 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8922 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008923 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008924 case IntToPointer:
8925 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008926 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8927 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008928 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008929 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008930 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008931 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008932 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8933 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008934 if (Hint.isNull() && !CheckInferredResultType) {
8935 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8936 }
8937 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008938 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008939 case IncompatiblePointerSign:
8940 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8941 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008942 case FunctionVoidPointer:
8943 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8944 break;
John McCall4fff8f62011-02-01 00:10:29 +00008945 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008946 // Perform array-to-pointer decay if necessary.
8947 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8948
John McCall4fff8f62011-02-01 00:10:29 +00008949 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8950 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8951 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8952 DiagKind = diag::err_typecheck_incompatible_address_space;
8953 break;
John McCall31168b02011-06-15 23:02:42 +00008954
8955
8956 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008957 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008958 break;
John McCall4fff8f62011-02-01 00:10:29 +00008959 }
8960
8961 llvm_unreachable("unknown error case for discarding qualifiers!");
8962 // fallthrough
8963 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008964 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008965 // If the qualifiers lost were because we were applying the
8966 // (deprecated) C++ conversion from a string literal to a char*
8967 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8968 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008969 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008970 // bit of refactoring (so that the second argument is an
8971 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008972 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008973 // C++ semantics.
8974 if (getLangOptions().CPlusPlus &&
8975 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8976 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008977 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8978 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008979 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008980 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008981 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008982 case IntToBlockPointer:
8983 DiagKind = diag::err_int_to_block_pointer;
8984 break;
8985 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008986 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008987 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008988 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008989 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008990 // it can give a more specific diagnostic.
8991 DiagKind = diag::warn_incompatible_qualified_id;
8992 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008993 case IncompatibleVectors:
8994 DiagKind = diag::warn_incompatible_vectors;
8995 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008996 case IncompatibleObjCWeakRef:
8997 DiagKind = diag::err_arc_weak_unavailable_assign;
8998 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008999 case Incompatible:
9000 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009001 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9002 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009003 isInvalid = true;
9004 break;
9005 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009006
Douglas Gregorc68e1402010-04-09 00:35:39 +00009007 QualType FirstType, SecondType;
9008 switch (Action) {
9009 case AA_Assigning:
9010 case AA_Initializing:
9011 // The destination type comes first.
9012 FirstType = DstType;
9013 SecondType = SrcType;
9014 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009015
Douglas Gregorc68e1402010-04-09 00:35:39 +00009016 case AA_Returning:
9017 case AA_Passing:
9018 case AA_Converting:
9019 case AA_Sending:
9020 case AA_Casting:
9021 // The source type comes first.
9022 FirstType = SrcType;
9023 SecondType = DstType;
9024 break;
9025 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009026
Anna Zaks3b402712011-07-28 19:51:27 +00009027 PartialDiagnostic FDiag = PDiag(DiagKind);
9028 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9029
9030 // If we can fix the conversion, suggest the FixIts.
9031 assert(ConvHints.isNull() || Hint.isNull());
9032 if (!ConvHints.isNull()) {
9033 for (llvm::SmallVector<FixItHint, 1>::iterator
9034 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9035 HI != HE; ++HI)
9036 FDiag << *HI;
9037 } else {
9038 FDiag << Hint;
9039 }
9040 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9041
9042 Diag(Loc, FDiag);
9043
Douglas Gregor33823722011-06-11 01:09:30 +00009044 if (CheckInferredResultType)
9045 EmitRelatedResultTypeNote(SrcExpr);
9046
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009047 if (Complained)
9048 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009049 return isInvalid;
9050}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009051
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009052bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009053 llvm::APSInt ICEResult;
9054 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9055 if (Result)
9056 *Result = ICEResult;
9057 return false;
9058 }
9059
Anders Carlssone54e8a12008-11-30 19:50:32 +00009060 Expr::EvalResult EvalResult;
9061
Mike Stump4e1f26a2009-02-19 03:04:26 +00009062 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009063 EvalResult.HasSideEffects) {
9064 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9065
9066 if (EvalResult.Diag) {
9067 // We only show the note if it's not the usual "invalid subexpression"
9068 // or if it's actually in a subexpression.
9069 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9070 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9071 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9072 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009073
Anders Carlssone54e8a12008-11-30 19:50:32 +00009074 return true;
9075 }
9076
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009077 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9078 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009079
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009080 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009081 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9082 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009083 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009084
Anders Carlssone54e8a12008-11-30 19:50:32 +00009085 if (Result)
9086 *Result = EvalResult.Val.getInt();
9087 return false;
9088}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009089
Douglas Gregorff790f12009-11-26 00:44:06 +00009090void
Mike Stump11289f42009-09-09 15:08:12 +00009091Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009092 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009093 ExpressionEvaluationContextRecord(NewContext,
9094 ExprTemporaries.size(),
9095 ExprNeedsCleanups));
9096 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009097}
9098
Richard Trieucfc491d2011-08-02 04:35:43 +00009099void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009100 // Pop the current expression evaluation context off the stack.
9101 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9102 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009103
Douglas Gregorfab31f42009-12-12 07:57:52 +00009104 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9105 if (Rec.PotentiallyReferenced) {
9106 // Mark any remaining declarations in the current position of the stack
9107 // as "referenced". If they were not meant to be referenced, semantic
9108 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009109 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009110 I = Rec.PotentiallyReferenced->begin(),
9111 IEnd = Rec.PotentiallyReferenced->end();
9112 I != IEnd; ++I)
9113 MarkDeclarationReferenced(I->first, I->second);
9114 }
9115
9116 if (Rec.PotentiallyDiagnosed) {
9117 // Emit any pending diagnostics.
9118 for (PotentiallyEmittedDiagnostics::iterator
9119 I = Rec.PotentiallyDiagnosed->begin(),
9120 IEnd = Rec.PotentiallyDiagnosed->end();
9121 I != IEnd; ++I)
9122 Diag(I->first, I->second);
9123 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009124 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009125
9126 // When are coming out of an unevaluated context, clear out any
9127 // temporaries that we may have created as part of the evaluation of
9128 // the expression in that context: they aren't relevant because they
9129 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009130 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009131 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9132 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009133 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9134
9135 // Otherwise, merge the contexts together.
9136 } else {
9137 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9138 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009139
9140 // Destroy the popped expression evaluation record.
9141 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009142}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009143
John McCall31168b02011-06-15 23:02:42 +00009144void Sema::DiscardCleanupsInEvaluationContext() {
9145 ExprTemporaries.erase(
9146 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9147 ExprTemporaries.end());
9148 ExprNeedsCleanups = false;
9149}
9150
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009151/// \brief Note that the given declaration was referenced in the source code.
9152///
9153/// This routine should be invoke whenever a given declaration is referenced
9154/// in the source code, and where that reference occurred. If this declaration
9155/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9156/// C99 6.9p3), then the declaration will be marked as used.
9157///
9158/// \param Loc the location where the declaration was referenced.
9159///
9160/// \param D the declaration that has been referenced by the source code.
9161void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9162 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009163
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009164 D->setReferenced();
9165
Douglas Gregorebada0772010-06-17 23:14:26 +00009166 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009167 return;
Mike Stump11289f42009-09-09 15:08:12 +00009168
Richard Trieucfc491d2011-08-02 04:35:43 +00009169 // Mark a parameter or variable declaration "used", regardless of whether
9170 // we're in a template or not. The reason for this is that unevaluated
9171 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9172 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009173 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009174 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009175 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009176 return;
9177 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009178
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009179 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9180 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009181
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009182 // Do not mark anything as "used" within a dependent context; wait for
9183 // an instantiation.
9184 if (CurContext->isDependentContext())
9185 return;
Mike Stump11289f42009-09-09 15:08:12 +00009186
Douglas Gregorff790f12009-11-26 00:44:06 +00009187 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009188 case Unevaluated:
9189 // We are in an expression that is not potentially evaluated; do nothing.
9190 return;
Mike Stump11289f42009-09-09 15:08:12 +00009191
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009192 case PotentiallyEvaluated:
9193 // We are in a potentially-evaluated expression, so this declaration is
9194 // "used"; handle this below.
9195 break;
Mike Stump11289f42009-09-09 15:08:12 +00009196
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009197 case PotentiallyPotentiallyEvaluated:
9198 // We are in an expression that may be potentially evaluated; queue this
9199 // declaration reference until we know whether the expression is
9200 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009201 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009202 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009203
9204 case PotentiallyEvaluatedIfUsed:
9205 // Referenced declarations will only be used if the construct in the
9206 // containing expression is used.
9207 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009208 }
Mike Stump11289f42009-09-09 15:08:12 +00009209
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009210 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009211 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009212 if (Constructor->isDefaulted()) {
9213 if (Constructor->isDefaultConstructor()) {
9214 if (Constructor->isTrivial())
9215 return;
9216 if (!Constructor->isUsed(false))
9217 DefineImplicitDefaultConstructor(Loc, Constructor);
9218 } else if (Constructor->isCopyConstructor()) {
9219 if (!Constructor->isUsed(false))
9220 DefineImplicitCopyConstructor(Loc, Constructor);
9221 } else if (Constructor->isMoveConstructor()) {
9222 if (!Constructor->isUsed(false))
9223 DefineImplicitMoveConstructor(Loc, Constructor);
9224 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009225 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009226
Douglas Gregor88d292c2010-05-13 16:44:06 +00009227 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009228 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009229 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009230 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009231 if (Destructor->isVirtual())
9232 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009233 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009234 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009235 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009236 if (!MethodDecl->isUsed(false)) {
9237 if (MethodDecl->isCopyAssignmentOperator())
9238 DefineImplicitCopyAssignment(Loc, MethodDecl);
9239 else
9240 DefineImplicitMoveAssignment(Loc, MethodDecl);
9241 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009242 } else if (MethodDecl->isVirtual())
9243 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009244 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009245 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009246 // Recursive functions should be marked when used from another function.
9247 if (CurContext == Function) return;
9248
Mike Stump11289f42009-09-09 15:08:12 +00009249 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009250 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009251 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009252 bool AlreadyInstantiated = false;
9253 if (FunctionTemplateSpecializationInfo *SpecInfo
9254 = Function->getTemplateSpecializationInfo()) {
9255 if (SpecInfo->getPointOfInstantiation().isInvalid())
9256 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009257 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009258 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009259 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009260 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009261 = Function->getMemberSpecializationInfo()) {
9262 if (MSInfo->getPointOfInstantiation().isInvalid())
9263 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009264 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009265 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009266 AlreadyInstantiated = true;
9267 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009268
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009269 if (!AlreadyInstantiated) {
9270 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9271 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9272 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9273 Loc));
9274 else
Chandler Carruth54080172010-08-25 08:44:16 +00009275 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009276 }
John McCall83779672011-02-19 02:53:41 +00009277 } else {
9278 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009279 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9280 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009281 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009282 MarkDeclarationReferenced(Loc, *i);
9283 }
John McCall83779672011-02-19 02:53:41 +00009284 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009285
John McCall83779672011-02-19 02:53:41 +00009286 // Keep track of used but undefined functions.
9287 if (!Function->isPure() && !Function->hasBody() &&
9288 Function->getLinkage() != ExternalLinkage) {
9289 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9290 if (old.isInvalid()) old = Loc;
9291 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009292
John McCall83779672011-02-19 02:53:41 +00009293 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009294 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009295 }
Mike Stump11289f42009-09-09 15:08:12 +00009296
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009297 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009298 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009299 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009300 Var->getInstantiatedFromStaticDataMember()) {
9301 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9302 assert(MSInfo && "Missing member specialization information?");
9303 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9304 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9305 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009306 // This is a modification of an existing AST node. Notify listeners.
9307 if (ASTMutationListener *L = getASTMutationListener())
9308 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009309 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009310 }
9311 }
Mike Stump11289f42009-09-09 15:08:12 +00009312
John McCall15dd4042011-02-21 19:25:48 +00009313 // Keep track of used but undefined variables. We make a hole in
9314 // the warning for static const data members with in-line
9315 // initializers.
John McCall83779672011-02-19 02:53:41 +00009316 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009317 && Var->getLinkage() != ExternalLinkage
9318 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009319 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9320 if (old.isInvalid()) old = Loc;
9321 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009322
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009323 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009324 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009325 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009326}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009327
Douglas Gregor5597ab42010-05-07 23:12:07 +00009328namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009329 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009330 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009331 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009332 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9333 Sema &S;
9334 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009335
Douglas Gregor5597ab42010-05-07 23:12:07 +00009336 public:
9337 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009338
Douglas Gregor5597ab42010-05-07 23:12:07 +00009339 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009340
9341 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9342 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009343 };
9344}
9345
Chandler Carruthaf80f662010-06-09 08:17:30 +00009346bool MarkReferencedDecls::TraverseTemplateArgument(
9347 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009348 if (Arg.getKind() == TemplateArgument::Declaration) {
9349 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9350 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009351
9352 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009353}
9354
Chandler Carruthaf80f662010-06-09 08:17:30 +00009355bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009356 if (ClassTemplateSpecializationDecl *Spec
9357 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9358 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009359 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009360 }
9361
Chandler Carruthc65667c2010-06-10 10:31:57 +00009362 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009363}
9364
9365void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9366 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009367 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009368}
9369
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009370namespace {
9371 /// \brief Helper class that marks all of the declarations referenced by
9372 /// potentially-evaluated subexpressions as "referenced".
9373 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9374 Sema &S;
9375
9376 public:
9377 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9378
9379 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9380
9381 void VisitDeclRefExpr(DeclRefExpr *E) {
9382 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9383 }
9384
9385 void VisitMemberExpr(MemberExpr *E) {
9386 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009387 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009388 }
9389
9390 void VisitCXXNewExpr(CXXNewExpr *E) {
9391 if (E->getConstructor())
9392 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9393 if (E->getOperatorNew())
9394 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9395 if (E->getOperatorDelete())
9396 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009397 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009398 }
9399
9400 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9401 if (E->getOperatorDelete())
9402 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009403 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9404 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9405 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9406 S.MarkDeclarationReferenced(E->getLocStart(),
9407 S.LookupDestructor(Record));
9408 }
9409
Douglas Gregor32b3de52010-09-11 23:32:50 +00009410 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009411 }
9412
9413 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9414 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009415 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009416 }
9417
9418 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9419 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9420 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009421
9422 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9423 Visit(E->getExpr());
9424 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009425 };
9426}
9427
9428/// \brief Mark any declarations that appear within this expression or any
9429/// potentially-evaluated subexpressions as "referenced".
9430void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9431 EvaluatedExprMarker(*this).Visit(E);
9432}
9433
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009434/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9435/// of the program being compiled.
9436///
9437/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009438/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009439/// possibility that the code will actually be executable. Code in sizeof()
9440/// expressions, code used only during overload resolution, etc., are not
9441/// potentially evaluated. This routine will suppress such diagnostics or,
9442/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009443/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009444/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009445///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009446/// This routine should be used for all diagnostics that describe the run-time
9447/// behavior of a program, such as passing a non-POD value through an ellipsis.
9448/// Failure to do so will likely result in spurious diagnostics or failures
9449/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009450bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009451 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009452 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009453 case Unevaluated:
9454 // The argument will never be evaluated, so don't complain.
9455 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009456
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009457 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009458 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009459 if (stmt && getCurFunctionOrMethodDecl()) {
9460 FunctionScopes.back()->PossiblyUnreachableDiags.
9461 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9462 }
9463 else
9464 Diag(Loc, PD);
9465
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009466 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009467
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009468 case PotentiallyPotentiallyEvaluated:
9469 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9470 break;
9471 }
9472
9473 return false;
9474}
9475
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009476bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9477 CallExpr *CE, FunctionDecl *FD) {
9478 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9479 return false;
9480
9481 PartialDiagnostic Note =
9482 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9483 << FD->getDeclName() : PDiag();
9484 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009485
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009486 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009487 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009488 PDiag(diag::err_call_function_incomplete_return)
9489 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009490 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009491 << CE->getSourceRange(),
9492 std::make_pair(NoteLoc, Note)))
9493 return true;
9494
9495 return false;
9496}
9497
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009498// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009499// will prevent this condition from triggering, which is what we want.
9500void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9501 SourceLocation Loc;
9502
John McCall0506e4a2009-11-11 02:41:58 +00009503 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009504 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009505
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009506 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009507 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009508 return;
9509
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009510 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9511
John McCallb0e419e2009-11-12 00:06:05 +00009512 // Greylist some idioms by putting them into a warning subcategory.
9513 if (ObjCMessageExpr *ME
9514 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9515 Selector Sel = ME->getSelector();
9516
John McCallb0e419e2009-11-12 00:06:05 +00009517 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009518 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009519 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9520
9521 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009522 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009523 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9524 }
John McCall0506e4a2009-11-11 02:41:58 +00009525
John McCalld5707ab2009-10-12 21:59:07 +00009526 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009527 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009528 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009529 return;
9530
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009531 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009532 Loc = Op->getOperatorLoc();
9533 } else {
9534 // Not an assignment.
9535 return;
9536 }
9537
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009538 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009539
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009540 SourceLocation Open = E->getSourceRange().getBegin();
9541 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9542 Diag(Loc, diag::note_condition_assign_silence)
9543 << FixItHint::CreateInsertion(Open, "(")
9544 << FixItHint::CreateInsertion(Close, ")");
9545
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009546 if (IsOrAssign)
9547 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9548 << FixItHint::CreateReplacement(Loc, "!=");
9549 else
9550 Diag(Loc, diag::note_condition_assign_to_comparison)
9551 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009552}
9553
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009554/// \brief Redundant parentheses over an equality comparison can indicate
9555/// that the user intended an assignment used as condition.
9556void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009557 // Don't warn if the parens came from a macro.
9558 SourceLocation parenLoc = parenE->getLocStart();
9559 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9560 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009561 // Don't warn for dependent expressions.
9562 if (parenE->isTypeDependent())
9563 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009564
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009565 Expr *E = parenE->IgnoreParens();
9566
9567 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009568 if (opE->getOpcode() == BO_EQ &&
9569 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9570 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009571 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009572
Ted Kremenekae022092011-02-02 02:20:30 +00009573 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009574 Diag(Loc, diag::note_equality_comparison_silence)
9575 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9576 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009577 Diag(Loc, diag::note_equality_comparison_to_assign)
9578 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009579 }
9580}
9581
John Wiegley01296292011-04-08 18:41:53 +00009582ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009583 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009584 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9585 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009586
John McCall0009fcc2011-04-26 20:42:42 +00009587 ExprResult result = CheckPlaceholderExpr(E);
9588 if (result.isInvalid()) return ExprError();
9589 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009590
John McCall0009fcc2011-04-26 20:42:42 +00009591 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009592 if (getLangOptions().CPlusPlus)
9593 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9594
John Wiegley01296292011-04-08 18:41:53 +00009595 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9596 if (ERes.isInvalid())
9597 return ExprError();
9598 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009599
9600 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009601 if (!T->isScalarType()) { // C99 6.8.4.1p1
9602 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9603 << T << E->getSourceRange();
9604 return ExprError();
9605 }
John McCalld5707ab2009-10-12 21:59:07 +00009606 }
9607
John Wiegley01296292011-04-08 18:41:53 +00009608 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009609}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009610
John McCalldadc5752010-08-24 06:29:42 +00009611ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9612 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009613 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009614 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009615
9616 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009617}
John McCall36e7fe32010-10-12 00:20:44 +00009618
John McCall31996342011-04-07 08:22:57 +00009619namespace {
John McCall2979fe02011-04-12 00:42:48 +00009620 /// A visitor for rebuilding a call to an __unknown_any expression
9621 /// to have an appropriate type.
9622 struct RebuildUnknownAnyFunction
9623 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9624
9625 Sema &S;
9626
9627 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9628
9629 ExprResult VisitStmt(Stmt *S) {
9630 llvm_unreachable("unexpected statement!");
9631 return ExprError();
9632 }
9633
9634 ExprResult VisitExpr(Expr *expr) {
9635 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9636 << expr->getSourceRange();
9637 return ExprError();
9638 }
9639
9640 /// Rebuild an expression which simply semantically wraps another
9641 /// expression which it shares the type and value kind of.
9642 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9643 ExprResult subResult = Visit(expr->getSubExpr());
9644 if (subResult.isInvalid()) return ExprError();
9645
9646 Expr *subExpr = subResult.take();
9647 expr->setSubExpr(subExpr);
9648 expr->setType(subExpr->getType());
9649 expr->setValueKind(subExpr->getValueKind());
9650 assert(expr->getObjectKind() == OK_Ordinary);
9651 return expr;
9652 }
9653
9654 ExprResult VisitParenExpr(ParenExpr *paren) {
9655 return rebuildSugarExpr(paren);
9656 }
9657
9658 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9659 return rebuildSugarExpr(op);
9660 }
9661
9662 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9663 ExprResult subResult = Visit(op->getSubExpr());
9664 if (subResult.isInvalid()) return ExprError();
9665
9666 Expr *subExpr = subResult.take();
9667 op->setSubExpr(subExpr);
9668 op->setType(S.Context.getPointerType(subExpr->getType()));
9669 assert(op->getValueKind() == VK_RValue);
9670 assert(op->getObjectKind() == OK_Ordinary);
9671 return op;
9672 }
9673
9674 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9675 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9676
9677 expr->setType(decl->getType());
9678
9679 assert(expr->getValueKind() == VK_RValue);
9680 if (S.getLangOptions().CPlusPlus &&
9681 !(isa<CXXMethodDecl>(decl) &&
9682 cast<CXXMethodDecl>(decl)->isInstance()))
9683 expr->setValueKind(VK_LValue);
9684
9685 return expr;
9686 }
9687
9688 ExprResult VisitMemberExpr(MemberExpr *mem) {
9689 return resolveDecl(mem, mem->getMemberDecl());
9690 }
9691
9692 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9693 return resolveDecl(ref, ref->getDecl());
9694 }
9695 };
9696}
9697
9698/// Given a function expression of unknown-any type, try to rebuild it
9699/// to have a function type.
9700static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9701 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9702 if (result.isInvalid()) return ExprError();
9703 return S.DefaultFunctionArrayConversion(result.take());
9704}
9705
9706namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009707 /// A visitor for rebuilding an expression of type __unknown_anytype
9708 /// into one which resolves the type directly on the referring
9709 /// expression. Strict preservation of the original source
9710 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009711 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009712 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009713
9714 Sema &S;
9715
9716 /// The current destination type.
9717 QualType DestType;
9718
9719 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9720 : S(S), DestType(castType) {}
9721
John McCall39439732011-04-09 22:50:59 +00009722 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009723 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009724 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009725 }
9726
John McCall2d2e8702011-04-11 07:02:50 +00009727 ExprResult VisitExpr(Expr *expr) {
9728 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9729 << expr->getSourceRange();
9730 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009731 }
9732
John McCall2d2e8702011-04-11 07:02:50 +00009733 ExprResult VisitCallExpr(CallExpr *call);
9734 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9735
John McCall39439732011-04-09 22:50:59 +00009736 /// Rebuild an expression which simply semantically wraps another
9737 /// expression which it shares the type and value kind of.
9738 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9739 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009740 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009741 Expr *subExpr = subResult.take();
9742 expr->setSubExpr(subExpr);
9743 expr->setType(subExpr->getType());
9744 expr->setValueKind(subExpr->getValueKind());
9745 assert(expr->getObjectKind() == OK_Ordinary);
9746 return expr;
9747 }
John McCall31996342011-04-07 08:22:57 +00009748
John McCall39439732011-04-09 22:50:59 +00009749 ExprResult VisitParenExpr(ParenExpr *paren) {
9750 return rebuildSugarExpr(paren);
9751 }
9752
9753 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9754 return rebuildSugarExpr(op);
9755 }
9756
John McCall2979fe02011-04-12 00:42:48 +00009757 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9758 const PointerType *ptr = DestType->getAs<PointerType>();
9759 if (!ptr) {
9760 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9761 << op->getSourceRange();
9762 return ExprError();
9763 }
9764 assert(op->getValueKind() == VK_RValue);
9765 assert(op->getObjectKind() == OK_Ordinary);
9766 op->setType(DestType);
9767
9768 // Build the sub-expression as if it were an object of the pointee type.
9769 DestType = ptr->getPointeeType();
9770 ExprResult subResult = Visit(op->getSubExpr());
9771 if (subResult.isInvalid()) return ExprError();
9772 op->setSubExpr(subResult.take());
9773 return op;
9774 }
9775
John McCall2d2e8702011-04-11 07:02:50 +00009776 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009777
John McCall2979fe02011-04-12 00:42:48 +00009778 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009779
John McCall2979fe02011-04-12 00:42:48 +00009780 ExprResult VisitMemberExpr(MemberExpr *mem) {
9781 return resolveDecl(mem, mem->getMemberDecl());
9782 }
John McCall39439732011-04-09 22:50:59 +00009783
9784 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009785 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009786 }
9787 };
9788}
9789
John McCall2d2e8702011-04-11 07:02:50 +00009790/// Rebuilds a call expression which yielded __unknown_anytype.
9791ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9792 Expr *callee = call->getCallee();
9793
9794 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009795 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009796 FK_FunctionPointer,
9797 FK_BlockPointer
9798 };
9799
9800 FnKind kind;
9801 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009802 if (type == S.Context.BoundMemberTy) {
9803 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9804 kind = FK_MemberFunction;
9805 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009806 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9807 type = ptr->getPointeeType();
9808 kind = FK_FunctionPointer;
9809 } else {
9810 type = type->castAs<BlockPointerType>()->getPointeeType();
9811 kind = FK_BlockPointer;
9812 }
9813 const FunctionType *fnType = type->castAs<FunctionType>();
9814
9815 // Verify that this is a legal result type of a function.
9816 if (DestType->isArrayType() || DestType->isFunctionType()) {
9817 unsigned diagID = diag::err_func_returning_array_function;
9818 if (kind == FK_BlockPointer)
9819 diagID = diag::err_block_returning_array_function;
9820
9821 S.Diag(call->getExprLoc(), diagID)
9822 << DestType->isFunctionType() << DestType;
9823 return ExprError();
9824 }
9825
9826 // Otherwise, go ahead and set DestType as the call's result.
9827 call->setType(DestType.getNonLValueExprType(S.Context));
9828 call->setValueKind(Expr::getValueKindForType(DestType));
9829 assert(call->getObjectKind() == OK_Ordinary);
9830
9831 // Rebuild the function type, replacing the result type with DestType.
9832 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9833 DestType = S.Context.getFunctionType(DestType,
9834 proto->arg_type_begin(),
9835 proto->getNumArgs(),
9836 proto->getExtProtoInfo());
9837 else
9838 DestType = S.Context.getFunctionNoProtoType(DestType,
9839 fnType->getExtInfo());
9840
9841 // Rebuild the appropriate pointer-to-function type.
9842 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009843 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009844 // Nothing to do.
9845 break;
9846
9847 case FK_FunctionPointer:
9848 DestType = S.Context.getPointerType(DestType);
9849 break;
9850
9851 case FK_BlockPointer:
9852 DestType = S.Context.getBlockPointerType(DestType);
9853 break;
9854 }
9855
9856 // Finally, we can recurse.
9857 ExprResult calleeResult = Visit(callee);
9858 if (!calleeResult.isUsable()) return ExprError();
9859 call->setCallee(calleeResult.take());
9860
9861 // Bind a temporary if necessary.
9862 return S.MaybeBindToTemporary(call);
9863}
9864
9865ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009866 // Verify that this is a legal result type of a call.
9867 if (DestType->isArrayType() || DestType->isFunctionType()) {
9868 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9869 << DestType->isFunctionType() << DestType;
9870 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009871 }
9872
John McCall3f4138c2011-07-13 17:56:40 +00009873 // Rewrite the method result type if available.
9874 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9875 assert(method->getResultType() == S.Context.UnknownAnyTy);
9876 method->setResultType(DestType);
9877 }
John McCall2979fe02011-04-12 00:42:48 +00009878
John McCall2d2e8702011-04-11 07:02:50 +00009879 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009880 msg->setType(DestType.getNonReferenceType());
9881 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009882
John McCall2979fe02011-04-12 00:42:48 +00009883 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009884}
9885
9886ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009887 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009888 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009889 assert(ice->getValueKind() == VK_RValue);
9890 assert(ice->getObjectKind() == OK_Ordinary);
9891
John McCall2979fe02011-04-12 00:42:48 +00009892 ice->setType(DestType);
9893
John McCall2d2e8702011-04-11 07:02:50 +00009894 // Rebuild the sub-expression as the pointee (function) type.
9895 DestType = DestType->castAs<PointerType>()->getPointeeType();
9896
9897 ExprResult result = Visit(ice->getSubExpr());
9898 if (!result.isUsable()) return ExprError();
9899
9900 ice->setSubExpr(result.take());
9901 return S.Owned(ice);
9902}
9903
John McCall2979fe02011-04-12 00:42:48 +00009904ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009905 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009906 QualType type = DestType;
9907
9908 // We know how to make this work for certain kinds of decls:
9909
9910 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009911 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall9a877fe2011-08-10 04:12:23 +00009912 if (const PointerType *ptr = type->getAs<PointerType>()) {
9913 DestType = ptr->getPointeeType();
9914 ExprResult result = resolveDecl(expr, decl);
9915 if (result.isInvalid()) return ExprError();
9916 return S.ImpCastExprToType(result.take(), type,
9917 CK_FunctionToPointerDecay, VK_RValue);
9918 }
9919
9920 if (!type->isFunctionType()) {
9921 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9922 << decl << expr->getSourceRange();
9923 return ExprError();
9924 }
John McCall2d2e8702011-04-11 07:02:50 +00009925
John McCall4adb38c2011-04-27 00:36:17 +00009926 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9927 if (method->isInstance()) {
9928 valueKind = VK_RValue;
9929 type = S.Context.BoundMemberTy;
9930 }
9931
John McCall2d2e8702011-04-11 07:02:50 +00009932 // Function references aren't l-values in C.
9933 if (!S.getLangOptions().CPlusPlus)
9934 valueKind = VK_RValue;
9935
9936 // - variables
9937 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009938 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9939 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009940 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009941 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9942 << decl << expr->getSourceRange();
9943 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009944 }
9945
9946 // - nothing else
9947 } else {
9948 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9949 << decl << expr->getSourceRange();
9950 return ExprError();
9951 }
9952
John McCall2979fe02011-04-12 00:42:48 +00009953 decl->setType(DestType);
9954 expr->setType(type);
9955 expr->setValueKind(valueKind);
9956 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009957}
9958
John McCall31996342011-04-07 08:22:57 +00009959/// Check a cast of an unknown-any type. We intentionally only
9960/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009961ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9962 Expr *castExpr, CastKind &castKind,
9963 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009964 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009965 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9966 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009967
John McCall39439732011-04-09 22:50:59 +00009968 castExpr = result.take();
9969 VK = castExpr->getValueKind();
9970 castKind = CK_NoOp;
9971
9972 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009973}
9974
9975static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9976 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009977 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009978 while (true) {
9979 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009980 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009981 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009982 diagID = diag::err_uncasted_call_of_unknown_any;
9983 } else {
John McCall31996342011-04-07 08:22:57 +00009984 break;
John McCall2d2e8702011-04-11 07:02:50 +00009985 }
John McCall31996342011-04-07 08:22:57 +00009986 }
9987
John McCall2d2e8702011-04-11 07:02:50 +00009988 SourceLocation loc;
9989 NamedDecl *d;
9990 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9991 loc = ref->getLocation();
9992 d = ref->getDecl();
9993 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9994 loc = mem->getMemberLoc();
9995 d = mem->getMemberDecl();
9996 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9997 diagID = diag::err_uncasted_call_of_unknown_any;
9998 loc = msg->getSelectorLoc();
9999 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010000 if (!d) {
10001 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10002 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10003 << orig->getSourceRange();
10004 return ExprError();
10005 }
John McCall2d2e8702011-04-11 07:02:50 +000010006 } else {
10007 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10008 << e->getSourceRange();
10009 return ExprError();
10010 }
10011
10012 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010013
10014 // Never recoverable.
10015 return ExprError();
10016}
10017
John McCall36e7fe32010-10-12 00:20:44 +000010018/// Check for operands with placeholder types and complain if found.
10019/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010020ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010021 // Placeholder types are always *exactly* the appropriate builtin type.
10022 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010023
John McCall31996342011-04-07 08:22:57 +000010024 // Overloaded expressions.
10025 if (type == Context.OverloadTy)
10026 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010027 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010028 QualType(),
10029 diag::err_ovl_unresolvable);
10030
John McCall0009fcc2011-04-26 20:42:42 +000010031 // Bound member functions.
10032 if (type == Context.BoundMemberTy) {
10033 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10034 << E->getSourceRange();
10035 return ExprError();
10036 }
10037
John McCall31996342011-04-07 08:22:57 +000010038 // Expressions of unknown type.
10039 if (type == Context.UnknownAnyTy)
10040 return diagnoseUnknownAnyExpr(*this, E);
10041
10042 assert(!type->isPlaceholderType());
10043 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010044}
Richard Trieu2c850c02011-04-21 21:44:26 +000010045
10046bool Sema::CheckCaseExpression(Expr *expr) {
10047 if (expr->isTypeDependent())
10048 return true;
10049 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10050 return expr->getType()->isIntegralOrEnumerationType();
10051 return false;
10052}