blob: 43e3807e21d5c4640f0bb67c8737935479b5e14c [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);
John McCall27584242010-12-06 20:48:59 +0000325 QualType T = E->getType();
326 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000327
John McCall27584242010-12-06 20:48:59 +0000328 // Create a load out of an ObjCProperty l-value, if necessary.
329 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000330 ExprResult Res = ConvertPropertyForRValue(E);
331 if (Res.isInvalid())
332 return Owned(E);
333 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000334 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000335 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000336 }
John McCall27584242010-12-06 20:48:59 +0000337
338 // We don't want to throw lvalue-to-rvalue casts on top of
339 // expressions of certain types in C++.
340 if (getLangOptions().CPlusPlus &&
341 (E->getType() == Context.OverloadTy ||
342 T->isDependentType() ||
343 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000344 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000345
346 // The C standard is actually really unclear on this point, and
347 // DR106 tells us what the result should be but not why. It's
348 // generally best to say that void types just doesn't undergo
349 // lvalue-to-rvalue at all. Note that expressions of unqualified
350 // 'void' type are never l-values, but qualified void can be.
351 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000352 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000353
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000354 CheckForNullPointerDereference(*this, E);
355
John McCall27584242010-12-06 20:48:59 +0000356 // C++ [conv.lval]p1:
357 // [...] If T is a non-class type, the type of the prvalue is the
358 // cv-unqualified version of T. Otherwise, the type of the
359 // rvalue is T.
360 //
361 // C99 6.3.2.1p2:
362 // If the lvalue has qualified type, the value has the unqualified
363 // version of the type of the lvalue; otherwise, the value has the
364 // type of the lvalue.
365 if (T.hasQualifiers())
366 T = T.getUnqualifiedType();
367
Ted Kremenekdf26df72011-03-01 18:41:00 +0000368 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000369
John Wiegley01296292011-04-08 18:41:53 +0000370 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
371 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000372}
373
John Wiegley01296292011-04-08 18:41:53 +0000374ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
375 ExprResult Res = DefaultFunctionArrayConversion(E);
376 if (Res.isInvalid())
377 return ExprError();
378 Res = DefaultLvalueConversion(Res.take());
379 if (Res.isInvalid())
380 return ExprError();
381 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000382}
383
384
Chris Lattner513165e2008-07-25 21:10:04 +0000385/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000386/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000387/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000388/// apply if the array is an argument to the sizeof or address (&) operators.
389/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000390ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000391 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000392 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
393 if (Res.isInvalid())
394 return Owned(E);
395 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000396
397 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000398 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000399
400 // Try to perform integral promotions if the object has a theoretically
401 // promotable type.
402 if (Ty->isIntegralOrUnscopedEnumerationType()) {
403 // C99 6.3.1.1p2:
404 //
405 // The following may be used in an expression wherever an int or
406 // unsigned int may be used:
407 // - an object or expression with an integer type whose integer
408 // conversion rank is less than or equal to the rank of int
409 // and unsigned int.
410 // - A bit-field of type _Bool, int, signed int, or unsigned int.
411 //
412 // If an int can represent all values of the original type, the
413 // value is converted to an int; otherwise, it is converted to an
414 // unsigned int. These are called the integer promotions. All
415 // other types are unchanged by the integer promotions.
416
417 QualType PTy = Context.isPromotableBitField(E);
418 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000419 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
420 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000421 }
422 if (Ty->isPromotableIntegerType()) {
423 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000424 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
425 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000426 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000427 }
John Wiegley01296292011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000429}
430
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000432/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000433/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000434ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
435 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000436 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000437
John Wiegley01296292011-04-08 18:41:53 +0000438 ExprResult Res = UsualUnaryConversions(E);
439 if (Res.isInvalid())
440 return Owned(E);
441 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000442
Chris Lattner2ce500f2008-07-25 22:25:12 +0000443 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000444 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000445 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
446
447 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000448}
449
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000450/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
451/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000452/// interfaces passed by value.
453ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000454 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000455 ExprResult ExprRes = CheckPlaceholderExpr(E);
456 if (ExprRes.isInvalid())
457 return ExprError();
458
459 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000460 if (ExprRes.isInvalid())
461 return ExprError();
462 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000464 // __builtin_va_start takes the second argument as a "varargs" argument, but
465 // it doesn't actually do anything with it. It doesn't need to be non-pod
466 // etc.
467 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000469
Douglas Gregor347e0f22011-05-21 19:26:31 +0000470 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000471 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000472 DiagRuntimeBehavior(E->getLocStart(), 0,
473 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
474 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000475 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000476
John McCall31168b02011-06-15 23:02:42 +0000477 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000478 // C++0x [expr.call]p7:
479 // Passing a potentially-evaluated argument of class type (Clause 9)
480 // having a non-trivial copy constructor, a non-trivial move constructor,
481 // or a non-trivial destructor, with no corresponding parameter,
482 // is conditionally-supported with implementation-defined semantics.
483 bool TrivialEnough = false;
484 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
485 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
486 if (Record->hasTrivialCopyConstructor() &&
487 Record->hasTrivialMoveConstructor() &&
488 Record->hasTrivialDestructor())
489 TrivialEnough = true;
490 }
491 }
John McCall31168b02011-06-15 23:02:42 +0000492
493 if (!TrivialEnough &&
494 getLangOptions().ObjCAutoRefCount &&
495 E->getType()->isObjCLifetimeType())
496 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000497
498 if (TrivialEnough) {
499 // Nothing to diagnose. This is okay.
500 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000501 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000502 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000503 << CT)) {
504 // Turn this into a trap.
505 CXXScopeSpec SS;
506 UnqualifiedId Name;
507 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
508 E->getLocStart());
509 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
510 if (TrapFn.isInvalid())
511 return ExprError();
512
513 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
514 MultiExprArg(), E->getLocEnd());
515 if (Call.isInvalid())
516 return ExprError();
517
518 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
519 Call.get(), E);
520 if (Comma.isInvalid())
521 return ExprError();
522
523 E = Comma.get();
524 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000525 }
526
John Wiegley01296292011-04-08 18:41:53 +0000527 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000528}
529
Chris Lattner513165e2008-07-25 21:10:04 +0000530/// UsualArithmeticConversions - Performs various conversions that are common to
531/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000532/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000533/// responsible for emitting appropriate error diagnostics.
534/// FIXME: verify the conversion rules for "complex int" are consistent with
535/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000536QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000537 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000538 if (!isCompAssign) {
539 lhsExpr = UsualUnaryConversions(lhsExpr.take());
540 if (lhsExpr.isInvalid())
541 return QualType();
542 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000543
John Wiegley01296292011-04-08 18:41:53 +0000544 rhsExpr = UsualUnaryConversions(rhsExpr.take());
545 if (rhsExpr.isInvalid())
546 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000547
Mike Stump11289f42009-09-09 15:08:12 +0000548 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000549 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000550 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000551 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000552 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000553 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000554
555 // If both types are identical, no conversion is needed.
556 if (lhs == rhs)
557 return lhs;
558
559 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
560 // The caller can deal with this (e.g. pointer + int).
561 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
562 return lhs;
563
John McCalld005ac92010-11-13 08:17:45 +0000564 // Apply unary and bitfield promotions to the LHS's type.
565 QualType lhs_unpromoted = lhs;
566 if (lhs->isPromotableIntegerType())
567 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000568 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000569 if (!LHSBitfieldPromoteTy.isNull())
570 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000571 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000572 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000573
John McCalld005ac92010-11-13 08:17:45 +0000574 // If both types are identical, no conversion is needed.
575 if (lhs == rhs)
576 return lhs;
577
578 // At this point, we have two different arithmetic types.
579
580 // Handle complex types first (C99 6.3.1.8p1).
581 bool LHSComplexFloat = lhs->isComplexType();
582 bool RHSComplexFloat = rhs->isComplexType();
583 if (LHSComplexFloat || RHSComplexFloat) {
584 // if we have an integer operand, the result is the complex type.
585
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
587 if (rhs->isIntegerType()) {
588 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000589 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
590 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000591 } else {
592 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000593 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000594 }
John McCalld005ac92010-11-13 08:17:45 +0000595 return lhs;
596 }
597
John McCallc5e62b42010-11-13 09:02:35 +0000598 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
599 if (!isCompAssign) {
600 // int -> float -> _Complex float
601 if (lhs->isIntegerType()) {
602 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000603 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
604 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000605 } else {
606 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000607 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000608 }
609 }
John McCalld005ac92010-11-13 08:17:45 +0000610 return rhs;
611 }
612
613 // This handles complex/complex, complex/float, or float/complex.
614 // When both operands are complex, the shorter operand is converted to the
615 // type of the longer, and that is the type of the result. This corresponds
616 // to what is done when combining two real floating-point operands.
617 // The fun begins when size promotion occur across type domains.
618 // From H&S 6.3.4: When one operand is complex and the other is a real
619 // floating-point type, the less precise type is converted, within it's
620 // real or complex domain, to the precision of the other type. For example,
621 // when combining a "long double" with a "double _Complex", the
622 // "double _Complex" is promoted to "long double _Complex".
623 int order = Context.getFloatingTypeOrder(lhs, rhs);
624
625 // If both are complex, just cast to the more precise type.
626 if (LHSComplexFloat && RHSComplexFloat) {
627 if (order > 0) {
628 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000629 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000630 return lhs;
631
632 } else if (order < 0) {
633 // _Complex float -> _Complex double
634 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000635 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000636 return rhs;
637 }
638 return lhs;
639 }
640
641 // If just the LHS is complex, the RHS needs to be converted,
642 // and the LHS might need to be promoted.
643 if (LHSComplexFloat) {
644 if (order > 0) { // LHS is wider
645 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000646 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000647 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
648 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000649 return lhs;
650 }
651
652 // RHS is at least as wide. Find its corresponding complex type.
653 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
654
655 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000656 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000657
658 // _Complex float -> _Complex double
659 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000660 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000661
662 return result;
663 }
664
665 // Just the RHS is complex, so the LHS needs to be converted
666 // and the RHS might need to be promoted.
667 assert(RHSComplexFloat);
668
669 if (order < 0) { // RHS is wider
670 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000671 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000672 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000673 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
674 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000675 }
John McCalld005ac92010-11-13 08:17:45 +0000676 return rhs;
677 }
678
679 // LHS is at least as wide. Find its corresponding complex type.
680 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
681
682 // double -> _Complex double
683 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000685
686 // _Complex float -> _Complex double
687 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000688 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000689
690 return result;
691 }
692
693 // Now handle "real" floating types (i.e. float, double, long double).
694 bool LHSFloat = lhs->isRealFloatingType();
695 bool RHSFloat = rhs->isRealFloatingType();
696 if (LHSFloat || RHSFloat) {
697 // If we have two real floating types, convert the smaller operand
698 // to the bigger result.
699 if (LHSFloat && RHSFloat) {
700 int order = Context.getFloatingTypeOrder(lhs, rhs);
701 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000702 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000703 return lhs;
704 }
705
706 assert(order < 0 && "illegal float comparison");
707 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000708 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000709 return rhs;
710 }
711
712 // If we have an integer operand, the result is the real floating type.
713 if (LHSFloat) {
714 if (rhs->isIntegerType()) {
715 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000716 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000717 return lhs;
718 }
719
720 // Convert both sides to the appropriate complex float.
721 assert(rhs->isComplexIntegerType());
722 QualType result = Context.getComplexType(lhs);
723
724 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000725 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000726
727 // float -> _Complex float
728 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000729 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000730
731 return result;
732 }
733
734 assert(RHSFloat);
735 if (lhs->isIntegerType()) {
736 // Convert lhs to the rhs floating point type.
737 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000738 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000739 return rhs;
740 }
741
742 // Convert both sides to the appropriate complex float.
743 assert(lhs->isComplexIntegerType());
744 QualType result = Context.getComplexType(rhs);
745
746 // _Complex int -> _Complex float
747 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000748 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000749
750 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000751 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000752
753 return result;
754 }
755
756 // Handle GCC complex int extension.
757 // FIXME: if the operands are (int, _Complex long), we currently
758 // don't promote the complex. Also, signedness?
759 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
760 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
761 if (lhsComplexInt && rhsComplexInt) {
762 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
763 rhsComplexInt->getElementType());
764 assert(order && "inequal types with equal element ordering");
765 if (order > 0) {
766 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000767 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000768 return lhs;
769 }
770
771 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000772 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000773 return rhs;
774 } else if (lhsComplexInt) {
775 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000776 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000777 return lhs;
778 } else if (rhsComplexInt) {
779 // int -> _Complex int
780 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000781 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000782 return rhs;
783 }
784
785 // Finally, we have two differing integer types.
786 // The rules for this case are in C99 6.3.1.8
787 int compare = Context.getIntegerTypeOrder(lhs, rhs);
788 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
789 rhsSigned = rhs->hasSignedIntegerRepresentation();
790 if (lhsSigned == rhsSigned) {
791 // Same signedness; use the higher-ranked type
792 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000793 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000794 return lhs;
795 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000796 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000797 return rhs;
798 } else if (compare != (lhsSigned ? 1 : -1)) {
799 // The unsigned type has greater than or equal rank to the
800 // signed type, so use the unsigned type
801 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000802 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000803 return lhs;
804 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000805 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000806 return rhs;
807 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
808 // 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.
811 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000812 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000813 return lhs;
814 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000816 return rhs;
817 } 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 =
823 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000824 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000825 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000826 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000827 return result;
828 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000829}
830
Chris Lattner513165e2008-07-25 21:10:04 +0000831//===----------------------------------------------------------------------===//
832// Semantic Analysis for various Expression Types
833//===----------------------------------------------------------------------===//
834
835
Peter Collingbourne91147592011-04-15 00:35:48 +0000836ExprResult
837Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
838 SourceLocation DefaultLoc,
839 SourceLocation RParenLoc,
840 Expr *ControllingExpr,
841 MultiTypeArg types,
842 MultiExprArg exprs) {
843 unsigned NumAssocs = types.size();
844 assert(NumAssocs == exprs.size());
845
846 ParsedType *ParsedTypes = types.release();
847 Expr **Exprs = exprs.release();
848
849 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
850 for (unsigned i = 0; i < NumAssocs; ++i) {
851 if (ParsedTypes[i])
852 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
853 else
854 Types[i] = 0;
855 }
856
857 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
858 ControllingExpr, Types, Exprs,
859 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000860 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000861 return ER;
862}
863
864ExprResult
865Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
866 SourceLocation DefaultLoc,
867 SourceLocation RParenLoc,
868 Expr *ControllingExpr,
869 TypeSourceInfo **Types,
870 Expr **Exprs,
871 unsigned NumAssocs) {
872 bool TypeErrorFound = false,
873 IsResultDependent = ControllingExpr->isTypeDependent(),
874 ContainsUnexpandedParameterPack
875 = ControllingExpr->containsUnexpandedParameterPack();
876
877 for (unsigned i = 0; i < NumAssocs; ++i) {
878 if (Exprs[i]->containsUnexpandedParameterPack())
879 ContainsUnexpandedParameterPack = true;
880
881 if (Types[i]) {
882 if (Types[i]->getType()->containsUnexpandedParameterPack())
883 ContainsUnexpandedParameterPack = true;
884
885 if (Types[i]->getType()->isDependentType()) {
886 IsResultDependent = true;
887 } else {
888 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
889 // complete object type other than a variably modified type."
890 unsigned D = 0;
891 if (Types[i]->getType()->isIncompleteType())
892 D = diag::err_assoc_type_incomplete;
893 else if (!Types[i]->getType()->isObjectType())
894 D = diag::err_assoc_type_nonobject;
895 else if (Types[i]->getType()->isVariablyModifiedType())
896 D = diag::err_assoc_type_variably_modified;
897
898 if (D != 0) {
899 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
900 << Types[i]->getTypeLoc().getSourceRange()
901 << Types[i]->getType();
902 TypeErrorFound = true;
903 }
904
905 // C1X 6.5.1.1p2 "No two generic associations in the same generic
906 // selection shall specify compatible types."
907 for (unsigned j = i+1; j < NumAssocs; ++j)
908 if (Types[j] && !Types[j]->getType()->isDependentType() &&
909 Context.typesAreCompatible(Types[i]->getType(),
910 Types[j]->getType())) {
911 Diag(Types[j]->getTypeLoc().getBeginLoc(),
912 diag::err_assoc_compatible_types)
913 << Types[j]->getTypeLoc().getSourceRange()
914 << Types[j]->getType()
915 << Types[i]->getType();
916 Diag(Types[i]->getTypeLoc().getBeginLoc(),
917 diag::note_compat_assoc)
918 << Types[i]->getTypeLoc().getSourceRange()
919 << Types[i]->getType();
920 TypeErrorFound = true;
921 }
922 }
923 }
924 }
925 if (TypeErrorFound)
926 return ExprError();
927
928 // If we determined that the generic selection is result-dependent, don't
929 // try to compute the result expression.
930 if (IsResultDependent)
931 return Owned(new (Context) GenericSelectionExpr(
932 Context, KeyLoc, ControllingExpr,
933 Types, Exprs, NumAssocs, DefaultLoc,
934 RParenLoc, ContainsUnexpandedParameterPack));
935
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000936 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000937 unsigned DefaultIndex = -1U;
938 for (unsigned i = 0; i < NumAssocs; ++i) {
939 if (!Types[i])
940 DefaultIndex = i;
941 else if (Context.typesAreCompatible(ControllingExpr->getType(),
942 Types[i]->getType()))
943 CompatIndices.push_back(i);
944 }
945
946 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
947 // type compatible with at most one of the types named in its generic
948 // association list."
949 if (CompatIndices.size() > 1) {
950 // We strip parens here because the controlling expression is typically
951 // parenthesized in macro definitions.
952 ControllingExpr = ControllingExpr->IgnoreParens();
953 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
954 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
955 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000956 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000957 E = CompatIndices.end(); I != E; ++I) {
958 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
959 diag::note_compat_assoc)
960 << Types[*I]->getTypeLoc().getSourceRange()
961 << Types[*I]->getType();
962 }
963 return ExprError();
964 }
965
966 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
967 // its controlling expression shall have type compatible with exactly one of
968 // the types named in its generic association list."
969 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
970 // We strip parens here because the controlling expression is typically
971 // parenthesized in macro definitions.
972 ControllingExpr = ControllingExpr->IgnoreParens();
973 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
974 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
975 return ExprError();
976 }
977
978 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
979 // type name that is compatible with the type of the controlling expression,
980 // then the result expression of the generic selection is the expression
981 // in that generic association. Otherwise, the result expression of the
982 // generic selection is the expression in the default generic association."
983 unsigned ResultIndex =
984 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
985
986 return Owned(new (Context) GenericSelectionExpr(
987 Context, KeyLoc, ControllingExpr,
988 Types, Exprs, NumAssocs, DefaultLoc,
989 RParenLoc, ContainsUnexpandedParameterPack,
990 ResultIndex));
991}
992
Steve Naroff83895f72007-09-16 03:34:24 +0000993/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000994/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
995/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
996/// multiple tokens. However, the common case is that StringToks points to one
997/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000998///
John McCalldadc5752010-08-24 06:29:42 +0000999ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001000Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001001 assert(NumStringToks && "Must have at least one string!");
1002
Chris Lattner8a24e582009-01-16 18:51:42 +00001003 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001004 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001005 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001006
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001007 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001008 for (unsigned i = 0; i != NumStringToks; ++i)
1009 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001010
Chris Lattner36fc8792008-02-11 00:02:17 +00001011 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001012 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001013 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001014 else if (Literal.isUTF16())
1015 StrTy = Context.Char16Ty;
1016 else if (Literal.isUTF32())
1017 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001018 else if (Literal.Pascal)
1019 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001020
Douglas Gregorfb65e592011-07-27 05:40:30 +00001021 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1022 if (Literal.isWide())
1023 Kind = StringLiteral::Wide;
1024 else if (Literal.isUTF8())
1025 Kind = StringLiteral::UTF8;
1026 else if (Literal.isUTF16())
1027 Kind = StringLiteral::UTF16;
1028 else if (Literal.isUTF32())
1029 Kind = StringLiteral::UTF32;
1030
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001031 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001032 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001033 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001034
Chris Lattner36fc8792008-02-11 00:02:17 +00001035 // Get an array type for the string, according to C99 6.4.5. This includes
1036 // the nul terminator character as well as the string length for pascal
1037 // strings.
1038 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001039 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001040 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner5b183d82006-11-10 05:03:26 +00001042 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001043 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001044 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001045 &StringTokLocs[0],
1046 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001047}
1048
John McCallc63de662011-02-02 13:00:07 +00001049enum CaptureResult {
1050 /// No capture is required.
1051 CR_NoCapture,
1052
1053 /// A capture is required.
1054 CR_Capture,
1055
John McCall351762c2011-02-07 10:33:21 +00001056 /// A by-ref capture is required.
1057 CR_CaptureByRef,
1058
John McCallc63de662011-02-02 13:00:07 +00001059 /// An error occurred when trying to capture the given variable.
1060 CR_Error
1061};
1062
1063/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001064///
John McCallc63de662011-02-02 13:00:07 +00001065/// \param var - the variable referenced
1066/// \param DC - the context which we couldn't capture through
1067static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001068diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001069 VarDecl *var, DeclContext *DC) {
1070 switch (S.ExprEvalContexts.back().Context) {
1071 case Sema::Unevaluated:
1072 // The argument will never be evaluated, so don't complain.
1073 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001074
John McCallc63de662011-02-02 13:00:07 +00001075 case Sema::PotentiallyEvaluated:
1076 case Sema::PotentiallyEvaluatedIfUsed:
1077 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001078
John McCallc63de662011-02-02 13:00:07 +00001079 case Sema::PotentiallyPotentiallyEvaluated:
1080 // FIXME: delay these!
1081 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCallc63de662011-02-02 13:00:07 +00001084 // Don't diagnose about capture if we're not actually in code right
1085 // now; in general, there are more appropriate places that will
1086 // diagnose this.
1087 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1088
John McCall92d627e2011-03-22 23:15:50 +00001089 // Certain madnesses can happen with parameter declarations, which
1090 // we want to ignore.
1091 if (isa<ParmVarDecl>(var)) {
1092 // - If the parameter still belongs to the translation unit, then
1093 // we're actually just using one parameter in the declaration of
1094 // the next. This is useful in e.g. VLAs.
1095 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1096 return CR_NoCapture;
1097
1098 // - This particular madness can happen in ill-formed default
1099 // arguments; claim it's okay and let downstream code handle it.
1100 if (S.CurContext == var->getDeclContext()->getParent())
1101 return CR_NoCapture;
1102 }
John McCallc63de662011-02-02 13:00:07 +00001103
1104 DeclarationName functionName;
1105 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1106 functionName = fn->getDeclName();
1107 // FIXME: variable from enclosing block that we couldn't capture from!
1108
1109 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1110 << var->getIdentifier() << functionName;
1111 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1112 << var->getIdentifier();
1113
1114 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001115}
1116
John McCall351762c2011-02-07 10:33:21 +00001117/// There is a well-formed capture at a particular scope level;
1118/// propagate it through all the nested blocks.
1119static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1120 const BlockDecl::Capture &capture) {
1121 VarDecl *var = capture.getVariable();
1122
1123 // Update all the inner blocks with the capture information.
1124 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1125 i != e; ++i) {
1126 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1127 innerBlock->Captures.push_back(
1128 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1129 /*nested*/ true, capture.getCopyExpr()));
1130 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1131 }
1132
1133 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1134}
1135
1136/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001137/// given value in the current context requires a variable capture.
1138///
1139/// This also keeps the captures set in the BlockScopeInfo records
1140/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001141static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001142 ValueDecl *value) {
1143 // Only variables ever require capture.
1144 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001145 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001146
1147 // Fast path: variables from the current context never require capture.
1148 DeclContext *DC = S.CurContext;
1149 if (var->getDeclContext() == DC) return CR_NoCapture;
1150
1151 // Only variables with local storage require capture.
1152 // FIXME: What about 'const' variables in C++?
1153 if (!var->hasLocalStorage()) return CR_NoCapture;
1154
1155 // Otherwise, we need to capture.
1156
1157 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001158 do {
1159 // Only blocks (and eventually C++0x closures) can capture; other
1160 // scopes don't work.
1161 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001162 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001163
1164 BlockScopeInfo *blockScope =
1165 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1166 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1167
John McCall351762c2011-02-07 10:33:21 +00001168 // Check whether we've already captured it in this block. If so,
1169 // we're done.
1170 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1171 return propagateCapture(S, functionScopesIndex,
1172 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001173
1174 functionScopesIndex--;
1175 DC = cast<BlockDecl>(DC)->getDeclContext();
1176 } while (var->getDeclContext() != DC);
1177
John McCall351762c2011-02-07 10:33:21 +00001178 // Okay, we descended all the way to the block that defines the variable.
1179 // Actually try to capture it.
1180 QualType type = var->getType();
1181
1182 // Prohibit variably-modified types.
1183 if (type->isVariablyModifiedType()) {
1184 S.Diag(loc, diag::err_ref_vm_type);
1185 S.Diag(var->getLocation(), diag::note_declared_at);
1186 return CR_Error;
1187 }
1188
1189 // Prohibit arrays, even in __block variables, but not references to
1190 // them.
1191 if (type->isArrayType()) {
1192 S.Diag(loc, diag::err_ref_array_type);
1193 S.Diag(var->getLocation(), diag::note_declared_at);
1194 return CR_Error;
1195 }
1196
1197 S.MarkDeclarationReferenced(loc, var);
1198
1199 // The BlocksAttr indicates the variable is bound by-reference.
1200 bool byRef = var->hasAttr<BlocksAttr>();
1201
1202 // Build a copy expression.
1203 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001204 const RecordType *rtype;
1205 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1206 (rtype = type->getAs<RecordType>())) {
1207
1208 // The capture logic needs the destructor, so make sure we mark it.
1209 // Usually this is unnecessary because most local variables have
1210 // their destructors marked at declaration time, but parameters are
1211 // an exception because it's technically only the call site that
1212 // actually requires the destructor.
1213 if (isa<ParmVarDecl>(var))
1214 S.FinalizeVarWithDestructor(var, rtype);
1215
John McCall351762c2011-02-07 10:33:21 +00001216 // According to the blocks spec, the capture of a variable from
1217 // the stack requires a const copy constructor. This is not true
1218 // of the copy/move done to move a __block variable to the heap.
1219 type.addConst();
1220
1221 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1222 ExprResult result =
1223 S.PerformCopyInitialization(
1224 InitializedEntity::InitializeBlock(var->getLocation(),
1225 type, false),
1226 loc, S.Owned(declRef));
1227
1228 // Build a full-expression copy expression if initialization
1229 // succeeded and used a non-trivial constructor. Recover from
1230 // errors by pretending that the copy isn't necessary.
1231 if (!result.isInvalid() &&
1232 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1233 result = S.MaybeCreateExprWithCleanups(result);
1234 copyExpr = result.take();
1235 }
1236 }
1237
1238 // We're currently at the declarer; go back to the closure.
1239 functionScopesIndex++;
1240 BlockScopeInfo *blockScope =
1241 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1242
1243 // Build a valid capture in this scope.
1244 blockScope->Captures.push_back(
1245 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1246 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1247
1248 // Propagate that to inner captures if necessary.
1249 return propagateCapture(S, functionScopesIndex,
1250 blockScope->Captures.back());
1251}
1252
1253static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1254 const DeclarationNameInfo &NameInfo,
1255 bool byRef) {
1256 assert(isa<VarDecl>(vd) && "capturing non-variable");
1257
1258 VarDecl *var = cast<VarDecl>(vd);
1259 assert(var->hasLocalStorage() && "capturing non-local");
1260 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1261
1262 QualType exprType = var->getType().getNonReferenceType();
1263
1264 BlockDeclRefExpr *BDRE;
1265 if (!byRef) {
1266 // The variable will be bound by copy; make it const within the
1267 // closure, but record that this was done in the expression.
1268 bool constAdded = !exprType.isConstQualified();
1269 exprType.addConst();
1270
1271 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1272 NameInfo.getLoc(), false,
1273 constAdded);
1274 } else {
1275 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1276 NameInfo.getLoc(), true);
1277 }
1278
1279 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001280}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001281
John McCalldadc5752010-08-24 06:29:42 +00001282ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001283Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001284 SourceLocation Loc,
1285 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001286 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001287 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001288}
1289
John McCallf4cd4f92011-02-09 01:13:10 +00001290/// BuildDeclRefExpr - Build an expression that references a
1291/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001292ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001293Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001294 const DeclarationNameInfo &NameInfo,
1295 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001296 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCall086a4642010-11-24 05:12:34 +00001298 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001299 SS? SS->getWithLocInContext(Context)
1300 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001301 D, NameInfo, Ty, VK);
1302
1303 // Just in case we're building an illegal pointer-to-member.
1304 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1305 E->setObjectKind(OK_BitField);
1306
1307 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001308}
1309
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001310/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001311/// possibly a list of template arguments.
1312///
1313/// If this produces template arguments, it is permitted to call
1314/// DecomposeTemplateName.
1315///
1316/// This actually loses a lot of source location information for
1317/// non-standard name kinds; we should consider preserving that in
1318/// some way.
Douglas Gregor5476205b2011-06-23 00:49:38 +00001319void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1320 TemplateArgumentListInfo &Buffer,
1321 DeclarationNameInfo &NameInfo,
1322 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001323 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1324 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1325 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1326
Douglas Gregor5476205b2011-06-23 00:49:38 +00001327 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001328 Id.TemplateId->getTemplateArgs(),
1329 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001330 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001331 TemplateArgsPtr.release();
1332
John McCall3e56fd42010-08-23 07:28:44 +00001333 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001334 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001335 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001336 TemplateArgs = &Buffer;
1337 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001338 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001339 TemplateArgs = 0;
1340 }
1341}
1342
John McCalld681c392009-12-16 08:11:27 +00001343/// Diagnose an empty lookup.
1344///
1345/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001346bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1347 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001348 DeclarationName Name = R.getLookupName();
1349
John McCalld681c392009-12-16 08:11:27 +00001350 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001351 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001352 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1353 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001354 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001355 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001356 diagnostic_suggest = diag::err_undeclared_use_suggest;
1357 }
John McCalld681c392009-12-16 08:11:27 +00001358
Douglas Gregor598b08f2009-12-31 05:20:13 +00001359 // If the original lookup was an unqualified lookup, fake an
1360 // unqualified lookup. This is useful when (for example) the
1361 // original lookup would not have found something because it was a
1362 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001363 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001364 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001365 if (isa<CXXRecordDecl>(DC)) {
1366 LookupQualifiedName(R, DC);
1367
1368 if (!R.empty()) {
1369 // Don't give errors about ambiguities in this lookup.
1370 R.suppressDiagnostics();
1371
1372 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1373 bool isInstance = CurMethod &&
1374 CurMethod->isInstance() &&
1375 DC == CurMethod->getParent();
1376
1377 // Give a code modification hint to insert 'this->'.
1378 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1379 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001380 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001381 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1382 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001383 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001384 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001385 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001386 Diag(R.getNameLoc(), diagnostic) << Name
1387 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1388 QualType DepThisType = DepMethod->getThisType(Context);
1389 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1390 R.getNameLoc(), DepThisType, false);
1391 TemplateArgumentListInfo TList;
1392 if (ULE->hasExplicitTemplateArgs())
1393 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001394
Douglas Gregore16af532011-02-28 18:50:33 +00001395 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001396 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001397 CXXDependentScopeMemberExpr *DepExpr =
1398 CXXDependentScopeMemberExpr::Create(
1399 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001400 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001401 R.getLookupNameInfo(), &TList);
1402 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001403 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001404 // FIXME: we should be able to handle this case too. It is correct
1405 // to add this-> here. This is a workaround for PR7947.
1406 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001407 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001408 } else {
John McCalld681c392009-12-16 08:11:27 +00001409 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001410 }
John McCalld681c392009-12-16 08:11:27 +00001411
1412 // Do we really want to note all of these?
1413 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1414 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1415
1416 // Tell the callee to try to recover.
1417 return false;
1418 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001419
1420 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001421 }
1422 }
1423
Douglas Gregor598b08f2009-12-31 05:20:13 +00001424 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001425 TypoCorrection Corrected;
1426 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1427 S, &SS, NULL, false, CTC))) {
1428 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1429 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1430 R.setLookupName(Corrected.getCorrection());
1431
Hans Wennborg38198de2011-07-12 08:45:31 +00001432 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001433 R.addDecl(ND);
1434 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001435 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001436 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1437 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001438 else
1439 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001440 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001441 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001442 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1443 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001444 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001445 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001446
1447 // Tell the callee to try to recover.
1448 return false;
1449 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001450
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001451 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001452 // FIXME: If we ended up with a typo for a type name or
1453 // Objective-C class name, we're in trouble because the parser
1454 // is in the wrong place to recover. Suggest the typo
1455 // correction, but don't make it a fix-it since we're not going
1456 // to recover well anyway.
1457 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001458 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001459 else
1460 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001461 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001462 << SS.getRange();
1463
1464 // Don't try to recover; it won't work.
1465 return true;
1466 }
1467 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001468 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001469 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001470 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001471 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001472 else
Douglas Gregor25363982010-01-01 00:15:04 +00001473 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001474 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001475 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001476 return true;
1477 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001478 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001479 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001480
1481 // Emit a special diagnostic for failed member lookups.
1482 // FIXME: computing the declaration context might fail here (?)
1483 if (!SS.isEmpty()) {
1484 Diag(R.getNameLoc(), diag::err_no_member)
1485 << Name << computeDeclContext(SS, false)
1486 << SS.getRange();
1487 return true;
1488 }
1489
John McCalld681c392009-12-16 08:11:27 +00001490 // Give up, we can't recover.
1491 Diag(R.getNameLoc(), diagnostic) << Name;
1492 return true;
1493}
1494
Douglas Gregor05fcf842010-11-02 20:36:02 +00001495ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1496 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001497 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1498 if (!IDecl)
1499 return 0;
1500 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1501 if (!ClassImpDecl)
1502 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001503 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001504 if (!property)
1505 return 0;
1506 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001507 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1508 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001509 return 0;
1510 return property;
1511}
1512
Douglas Gregor05fcf842010-11-02 20:36:02 +00001513bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1514 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1515 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1516 if (!IDecl)
1517 return false;
1518 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1519 if (!ClassImpDecl)
1520 return false;
1521 if (ObjCPropertyImplDecl *PIDecl
1522 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1523 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1524 PIDecl->getPropertyIvarDecl())
1525 return false;
1526
1527 return true;
1528}
1529
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001530ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1531 IdentifierInfo *II,
1532 SourceLocation NameLoc) {
1533 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001534 bool LookForIvars;
1535 if (Lookup.empty())
1536 LookForIvars = true;
1537 else if (CurMeth->isClassMethod())
1538 LookForIvars = false;
1539 else
1540 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001541 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1542 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001543 if (!LookForIvars)
1544 return 0;
1545
Fariborz Jahanian18722982010-07-17 00:59:30 +00001546 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1547 if (!IDecl)
1548 return 0;
1549 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001550 if (!ClassImpDecl)
1551 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001552 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001553 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001554 if (!property)
1555 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001556 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001557 DynamicImplSeen =
1558 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001559 // property implementation has a designated ivar. No need to assume a new
1560 // one.
1561 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1562 return 0;
1563 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001564 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001565 QualType PropType = Context.getCanonicalType(property->getType());
1566 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001567 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001568 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001569 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001570 (Expr *)0, true);
1571 ClassImpDecl->addDecl(Ivar);
1572 IDecl->makeDeclVisibleInContext(Ivar, false);
1573 property->setPropertyIvarDecl(Ivar);
1574 return Ivar;
1575 }
1576 return 0;
1577}
1578
John McCalldadc5752010-08-24 06:29:42 +00001579ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001580 CXXScopeSpec &SS,
1581 UnqualifiedId &Id,
1582 bool HasTrailingLParen,
1583 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001584 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1585 "cannot be direct & operand and have a trailing lparen");
1586
1587 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001588 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001589
John McCall10eae182009-11-30 22:42:35 +00001590 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001591
1592 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001593 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001594 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001595 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001596
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001597 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001598 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001599 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001600
John McCalle66edc12009-11-24 19:00:30 +00001601 // C++ [temp.dep.expr]p3:
1602 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001603 // -- an identifier that was declared with a dependent type,
1604 // (note: handled after lookup)
1605 // -- a template-id that is dependent,
1606 // (note: handled in BuildTemplateIdExpr)
1607 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001608 // -- a nested-name-specifier that contains a class-name that
1609 // names a dependent type.
1610 // Determine whether this is a member of an unknown specialization;
1611 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001612 bool DependentID = false;
1613 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1614 Name.getCXXNameType()->isDependentType()) {
1615 DependentID = true;
1616 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001617 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001618 if (RequireCompleteDeclContext(SS, DC))
1619 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001620 } else {
1621 DependentID = true;
1622 }
1623 }
1624
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001625 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001627 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001628
Fariborz Jahanian86151342010-07-22 23:33:21 +00001629 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001630 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001631 LookupResult R(*this, NameInfo,
1632 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1633 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001634 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001635 // Lookup the template name again to correctly establish the context in
1636 // which it was found. This is really unfortunate as we already did the
1637 // lookup to determine that it was a template name in the first place. If
1638 // this becomes a performance hit, we can work harder to preserve those
1639 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001640 bool MemberOfUnknownSpecialization;
1641 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1642 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001643
1644 if (MemberOfUnknownSpecialization ||
1645 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1646 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1647 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001648 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001649 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001650 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001651
Douglas Gregora5226932011-02-04 13:35:07 +00001652 // If the result might be in a dependent base class, this is a dependent
1653 // id-expression.
1654 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1655 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1656 TemplateArgs);
1657
John McCalle66edc12009-11-24 19:00:30 +00001658 // If this reference is in an Objective-C method, then we need to do
1659 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001660 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001661 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001662 if (E.isInvalid())
1663 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001664
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001665 if (Expr *Ex = E.takeAs<Expr>())
1666 return Owned(Ex);
1667
1668 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001669 if (getLangOptions().ObjCDefaultSynthProperties &&
1670 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001671 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001672 if (const ObjCPropertyDecl *Property =
1673 canSynthesizeProvisionalIvar(II)) {
1674 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1675 Diag(Property->getLocation(), diag::note_property_declare);
1676 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001677 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1678 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001679 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001680 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001681 // for further use, this must be set to false if in class method.
1682 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001683 }
Chris Lattner59a25942008-03-31 00:36:02 +00001684 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001685
John McCalle66edc12009-11-24 19:00:30 +00001686 if (R.isAmbiguous())
1687 return ExprError();
1688
Douglas Gregor171c45a2009-02-18 21:56:37 +00001689 // Determine whether this name might be a candidate for
1690 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001691 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001692
John McCalle66edc12009-11-24 19:00:30 +00001693 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001694 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001695 // in C90, extension in C99, forbidden in C++).
1696 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1697 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1698 if (D) R.addDecl(D);
1699 }
1700
1701 // If this name wasn't predeclared and if this is not a function
1702 // call, diagnose the problem.
1703 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001704 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001705 return ExprError();
1706
1707 assert(!R.empty() &&
1708 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001709
1710 // If we found an Objective-C instance variable, let
1711 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001712 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001713 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1714 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001715 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001716 assert(E.isInvalid() || E.get());
1717 return move(E);
1718 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001719 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721
John McCalle66edc12009-11-24 19:00:30 +00001722 // This is guaranteed from this point on.
1723 assert(!R.empty() || ADL);
1724
John McCall2d74de92009-12-01 22:10:20 +00001725 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001726 // C++ [class.mfct.non-static]p3:
1727 // When an id-expression that is not part of a class member access
1728 // syntax and not used to form a pointer to member is used in the
1729 // body of a non-static member function of class X, if name lookup
1730 // resolves the name in the id-expression to a non-static non-type
1731 // member of some class C, the id-expression is transformed into a
1732 // class member access expression using (*this) as the
1733 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001734 //
1735 // But we don't actually need to do this for '&' operands if R
1736 // resolved to a function or overloaded function set, because the
1737 // expression is ill-formed if it actually works out to be a
1738 // non-static member function:
1739 //
1740 // C++ [expr.ref]p4:
1741 // Otherwise, if E1.E2 refers to a non-static member function. . .
1742 // [t]he expression can be used only as the left-hand operand of a
1743 // member function call.
1744 //
1745 // There are other safeguards against such uses, but it's important
1746 // to get this right here so that we don't end up making a
1747 // spuriously dependent expression if we're inside a dependent
1748 // instance method.
John McCall57500772009-12-16 12:17:52 +00001749 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001750 bool MightBeImplicitMember;
1751 if (!isAddressOfOperand)
1752 MightBeImplicitMember = true;
1753 else if (!SS.isEmpty())
1754 MightBeImplicitMember = false;
1755 else if (R.isOverloadedResult())
1756 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001757 else if (R.isUnresolvableResult())
1758 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001759 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001760 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1761 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001762
1763 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001764 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001765 }
1766
John McCalle66edc12009-11-24 19:00:30 +00001767 if (TemplateArgs)
1768 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001769
John McCalle66edc12009-11-24 19:00:30 +00001770 return BuildDeclarationNameExpr(SS, R, ADL);
1771}
1772
John McCall10eae182009-11-30 22:42:35 +00001773/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1774/// declaration name, generally during template instantiation.
1775/// There's a large number of things which don't need to be done along
1776/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001777ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001778Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001779 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001780 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001781 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001782 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001783
John McCall0b66eb32010-05-01 00:40:08 +00001784 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001785 return ExprError();
1786
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001787 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001788 LookupQualifiedName(R, DC);
1789
1790 if (R.isAmbiguous())
1791 return ExprError();
1792
1793 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001794 Diag(NameInfo.getLoc(), diag::err_no_member)
1795 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001796 return ExprError();
1797 }
1798
1799 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1800}
1801
1802/// LookupInObjCMethod - The parser has read a name in, and Sema has
1803/// detected that we're currently inside an ObjC method. Perform some
1804/// additional lookup.
1805///
1806/// Ideally, most of this would be done by lookup, but there's
1807/// actually quite a lot of extra work involved.
1808///
1809/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001810ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001811Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001812 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001813 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001814 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001815
John McCalle66edc12009-11-24 19:00:30 +00001816 // There are two cases to handle here. 1) scoped lookup could have failed,
1817 // in which case we should look for an ivar. 2) scoped lookup could have
1818 // found a decl, but that decl is outside the current instance method (i.e.
1819 // a global variable). In these two cases, we do a lookup for an ivar with
1820 // this name, if the lookup sucedes, we replace it our current decl.
1821
1822 // If we're in a class method, we don't normally want to look for
1823 // ivars. But if we don't find anything else, and there's an
1824 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001825 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001826
1827 bool LookForIvars;
1828 if (Lookup.empty())
1829 LookForIvars = true;
1830 else if (IsClassMethod)
1831 LookForIvars = false;
1832 else
1833 LookForIvars = (Lookup.isSingleResult() &&
1834 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001835 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001836 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001837 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001838 ObjCInterfaceDecl *ClassDeclared;
1839 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1840 // Diagnose using an ivar in a class method.
1841 if (IsClassMethod)
1842 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1843 << IV->getDeclName());
1844
1845 // If we're referencing an invalid decl, just return this as a silent
1846 // error node. The error diagnostic was already emitted on the decl.
1847 if (IV->isInvalidDecl())
1848 return ExprError();
1849
1850 // Check if referencing a field with __attribute__((deprecated)).
1851 if (DiagnoseUseOfDecl(IV, Loc))
1852 return ExprError();
1853
1854 // Diagnose the use of an ivar outside of the declaring class.
1855 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1856 ClassDeclared != IFace)
1857 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1858
1859 // FIXME: This should use a new expr for a direct reference, don't
1860 // turn this into Self->ivar, just return a BareIVarExpr or something.
1861 IdentifierInfo &II = Context.Idents.get("self");
1862 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001863 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001864 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001865 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001866 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001867 SelfName, false, false);
1868 if (SelfExpr.isInvalid())
1869 return ExprError();
1870
John Wiegley01296292011-04-08 18:41:53 +00001871 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1872 if (SelfExpr.isInvalid())
1873 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001874
John McCalle66edc12009-11-24 19:00:30 +00001875 MarkDeclarationReferenced(Loc, IV);
1876 return Owned(new (Context)
1877 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001878 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001879 }
Chris Lattner87313662010-04-12 05:10:17 +00001880 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001881 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001882 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001883 ObjCInterfaceDecl *ClassDeclared;
1884 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1885 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1886 IFace == ClassDeclared)
1887 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1888 }
1889 }
1890
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001891 if (Lookup.empty() && II && AllowBuiltinCreation) {
1892 // FIXME. Consolidate this with similar code in LookupName.
1893 if (unsigned BuiltinID = II->getBuiltinID()) {
1894 if (!(getLangOptions().CPlusPlus &&
1895 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1896 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1897 S, Lookup.isForRedeclaration(),
1898 Lookup.getNameLoc());
1899 if (D) Lookup.addDecl(D);
1900 }
1901 }
1902 }
John McCalle66edc12009-11-24 19:00:30 +00001903 // Sentinel value saying that we didn't do anything special.
1904 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001905}
John McCalld14a8642009-11-21 08:51:07 +00001906
John McCall16df1e52010-03-30 21:47:33 +00001907/// \brief Cast a base object to a member's actual type.
1908///
1909/// Logically this happens in three phases:
1910///
1911/// * First we cast from the base type to the naming class.
1912/// The naming class is the class into which we were looking
1913/// when we found the member; it's the qualifier type if a
1914/// qualifier was provided, and otherwise it's the base type.
1915///
1916/// * Next we cast from the naming class to the declaring class.
1917/// If the member we found was brought into a class's scope by
1918/// a using declaration, this is that class; otherwise it's
1919/// the class declaring the member.
1920///
1921/// * Finally we cast from the declaring class to the "true"
1922/// declaring class of the member. This conversion does not
1923/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001924ExprResult
1925Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001926 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001927 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001928 NamedDecl *Member) {
1929 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1930 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001931 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001932
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001933 QualType DestRecordType;
1934 QualType DestType;
1935 QualType FromRecordType;
1936 QualType FromType = From->getType();
1937 bool PointerConversions = false;
1938 if (isa<FieldDecl>(Member)) {
1939 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001940
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 if (FromType->getAs<PointerType>()) {
1942 DestType = Context.getPointerType(DestRecordType);
1943 FromRecordType = FromType->getPointeeType();
1944 PointerConversions = true;
1945 } else {
1946 DestType = DestRecordType;
1947 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001948 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001949 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1950 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001951 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001952
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001953 DestType = Method->getThisType(Context);
1954 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 if (FromType->getAs<PointerType>()) {
1957 FromRecordType = FromType->getPointeeType();
1958 PointerConversions = true;
1959 } else {
1960 FromRecordType = FromType;
1961 DestType = DestRecordType;
1962 }
1963 } else {
1964 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001965 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001969 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001970
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001971 // If the unqualified types are the same, no conversion is necessary.
1972 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001973 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
John McCall16df1e52010-03-30 21:47:33 +00001975 SourceRange FromRange = From->getSourceRange();
1976 SourceLocation FromLoc = FromRange.getBegin();
1977
John McCall2536c6d2010-08-25 10:28:54 +00001978 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001979
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001980 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001981 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001982 // class name.
1983 //
1984 // If the member was a qualified name and the qualified referred to a
1985 // specific base subobject type, we'll cast to that intermediate type
1986 // first and then to the object in which the member is declared. That allows
1987 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1988 //
1989 // class Base { public: int x; };
1990 // class Derived1 : public Base { };
1991 // class Derived2 : public Base { };
1992 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1993 //
1994 // void VeryDerived::f() {
1995 // x = 17; // error: ambiguous base subobjects
1996 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1997 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001999 QualType QType = QualType(Qualifier->getAsType(), 0);
2000 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2001 assert(QType->isRecordType() && "lookup done with non-record type");
2002
2003 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2004
2005 // In C++98, the qualifier type doesn't actually have to be a base
2006 // type of the object type, in which case we just ignore it.
2007 // Otherwise build the appropriate casts.
2008 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002009 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002010 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002011 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002012 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002013
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002015 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002016 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2017 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002018
2019 FromType = QType;
2020 FromRecordType = QRecordType;
2021
2022 // If the qualifier type was the same as the destination type,
2023 // we're done.
2024 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002025 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002026 }
2027 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002028
John McCall16df1e52010-03-30 21:47:33 +00002029 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002030
John McCall16df1e52010-03-30 21:47:33 +00002031 // If we actually found the member through a using declaration, cast
2032 // down to the using declaration's type.
2033 //
2034 // Pointer equality is fine here because only one declaration of a
2035 // class ever has member declarations.
2036 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2037 assert(isa<UsingShadowDecl>(FoundDecl));
2038 QualType URecordType = Context.getTypeDeclType(
2039 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2040
2041 // We only need to do this if the naming-class to declaring-class
2042 // conversion is non-trivial.
2043 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2044 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002045 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002046 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002047 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002048 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002049
John McCall16df1e52010-03-30 21:47:33 +00002050 QualType UType = URecordType;
2051 if (PointerConversions)
2052 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002053 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2054 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002055 FromType = UType;
2056 FromRecordType = URecordType;
2057 }
2058
2059 // We don't do access control for the conversion from the
2060 // declaring class to the true declaring class.
2061 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002062 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002063
John McCallcf142162010-08-07 06:22:56 +00002064 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002065 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2066 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002067 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002068 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002069
John Wiegley01296292011-04-08 18:41:53 +00002070 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2071 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002072}
Douglas Gregor3256d042009-06-30 15:47:41 +00002073
John McCalle66edc12009-11-24 19:00:30 +00002074bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002075 const LookupResult &R,
2076 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002077 // Only when used directly as the postfix-expression of a call.
2078 if (!HasTrailingLParen)
2079 return false;
2080
2081 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002082 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002083 return false;
2084
2085 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002086 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002087 return false;
2088
2089 // Turn off ADL when we find certain kinds of declarations during
2090 // normal lookup:
2091 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2092 NamedDecl *D = *I;
2093
2094 // C++0x [basic.lookup.argdep]p3:
2095 // -- a declaration of a class member
2096 // Since using decls preserve this property, we check this on the
2097 // original decl.
John McCall57500772009-12-16 12:17:52 +00002098 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002099 return false;
2100
2101 // C++0x [basic.lookup.argdep]p3:
2102 // -- a block-scope function declaration that is not a
2103 // using-declaration
2104 // NOTE: we also trigger this for function templates (in fact, we
2105 // don't check the decl type at all, since all other decl types
2106 // turn off ADL anyway).
2107 if (isa<UsingShadowDecl>(D))
2108 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2109 else if (D->getDeclContext()->isFunctionOrMethod())
2110 return false;
2111
2112 // C++0x [basic.lookup.argdep]p3:
2113 // -- a declaration that is neither a function or a function
2114 // template
2115 // And also for builtin functions.
2116 if (isa<FunctionDecl>(D)) {
2117 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2118
2119 // But also builtin functions.
2120 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2121 return false;
2122 } else if (!isa<FunctionTemplateDecl>(D))
2123 return false;
2124 }
2125
2126 return true;
2127}
2128
2129
John McCalld14a8642009-11-21 08:51:07 +00002130/// Diagnoses obvious problems with the use of the given declaration
2131/// as an expression. This is only actually called for lookups that
2132/// were not overloaded, and it doesn't promise that the declaration
2133/// will in fact be used.
2134static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002135 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002136 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2137 return true;
2138 }
2139
2140 if (isa<ObjCInterfaceDecl>(D)) {
2141 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2142 return true;
2143 }
2144
2145 if (isa<NamespaceDecl>(D)) {
2146 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2147 return true;
2148 }
2149
2150 return false;
2151}
2152
John McCalldadc5752010-08-24 06:29:42 +00002153ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002154Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002155 LookupResult &R,
2156 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002157 // If this is a single, fully-resolved result and we don't need ADL,
2158 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002159 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002160 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2161 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002162
2163 // We only need to check the declaration if there's exactly one
2164 // result, because in the overloaded case the results can only be
2165 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002166 if (R.isSingleResult() &&
2167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002168 return ExprError();
2169
John McCall58cc69d2010-01-27 01:50:18 +00002170 // Otherwise, just build an unresolved lookup expression. Suppress
2171 // any lookup-related diagnostics; we'll hash these out later, when
2172 // we've picked a target.
2173 R.suppressDiagnostics();
2174
John McCalld14a8642009-11-21 08:51:07 +00002175 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002177 SS.getWithLocInContext(Context),
2178 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002179 NeedsADL, R.isOverloadedResult(),
2180 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002181
2182 return Owned(ULE);
2183}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002184
John McCalld14a8642009-11-21 08:51:07 +00002185/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002188 const DeclarationNameInfo &NameInfo,
2189 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002190 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002191 assert(!isa<FunctionTemplateDecl>(D) &&
2192 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002193
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002194 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002195 if (CheckDeclInExpr(*this, Loc, D))
2196 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002197
Douglas Gregore7488b92009-12-01 16:58:18 +00002198 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2199 // Specifically diagnose references to class templates that are missing
2200 // a template argument list.
2201 Diag(Loc, diag::err_template_decl_ref)
2202 << Template << SS.getRange();
2203 Diag(Template->getLocation(), diag::note_template_decl_here);
2204 return ExprError();
2205 }
2206
2207 // Make sure that we're referring to a value.
2208 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2209 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002210 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002211 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002212 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002213 return ExprError();
2214 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002215
Douglas Gregor171c45a2009-02-18 21:56:37 +00002216 // Check whether this declaration can be used. Note that we suppress
2217 // this check when we're going to perform argument-dependent lookup
2218 // on this function name, because this might not be the function
2219 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002220 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002221 return ExprError();
2222
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002223 // Only create DeclRefExpr's for valid Decl's.
2224 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002225 return ExprError();
2226
John McCallf3a88602011-02-03 08:15:49 +00002227 // Handle members of anonymous structs and unions. If we got here,
2228 // and the reference is to a class member indirect field, then this
2229 // must be the subject of a pointer-to-member expression.
2230 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2231 if (!indirectField->isCXXClassMember())
2232 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2233 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002234
Chris Lattner2a9d9892008-10-20 05:16:36 +00002235 // If the identifier reference is inside a block, and it refers to a value
2236 // that is outside the block, create a BlockDeclRefExpr instead of a
2237 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2238 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002239 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002240 // We do not do this for things like enum constants, global variables, etc,
2241 // as they do not get snapshotted.
2242 //
John McCall351762c2011-02-07 10:33:21 +00002243 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002244 case CR_Error:
2245 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002246
John McCallc63de662011-02-02 13:00:07 +00002247 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002248 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2249 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2250
2251 case CR_CaptureByRef:
2252 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2253 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002254
2255 case CR_NoCapture: {
2256 // If this reference is not in a block or if the referenced
2257 // variable is within the block, create a normal DeclRefExpr.
2258
2259 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002260 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002261
2262 switch (D->getKind()) {
2263 // Ignore all the non-ValueDecl kinds.
2264#define ABSTRACT_DECL(kind)
2265#define VALUE(type, base)
2266#define DECL(type, base) \
2267 case Decl::type:
2268#include "clang/AST/DeclNodes.inc"
2269 llvm_unreachable("invalid value decl kind");
2270 return ExprError();
2271
2272 // These shouldn't make it here.
2273 case Decl::ObjCAtDefsField:
2274 case Decl::ObjCIvar:
2275 llvm_unreachable("forming non-member reference to ivar?");
2276 return ExprError();
2277
2278 // Enum constants are always r-values and never references.
2279 // Unresolved using declarations are dependent.
2280 case Decl::EnumConstant:
2281 case Decl::UnresolvedUsingValue:
2282 valueKind = VK_RValue;
2283 break;
2284
2285 // Fields and indirect fields that got here must be for
2286 // pointer-to-member expressions; we just call them l-values for
2287 // internal consistency, because this subexpression doesn't really
2288 // exist in the high-level semantics.
2289 case Decl::Field:
2290 case Decl::IndirectField:
2291 assert(getLangOptions().CPlusPlus &&
2292 "building reference to field in C?");
2293
2294 // These can't have reference type in well-formed programs, but
2295 // for internal consistency we do this anyway.
2296 type = type.getNonReferenceType();
2297 valueKind = VK_LValue;
2298 break;
2299
2300 // Non-type template parameters are either l-values or r-values
2301 // depending on the type.
2302 case Decl::NonTypeTemplateParm: {
2303 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2304 type = reftype->getPointeeType();
2305 valueKind = VK_LValue; // even if the parameter is an r-value reference
2306 break;
2307 }
2308
2309 // For non-references, we need to strip qualifiers just in case
2310 // the template parameter was declared as 'const int' or whatever.
2311 valueKind = VK_RValue;
2312 type = type.getUnqualifiedType();
2313 break;
2314 }
2315
2316 case Decl::Var:
2317 // In C, "extern void blah;" is valid and is an r-value.
2318 if (!getLangOptions().CPlusPlus &&
2319 !type.hasQualifiers() &&
2320 type->isVoidType()) {
2321 valueKind = VK_RValue;
2322 break;
2323 }
2324 // fallthrough
2325
2326 case Decl::ImplicitParam:
2327 case Decl::ParmVar:
2328 // These are always l-values.
2329 valueKind = VK_LValue;
2330 type = type.getNonReferenceType();
2331 break;
2332
2333 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002334 const FunctionType *fty = type->castAs<FunctionType>();
2335
2336 // If we're referring to a function with an __unknown_anytype
2337 // result type, make the entire expression __unknown_anytype.
2338 if (fty->getResultType() == Context.UnknownAnyTy) {
2339 type = Context.UnknownAnyTy;
2340 valueKind = VK_RValue;
2341 break;
2342 }
2343
John McCallf4cd4f92011-02-09 01:13:10 +00002344 // Functions are l-values in C++.
2345 if (getLangOptions().CPlusPlus) {
2346 valueKind = VK_LValue;
2347 break;
2348 }
2349
2350 // C99 DR 316 says that, if a function type comes from a
2351 // function definition (without a prototype), that type is only
2352 // used for checking compatibility. Therefore, when referencing
2353 // the function, we pretend that we don't have the full function
2354 // type.
John McCall2979fe02011-04-12 00:42:48 +00002355 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2356 isa<FunctionProtoType>(fty))
2357 type = Context.getFunctionNoProtoType(fty->getResultType(),
2358 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002359
2360 // Functions are r-values in C.
2361 valueKind = VK_RValue;
2362 break;
2363 }
2364
2365 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002366 // If we're referring to a method with an __unknown_anytype
2367 // result type, make the entire expression __unknown_anytype.
2368 // This should only be possible with a type written directly.
2369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2370 if (proto->getResultType() == Context.UnknownAnyTy) {
2371 type = Context.UnknownAnyTy;
2372 valueKind = VK_RValue;
2373 break;
2374 }
2375
John McCallf4cd4f92011-02-09 01:13:10 +00002376 // C++ methods are l-values if static, r-values if non-static.
2377 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2378 valueKind = VK_LValue;
2379 break;
2380 }
2381 // fallthrough
2382
2383 case Decl::CXXConversion:
2384 case Decl::CXXDestructor:
2385 case Decl::CXXConstructor:
2386 valueKind = VK_RValue;
2387 break;
2388 }
2389
2390 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2391 }
2392
John McCallc63de662011-02-02 13:00:07 +00002393 }
John McCall7decc9e2010-11-18 06:31:45 +00002394
John McCall351762c2011-02-07 10:33:21 +00002395 llvm_unreachable("unknown capture result");
2396 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002397}
Chris Lattnere168f762006-11-10 05:29:30 +00002398
John McCall2979fe02011-04-12 00:42:48 +00002399ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002400 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002401
Chris Lattnere168f762006-11-10 05:29:30 +00002402 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002403 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002404 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2405 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2406 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002407 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002408
Chris Lattnera81a0272008-01-12 08:14:25 +00002409 // Pre-defined identifiers are of type char[x], where x is the length of the
2410 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002411
Anders Carlsson2fb08242009-09-08 18:24:21 +00002412 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002413 if (!currentDecl && getCurBlock())
2414 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002415 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002416 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002417 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002418 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002419
Anders Carlsson0b209a82009-09-11 01:22:35 +00002420 QualType ResTy;
2421 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2422 ResTy = Context.DependentTy;
2423 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002424 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002425
Anders Carlsson0b209a82009-09-11 01:22:35 +00002426 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002427 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002428 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2429 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002430 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002431}
2432
John McCalldadc5752010-08-24 06:29:42 +00002433ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002434 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002435 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002436 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002437 if (Invalid)
2438 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002439
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002440 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002441 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002442 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002443 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002444
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002445 QualType Ty;
2446 if (!getLangOptions().CPlusPlus)
2447 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2448 else if (Literal.isWide())
2449 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002450 else if (Literal.isUTF16())
2451 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2452 else if (Literal.isUTF32())
2453 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002454 else if (Literal.isMultiChar())
2455 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002456 else
2457 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002458
Douglas Gregorfb65e592011-07-27 05:40:30 +00002459 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2460 if (Literal.isWide())
2461 Kind = CharacterLiteral::Wide;
2462 else if (Literal.isUTF16())
2463 Kind = CharacterLiteral::UTF16;
2464 else if (Literal.isUTF32())
2465 Kind = CharacterLiteral::UTF32;
2466
2467 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2468 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002469}
2470
John McCalldadc5752010-08-24 06:29:42 +00002471ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002472 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002473 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2474 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002475 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002476 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002477 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002478 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002479 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002480
Chris Lattner23b7eb62007-06-15 23:05:46 +00002481 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002482 // Add padding so that NumericLiteralParser can overread by one character.
2483 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002484 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002485
Chris Lattner67ca9252007-05-21 01:08:44 +00002486 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002487 bool Invalid = false;
2488 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2489 if (Invalid)
2490 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002491
Mike Stump11289f42009-09-09 15:08:12 +00002492 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002493 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002494 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002495 return ExprError();
2496
Chris Lattner1c20a172007-08-26 03:42:43 +00002497 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002498
Chris Lattner1c20a172007-08-26 03:42:43 +00002499 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002500 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002501 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002502 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002503 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002504 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002505 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002506 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002507
2508 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2509
John McCall53b93a02009-12-24 09:08:04 +00002510 using llvm::APFloat;
2511 APFloat Val(Format);
2512
2513 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002514
2515 // Overflow is always an error, but underflow is only an error if
2516 // we underflowed to zero (APFloat reports denormals as underflow).
2517 if ((result & APFloat::opOverflow) ||
2518 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002519 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002520 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002521 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002522 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002523 APFloat::getLargest(Format).toString(buffer);
2524 } else {
John McCall62abc942010-02-26 23:35:57 +00002525 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002526 APFloat::getSmallest(Format).toString(buffer);
2527 }
2528
2529 Diag(Tok.getLocation(), diagnostic)
2530 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002531 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002532 }
2533
2534 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002535 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002537 if (Ty == Context.DoubleTy) {
2538 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002539 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002540 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2541 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002542 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002543 }
2544 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002545 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002546 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002547 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002548 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002549
Neil Boothac582c52007-08-29 22:00:19 +00002550 // long long is a C99 feature.
2551 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002552 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002553 Diag(Tok.getLocation(), diag::ext_longlong);
2554
Chris Lattner67ca9252007-05-21 01:08:44 +00002555 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002556 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002557
Chris Lattner67ca9252007-05-21 01:08:44 +00002558 if (Literal.GetIntegerValue(ResultVal)) {
2559 // If this value didn't fit into uintmax_t, warn and force to ull.
2560 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002561 Ty = Context.UnsignedLongLongTy;
2562 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002563 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002564 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002565 // If this value fits into a ULL, try to figure out what else it fits into
2566 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002567
Chris Lattner67ca9252007-05-21 01:08:44 +00002568 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2569 // be an unsigned int.
2570 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2571
2572 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002573 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002574 if (!Literal.isLong && !Literal.isLongLong) {
2575 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002576 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Chris Lattner67ca9252007-05-21 01:08:44 +00002578 // Does it fit in a unsigned int?
2579 if (ResultVal.isIntN(IntSize)) {
2580 // Does it fit in a signed int?
2581 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002582 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002583 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002584 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002585 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002586 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002587 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002588
Chris Lattner67ca9252007-05-21 01:08:44 +00002589 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002590 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002591 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002592
Chris Lattner67ca9252007-05-21 01:08:44 +00002593 // Does it fit in a unsigned long?
2594 if (ResultVal.isIntN(LongSize)) {
2595 // Does it fit in a signed long?
2596 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002597 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002598 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002599 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002600 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002601 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002602 }
2603
Chris Lattner67ca9252007-05-21 01:08:44 +00002604 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002605 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002606 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002607
Chris Lattner67ca9252007-05-21 01:08:44 +00002608 // Does it fit in a unsigned long long?
2609 if (ResultVal.isIntN(LongLongSize)) {
2610 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002611 // To be compatible with MSVC, hex integer literals ending with the
2612 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002613 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2614 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002615 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002616 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002617 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002618 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002619 }
2620 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002621
Chris Lattner67ca9252007-05-21 01:08:44 +00002622 // If we still couldn't decide a type, we probably have something that
2623 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002625 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002626 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002627 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002628 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002629
Chris Lattner55258cf2008-05-09 05:59:00 +00002630 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002631 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002632 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002633 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002634 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002635
Chris Lattner1c20a172007-08-26 03:42:43 +00002636 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2637 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002638 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002639 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640
2641 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002642}
2643
John McCalldadc5752010-08-24 06:29:42 +00002644ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002645 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002646 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002647 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002648}
2649
Chandler Carruth62da79c2011-05-26 08:53:12 +00002650static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2651 SourceLocation Loc,
2652 SourceRange ArgRange) {
2653 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2654 // scalar or vector data type argument..."
2655 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2656 // type (C99 6.2.5p18) or void.
2657 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2658 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2659 << T << ArgRange;
2660 return true;
2661 }
2662
2663 assert((T->isVoidType() || !T->isIncompleteType()) &&
2664 "Scalar types should always be complete");
2665 return false;
2666}
2667
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002668static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2669 SourceLocation Loc,
2670 SourceRange ArgRange,
2671 UnaryExprOrTypeTrait TraitKind) {
2672 // C99 6.5.3.4p1:
2673 if (T->isFunctionType()) {
2674 // alignof(function) is allowed as an extension.
2675 if (TraitKind == UETT_SizeOf)
2676 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2677 return false;
2678 }
2679
2680 // Allow sizeof(void)/alignof(void) as an extension.
2681 if (T->isVoidType()) {
2682 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2683 return false;
2684 }
2685
2686 return true;
2687}
2688
2689static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2690 SourceLocation Loc,
2691 SourceRange ArgRange,
2692 UnaryExprOrTypeTrait TraitKind) {
2693 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2694 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2695 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2696 << T << (TraitKind == UETT_SizeOf)
2697 << ArgRange;
2698 return true;
2699 }
2700
2701 return false;
2702}
2703
Chandler Carruth14502c22011-05-26 08:53:10 +00002704/// \brief Check the constrains on expression operands to unary type expression
2705/// and type traits.
2706///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002707/// Completes any types necessary and validates the constraints on the operand
2708/// expression. The logic mostly mirrors the type-based overload, but may modify
2709/// the expression as it completes the type for that expression through template
2710/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002711bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2712 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002713 QualType ExprTy = Op->getType();
2714
2715 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2716 // the result is the size of the referenced type."
2717 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2718 // result shall be the alignment of the referenced type."
2719 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2720 ExprTy = Ref->getPointeeType();
2721
2722 if (ExprKind == UETT_VecStep)
2723 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2724 Op->getSourceRange());
2725
2726 // Whitelist some types as extensions
2727 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2728 Op->getSourceRange(), ExprKind))
2729 return false;
2730
2731 if (RequireCompleteExprType(Op,
2732 PDiag(diag::err_sizeof_alignof_incomplete_type)
2733 << ExprKind << Op->getSourceRange(),
2734 std::make_pair(SourceLocation(), PDiag(0))))
2735 return true;
2736
2737 // Completeing the expression's type may have changed it.
2738 ExprTy = Op->getType();
2739 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2740 ExprTy = Ref->getPointeeType();
2741
2742 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2743 Op->getSourceRange(), ExprKind))
2744 return true;
2745
Nico Weber0870deb2011-06-15 02:47:03 +00002746 if (ExprKind == UETT_SizeOf) {
2747 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2748 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2749 QualType OType = PVD->getOriginalType();
2750 QualType Type = PVD->getType();
2751 if (Type->isPointerType() && OType->isArrayType()) {
2752 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2753 << Type << OType;
2754 Diag(PVD->getLocation(), diag::note_declared_at);
2755 }
2756 }
2757 }
2758 }
2759
Chandler Carruth7c430c02011-05-27 01:33:31 +00002760 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002761}
2762
2763/// \brief Check the constraints on operands to unary expression and type
2764/// traits.
2765///
2766/// This will complete any types necessary, and validate the various constraints
2767/// on those operands.
2768///
Steve Naroff71b59a92007-06-04 22:22:31 +00002769/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002770/// C99 6.3.2.1p[2-4] all state:
2771/// Except when it is the operand of the sizeof operator ...
2772///
2773/// C++ [expr.sizeof]p4
2774/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2775/// standard conversions are not applied to the operand of sizeof.
2776///
2777/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002778bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2779 SourceLocation OpLoc,
2780 SourceRange ExprRange,
2781 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002782 if (exprType->isDependentType())
2783 return false;
2784
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002785 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2786 // the result is the size of the referenced type."
2787 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2788 // result shall be the alignment of the referenced type."
2789 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2790 exprType = Ref->getPointeeType();
2791
Chandler Carruth62da79c2011-05-26 08:53:12 +00002792 if (ExprKind == UETT_VecStep)
2793 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002794
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002795 // Whitelist some types as extensions
2796 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2797 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002798 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Chris Lattner62975a72009-04-24 00:30:45 +00002800 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002801 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002802 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002803 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002804
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002805 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2806 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002807 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002808
Chris Lattner62975a72009-04-24 00:30:45 +00002809 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002810}
2811
Chandler Carruth14502c22011-05-26 08:53:10 +00002812static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002813 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002814
Mike Stump11289f42009-09-09 15:08:12 +00002815 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002816 if (isa<DeclRefExpr>(E))
2817 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002818
2819 // Cannot know anything else if the expression is dependent.
2820 if (E->isTypeDependent())
2821 return false;
2822
Douglas Gregor71235ec2009-05-02 02:18:30 +00002823 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002824 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2825 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002826 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002827 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002828
2829 // Alignment of a field access is always okay, so long as it isn't a
2830 // bit-field.
2831 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002832 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002833 return false;
2834
Chandler Carruth14502c22011-05-26 08:53:10 +00002835 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002836}
2837
Chandler Carruth14502c22011-05-26 08:53:10 +00002838bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002839 E = E->IgnoreParens();
2840
2841 // Cannot know anything else if the expression is dependent.
2842 if (E->isTypeDependent())
2843 return false;
2844
Chandler Carruth14502c22011-05-26 08:53:10 +00002845 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002846}
2847
Douglas Gregor0950e412009-03-13 21:01:28 +00002848/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002849ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002850Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2851 SourceLocation OpLoc,
2852 UnaryExprOrTypeTrait ExprKind,
2853 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002854 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002855 return ExprError();
2856
John McCallbcd03502009-12-07 02:54:59 +00002857 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002858
Douglas Gregor0950e412009-03-13 21:01:28 +00002859 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002860 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002861 return ExprError();
2862
2863 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002864 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2865 Context.getSizeType(),
2866 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002867}
2868
2869/// \brief Build a sizeof or alignof expression given an expression
2870/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002871ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002872Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2873 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002874 ExprResult PE = CheckPlaceholderExpr(E);
2875 if (PE.isInvalid())
2876 return ExprError();
2877
2878 E = PE.get();
2879
Douglas Gregor0950e412009-03-13 21:01:28 +00002880 // Verify that the operand is valid.
2881 bool isInvalid = false;
2882 if (E->isTypeDependent()) {
2883 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002884 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002885 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002886 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002887 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002888 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002889 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002890 isInvalid = true;
2891 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002892 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002893 }
2894
2895 if (isInvalid)
2896 return ExprError();
2897
2898 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002899 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002900 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002901 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002902}
2903
Peter Collingbournee190dee2011-03-11 19:24:49 +00002904/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2905/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002906/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002907ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002908Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2909 UnaryExprOrTypeTrait ExprKind, bool isType,
2910 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002911 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002912 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002913
Sebastian Redl6f282892008-11-11 17:56:53 +00002914 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002915 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002916 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002917 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002918 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002919
Douglas Gregor0950e412009-03-13 21:01:28 +00002920 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002921 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002922 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002923}
2924
John Wiegley01296292011-04-08 18:41:53 +00002925static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002926 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002927 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002928 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002929
John McCall34376a62010-12-04 03:47:34 +00002930 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002931 if (V.get()->getObjectKind() != OK_Ordinary) {
2932 V = S.DefaultLvalueConversion(V.take());
2933 if (V.isInvalid())
2934 return QualType();
2935 }
John McCall34376a62010-12-04 03:47:34 +00002936
Chris Lattnere267f5d2007-08-26 05:39:26 +00002937 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002938 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002939 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002940
Chris Lattnere267f5d2007-08-26 05:39:26 +00002941 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002942 if (V.get()->getType()->isArithmeticType())
2943 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002944
John McCall36226622010-10-12 02:09:17 +00002945 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002946 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002947 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002948 if (PR.get() != V.get()) {
2949 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002950 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002951 }
2952
Chris Lattnere267f5d2007-08-26 05:39:26 +00002953 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002954 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002955 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002956 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002957}
2958
2959
Chris Lattnere168f762006-11-10 05:29:30 +00002960
John McCalldadc5752010-08-24 06:29:42 +00002961ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002963 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002964 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002965 switch (Kind) {
2966 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002967 case tok::plusplus: Opc = UO_PostInc; break;
2968 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002969 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002970
John McCallb268a282010-08-23 23:25:46 +00002971 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002972}
2973
John McCalldadc5752010-08-24 06:29:42 +00002974ExprResult
John McCallb268a282010-08-23 23:25:46 +00002975Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2976 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002977 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002978 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002979 if (Result.isInvalid()) return ExprError();
2980 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002981
John McCallb268a282010-08-23 23:25:46 +00002982 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002983
Douglas Gregor40412ac2008-11-19 17:17:41 +00002984 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002985 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002986 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002987 Context.DependentTy,
2988 VK_LValue, OK_Ordinary,
2989 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002990 }
2991
Mike Stump11289f42009-09-09 15:08:12 +00002992 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002993 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002994 LHSExp->getType()->isEnumeralType() ||
2995 RHSExp->getType()->isRecordType() ||
2996 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002997 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002998 }
2999
John McCallb268a282010-08-23 23:25:46 +00003000 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003001}
3002
3003
John McCalldadc5752010-08-24 06:29:42 +00003004ExprResult
John McCallb268a282010-08-23 23:25:46 +00003005Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3006 Expr *Idx, SourceLocation RLoc) {
3007 Expr *LHSExp = Base;
3008 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003009
Chris Lattner36d572b2007-07-16 00:14:47 +00003010 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003011 if (!LHSExp->getType()->getAs<VectorType>()) {
3012 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3013 if (Result.isInvalid())
3014 return ExprError();
3015 LHSExp = Result.take();
3016 }
3017 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3018 if (Result.isInvalid())
3019 return ExprError();
3020 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003021
Chris Lattner36d572b2007-07-16 00:14:47 +00003022 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003023 ExprValueKind VK = VK_LValue;
3024 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003025
Steve Naroffc1aadb12007-03-28 21:49:40 +00003026 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003027 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003028 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003029 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003030 Expr *BaseExpr, *IndexExpr;
3031 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003032 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3033 BaseExpr = LHSExp;
3034 IndexExpr = RHSExp;
3035 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003036 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003037 BaseExpr = LHSExp;
3038 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003039 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003040 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003041 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003042 BaseExpr = RHSExp;
3043 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003044 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003045 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003046 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003047 BaseExpr = LHSExp;
3048 IndexExpr = RHSExp;
3049 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003050 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003051 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003052 // Handle the uncommon case of "123[Ptr]".
3053 BaseExpr = RHSExp;
3054 IndexExpr = LHSExp;
3055 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003056 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003057 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003058 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003059 VK = LHSExp->getValueKind();
3060 if (VK != VK_RValue)
3061 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003062
Chris Lattner36d572b2007-07-16 00:14:47 +00003063 // FIXME: need to deal with const...
3064 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003065 } else if (LHSTy->isArrayType()) {
3066 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003067 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003068 // wasn't promoted because of the C90 rule that doesn't
3069 // allow promoting non-lvalue arrays. Warn, then
3070 // force the promotion here.
3071 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3072 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003073 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3074 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003075 LHSTy = LHSExp->getType();
3076
3077 BaseExpr = LHSExp;
3078 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003079 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003080 } else if (RHSTy->isArrayType()) {
3081 // Same as previous, except for 123[f().a] case
3082 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3083 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003084 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3085 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003086 RHSTy = RHSExp->getType();
3087
3088 BaseExpr = RHSExp;
3089 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003090 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003091 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003092 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3093 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003094 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003095 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003096 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003097 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3098 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003099
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003100 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003101 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3102 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003103 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3104
Douglas Gregorac1fb652009-03-24 19:52:54 +00003105 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003106 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3107 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003108 // incomplete types are not object types.
3109 if (ResultType->isFunctionType()) {
3110 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3111 << ResultType << BaseExpr->getSourceRange();
3112 return ExprError();
3113 }
Mike Stump11289f42009-09-09 15:08:12 +00003114
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003115 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3116 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003117 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3118 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003119
3120 // C forbids expressions of unqualified void type from being l-values.
3121 // See IsCForbiddenLValueType.
3122 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003123 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003124 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003125 PDiag(diag::err_subscript_incomplete_type)
3126 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003127 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003128
Chris Lattner62975a72009-04-24 00:30:45 +00003129 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003130 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003131 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3132 << ResultType << BaseExpr->getSourceRange();
3133 return ExprError();
3134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
John McCall4bc41ae2010-11-18 19:01:18 +00003136 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003137 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003138
Mike Stump4e1f26a2009-02-19 03:04:26 +00003139 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003140 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003141}
3142
John McCalldadc5752010-08-24 06:29:42 +00003143ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003144 FunctionDecl *FD,
3145 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003146 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003147 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003148 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003149 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003150 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003151 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003152 return ExprError();
3153 }
3154
3155 if (Param->hasUninstantiatedDefaultArg()) {
3156 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003157
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003158 // Instantiate the expression.
3159 MultiLevelTemplateArgumentList ArgList
3160 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003161
Nico Weber44887f62010-11-29 18:19:25 +00003162 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003163 = ArgList.getInnermost();
3164 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3165 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003166
Nico Weber44887f62010-11-29 18:19:25 +00003167 ExprResult Result;
3168 {
3169 // C++ [dcl.fct.default]p5:
3170 // The names in the [default argument] expression are bound, and
3171 // the semantic constraints are checked, at the point where the
3172 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003173 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003174 Result = SubstExpr(UninstExpr, ArgList);
3175 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003176 if (Result.isInvalid())
3177 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003178
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003179 // Check the expression as an initializer for the parameter.
3180 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003181 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003182 InitializationKind Kind
3183 = InitializationKind::CreateCopy(Param->getLocation(),
3184 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3185 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003186
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003187 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3188 Result = InitSeq.Perform(*this, Entity, Kind,
3189 MultiExprArg(*this, &ResultE, 1));
3190 if (Result.isInvalid())
3191 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003192
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003193 // Build the default argument expression.
3194 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3195 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003196 }
3197
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198 // If the default expression creates temporaries, we need to
3199 // push them to the current stack of expression temporaries so they'll
3200 // be properly destroyed.
3201 // FIXME: We should really be rebuilding the default argument with new
3202 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003203 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3204 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3205 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3206 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3207 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003208 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003209 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003210
3211 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003212 // Just mark all of the declarations in this potentially-evaluated expression
3213 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003214 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003215 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003216}
3217
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003218/// ConvertArgumentsForCall - Converts the arguments specified in
3219/// Args/NumArgs to the parameter types of the function FDecl with
3220/// function prototype Proto. Call is the call expression itself, and
3221/// Fn is the function expression. For a C++ member function, this
3222/// routine does not attempt to convert the object argument. Returns
3223/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003224bool
3225Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003226 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003227 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003228 Expr **Args, unsigned NumArgs,
3229 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003230 // Bail out early if calling a builtin with custom typechecking.
3231 // We don't need to do this in the
3232 if (FDecl)
3233 if (unsigned ID = FDecl->getBuiltinID())
3234 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3235 return false;
3236
Mike Stump4e1f26a2009-02-19 03:04:26 +00003237 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003238 // assignment, to the types of the corresponding parameter, ...
3239 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003240 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003241
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003242 // If too few arguments are available (and we don't have default
3243 // arguments for the remaining parameters), don't make the call.
3244 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003245 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3246 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003247 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003248 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003249
3250 // Emit the location of the prototype.
3251 if (FDecl && !FDecl->getBuiltinID())
3252 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3253 << FDecl;
3254
3255 return true;
3256 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003257 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003258 }
3259
3260 // If too many are passed and not variadic, error on the extras and drop
3261 // them.
3262 if (NumArgs > NumArgsInProto) {
3263 if (!Proto->isVariadic()) {
3264 Diag(Args[NumArgsInProto]->getLocStart(),
3265 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003266 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003267 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003268 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3269 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003270
3271 // Emit the location of the prototype.
3272 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003273 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3274 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003275
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003276 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003277 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003278 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003279 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003280 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003281 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003282 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003283 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3284 if (Fn->getType()->isBlockPointerType())
3285 CallType = VariadicBlock; // Block
3286 else if (isa<MemberExpr>(Fn))
3287 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003288 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003289 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003290 if (Invalid)
3291 return true;
3292 unsigned TotalNumArgs = AllArgs.size();
3293 for (unsigned i = 0; i < TotalNumArgs; ++i)
3294 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003295
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003296 return false;
3297}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003298
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003299bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3300 FunctionDecl *FDecl,
3301 const FunctionProtoType *Proto,
3302 unsigned FirstProtoArg,
3303 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003304 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003305 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003306 unsigned NumArgsInProto = Proto->getNumArgs();
3307 unsigned NumArgsToCheck = NumArgs;
3308 bool Invalid = false;
3309 if (NumArgs != NumArgsInProto)
3310 // Use default arguments for missing arguments
3311 NumArgsToCheck = NumArgsInProto;
3312 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003313 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003314 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003315 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003316
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003318 if (ArgIx < NumArgs) {
3319 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003320
Eli Friedman3164fb12009-03-22 22:00:50 +00003321 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3322 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003323 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003324 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003325 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003326
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003327 // Pass the argument
3328 ParmVarDecl *Param = 0;
3329 if (FDecl && i < FDecl->getNumParams())
3330 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003331
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003332 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003333 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003334 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3335 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003336 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003337 SourceLocation(),
3338 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003339 if (ArgE.isInvalid())
3340 return true;
3341
3342 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003343 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003344 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003345
John McCalldadc5752010-08-24 06:29:42 +00003346 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003347 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003348 if (ArgExpr.isInvalid())
3349 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003350
Anders Carlsson355933d2009-08-25 03:49:14 +00003351 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003352 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003353 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003354 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003355
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003356 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003357 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003358
3359 // Assume that extern "C" functions with variadic arguments that
3360 // return __unknown_anytype aren't *really* variadic.
3361 if (Proto->getResultType() == Context.UnknownAnyTy &&
3362 FDecl && FDecl->isExternC()) {
3363 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3364 ExprResult arg;
3365 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3366 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3367 else
3368 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3369 Invalid |= arg.isInvalid();
3370 AllArgs.push_back(arg.take());
3371 }
3372
3373 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3374 } else {
3375 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3376 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3377 Invalid |= Arg.isInvalid();
3378 AllArgs.push_back(Arg.take());
3379 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003380 }
3381 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003382 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003383}
3384
John McCall2979fe02011-04-12 00:42:48 +00003385/// Given a function expression of unknown-any type, try to rebuild it
3386/// to have a function type.
3387static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3388
Steve Naroff83895f72007-09-16 03:34:24 +00003389/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003390/// This provides the location of the left/right parens and a list of comma
3391/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003392ExprResult
John McCallb268a282010-08-23 23:25:46 +00003393Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003394 MultiExprArg args, SourceLocation RParenLoc,
3395 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003396 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003397
3398 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003399 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003400 if (Result.isInvalid()) return ExprError();
3401 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003402
John McCallb268a282010-08-23 23:25:46 +00003403 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003404
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003406 // If this is a pseudo-destructor expression, build the call immediately.
3407 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3408 if (NumArgs > 0) {
3409 // Pseudo-destructor calls should not have any arguments.
3410 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003411 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003412 SourceRange(Args[0]->getLocStart(),
3413 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003414
Douglas Gregorad8a3362009-09-04 17:36:40 +00003415 NumArgs = 0;
3416 }
Mike Stump11289f42009-09-09 15:08:12 +00003417
Douglas Gregorad8a3362009-09-04 17:36:40 +00003418 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003419 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003420 }
Mike Stump11289f42009-09-09 15:08:12 +00003421
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003422 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003423 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003424 // FIXME: Will need to cache the results of name lookup (including ADL) in
3425 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003426 bool Dependent = false;
3427 if (Fn->isTypeDependent())
3428 Dependent = true;
3429 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3430 Dependent = true;
3431
Peter Collingbourne41f85462011-02-09 21:07:24 +00003432 if (Dependent) {
3433 if (ExecConfig) {
3434 return Owned(new (Context) CUDAKernelCallExpr(
3435 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3436 Context.DependentTy, VK_RValue, RParenLoc));
3437 } else {
3438 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3439 Context.DependentTy, VK_RValue,
3440 RParenLoc));
3441 }
3442 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003443
3444 // Determine whether this is a call to an object (C++ [over.call.object]).
3445 if (Fn->getType()->isRecordType())
3446 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003447 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003448
John McCall2979fe02011-04-12 00:42:48 +00003449 if (Fn->getType() == Context.UnknownAnyTy) {
3450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3451 if (result.isInvalid()) return ExprError();
3452 Fn = result.take();
3453 }
3454
John McCall0009fcc2011-04-26 20:42:42 +00003455 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003456 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003457 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003458 }
John McCall0009fcc2011-04-26 20:42:42 +00003459 }
John McCall10eae182009-11-30 22:42:35 +00003460
John McCall0009fcc2011-04-26 20:42:42 +00003461 // Check for overloaded calls. This can happen even in C due to extensions.
3462 if (Fn->getType() == Context.OverloadTy) {
3463 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3464
3465 // We aren't supposed to apply this logic if there's an '&' involved.
3466 if (!find.IsAddressOfOperand) {
3467 OverloadExpr *ovl = find.Expression;
3468 if (isa<UnresolvedLookupExpr>(ovl)) {
3469 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3470 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3471 RParenLoc, ExecConfig);
3472 } else {
John McCall2d74de92009-12-01 22:10:20 +00003473 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003474 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003475 }
3476 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003477 }
3478
Douglas Gregore254f902009-02-04 00:32:51 +00003479 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003480
Eli Friedmane14b1992009-12-26 03:35:45 +00003481 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003482
John McCall57500772009-12-16 12:17:52 +00003483 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003484 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3485 if (UnOp->getOpcode() == UO_AddrOf)
3486 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3487
John McCall57500772009-12-16 12:17:52 +00003488 if (isa<DeclRefExpr>(NakedFn))
3489 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003490 else if (isa<MemberExpr>(NakedFn))
3491 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003492
Peter Collingbourne41f85462011-02-09 21:07:24 +00003493 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3494 ExecConfig);
3495}
3496
3497ExprResult
3498Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3499 MultiExprArg execConfig, SourceLocation GGGLoc) {
3500 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3501 if (!ConfigDecl)
3502 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3503 << "cudaConfigureCall");
3504 QualType ConfigQTy = ConfigDecl->getType();
3505
3506 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3507 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3508
3509 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003510}
3511
Tanya Lattner55808c12011-06-04 00:47:47 +00003512/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3513///
3514/// __builtin_astype( value, dst type )
3515///
3516ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3517 SourceLocation BuiltinLoc,
3518 SourceLocation RParenLoc) {
3519 ExprValueKind VK = VK_RValue;
3520 ExprObjectKind OK = OK_Ordinary;
3521 QualType DstTy = GetTypeFromParser(destty);
3522 QualType SrcTy = expr->getType();
3523 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3524 return ExprError(Diag(BuiltinLoc,
3525 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003526 << DstTy
3527 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003528 << expr->getSourceRange());
3529 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3530}
3531
John McCall57500772009-12-16 12:17:52 +00003532/// BuildResolvedCallExpr - Build a call to a resolved expression,
3533/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003534/// unary-convert to an expression of function-pointer or
3535/// block-pointer type.
3536///
3537/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003538ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003539Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3540 SourceLocation LParenLoc,
3541 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003542 SourceLocation RParenLoc,
3543 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003544 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3545
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003546 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003547 ExprResult Result = UsualUnaryConversions(Fn);
3548 if (Result.isInvalid())
3549 return ExprError();
3550 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003551
Chris Lattner08464942007-12-28 05:29:59 +00003552 // Make the call expr early, before semantic checks. This guarantees cleanup
3553 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003554 CallExpr *TheCall;
3555 if (Config) {
3556 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3557 cast<CallExpr>(Config),
3558 Args, NumArgs,
3559 Context.BoolTy,
3560 VK_RValue,
3561 RParenLoc);
3562 } else {
3563 TheCall = new (Context) CallExpr(Context, Fn,
3564 Args, NumArgs,
3565 Context.BoolTy,
3566 VK_RValue,
3567 RParenLoc);
3568 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003569
John McCallbebede42011-02-26 05:39:39 +00003570 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3571
3572 // Bail out early if calling a builtin with custom typechecking.
3573 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3574 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3575
John McCall31996342011-04-07 08:22:57 +00003576 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003577 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003578 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003579 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3580 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003581 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003582 if (FuncT == 0)
3583 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3584 << Fn->getType() << Fn->getSourceRange());
3585 } else if (const BlockPointerType *BPT =
3586 Fn->getType()->getAs<BlockPointerType>()) {
3587 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3588 } else {
John McCall31996342011-04-07 08:22:57 +00003589 // Handle calls to expressions of unknown-any type.
3590 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003591 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003592 if (rewrite.isInvalid()) return ExprError();
3593 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003594 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003595 goto retry;
3596 }
3597
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003598 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3599 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003600 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003601
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003602 if (getLangOptions().CUDA) {
3603 if (Config) {
3604 // CUDA: Kernel calls must be to global functions
3605 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3606 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3607 << FDecl->getName() << Fn->getSourceRange());
3608
3609 // CUDA: Kernel function must have 'void' return type
3610 if (!FuncT->getResultType()->isVoidType())
3611 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3612 << Fn->getType() << Fn->getSourceRange());
3613 }
3614 }
3615
Eli Friedman3164fb12009-03-22 22:00:50 +00003616 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003617 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003618 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003619 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003620 return ExprError();
3621
Chris Lattner08464942007-12-28 05:29:59 +00003622 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003623 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003624 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003625
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003626 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003627 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003628 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003629 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003630 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003631 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003632
Douglas Gregord8e97de2009-04-02 15:37:10 +00003633 if (FDecl) {
3634 // Check if we have too few/too many template arguments, based
3635 // on our knowledge of the function definition.
3636 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003637 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003638 const FunctionProtoType *Proto
3639 = Def->getType()->getAs<FunctionProtoType>();
3640 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003641 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3642 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003643 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003644
3645 // If the function we're calling isn't a function prototype, but we have
3646 // a function prototype from a prior declaratiom, use that prototype.
3647 if (!FDecl->hasPrototype())
3648 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003649 }
3650
Steve Naroff0b661582007-08-28 23:30:39 +00003651 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003652 for (unsigned i = 0; i != NumArgs; i++) {
3653 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003654
3655 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003656 InitializedEntity Entity
3657 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003658 Proto->getArgType(i),
3659 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003660 ExprResult ArgE = PerformCopyInitialization(Entity,
3661 SourceLocation(),
3662 Owned(Arg));
3663 if (ArgE.isInvalid())
3664 return true;
3665
3666 Arg = ArgE.takeAs<Expr>();
3667
3668 } else {
John Wiegley01296292011-04-08 18:41:53 +00003669 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3670
3671 if (ArgE.isInvalid())
3672 return true;
3673
3674 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003675 }
3676
Douglas Gregor83025412010-10-26 05:45:40 +00003677 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3678 Arg->getType(),
3679 PDiag(diag::err_call_incomplete_argument)
3680 << Arg->getSourceRange()))
3681 return ExprError();
3682
Chris Lattner08464942007-12-28 05:29:59 +00003683 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003684 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003685 }
Chris Lattner08464942007-12-28 05:29:59 +00003686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003687 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3688 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003689 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3690 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003691
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003692 // Check for sentinels
3693 if (NDecl)
3694 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003695
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003696 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003697 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003698 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003699 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003700
John McCallbebede42011-02-26 05:39:39 +00003701 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003702 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003703 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003704 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003705 return ExprError();
3706 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003707
John McCallb268a282010-08-23 23:25:46 +00003708 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003709}
3710
John McCalldadc5752010-08-24 06:29:42 +00003711ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003712Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003713 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003714 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003715 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003716 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003717
3718 TypeSourceInfo *TInfo;
3719 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3720 if (!TInfo)
3721 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3722
John McCallb268a282010-08-23 23:25:46 +00003723 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003724}
3725
John McCalldadc5752010-08-24 06:29:42 +00003726ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003727Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003728 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003729 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003730
Eli Friedman37a186d2008-05-20 05:22:08 +00003731 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003732 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3733 PDiag(diag::err_illegal_decl_array_incomplete_type)
3734 << SourceRange(LParenLoc,
3735 literalExpr->getSourceRange().getEnd())))
3736 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003737 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003738 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3739 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003740 } else if (!literalType->isDependentType() &&
3741 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003742 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003743 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003744 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003745 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003746
Douglas Gregor85dabae2009-12-16 01:38:02 +00003747 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003748 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003749 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003750 = InitializationKind::CreateCStyleCast(LParenLoc,
3751 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003752 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003753 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003754 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003755 &literalType);
3756 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003757 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003758 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003759
Chris Lattner79413952008-12-04 23:50:19 +00003760 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003761 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003762 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003763 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003764 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003765
John McCall7decc9e2010-11-18 06:31:45 +00003766 // In C, compound literals are l-values for some reason.
3767 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3768
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003769 return MaybeBindToTemporary(
3770 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3771 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003772}
3773
John McCalldadc5752010-08-24 06:29:42 +00003774ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003775Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003776 SourceLocation RBraceLoc) {
3777 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003778 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003779
Steve Naroff30d242c2007-09-15 18:49:24 +00003780 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003781 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003782
Ted Kremenekac034612010-04-13 23:39:13 +00003783 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3784 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003785 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003786 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003787}
3788
John McCalld7646252010-11-14 08:17:51 +00003789/// Prepares for a scalar cast, performing all the necessary stages
3790/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003791static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003792 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3793 // Also, callers should have filtered out the invalid cases with
3794 // pointers. Everything else should be possible.
3795
John Wiegley01296292011-04-08 18:41:53 +00003796 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003797 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003798 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003799
John McCall8cb679e2010-11-15 09:13:47 +00003800 switch (SrcTy->getScalarTypeKind()) {
3801 case Type::STK_MemberPointer:
3802 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003803
John McCall8cb679e2010-11-15 09:13:47 +00003804 case Type::STK_Pointer:
3805 switch (DestTy->getScalarTypeKind()) {
3806 case Type::STK_Pointer:
3807 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003808 CK_AnyPointerToObjCPointerCast :
3809 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003810 case Type::STK_Bool:
3811 return CK_PointerToBoolean;
3812 case Type::STK_Integral:
3813 return CK_PointerToIntegral;
3814 case Type::STK_Floating:
3815 case Type::STK_FloatingComplex:
3816 case Type::STK_IntegralComplex:
3817 case Type::STK_MemberPointer:
3818 llvm_unreachable("illegal cast from pointer");
3819 }
3820 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003821
John McCall8cb679e2010-11-15 09:13:47 +00003822 case Type::STK_Bool: // casting from bool is like casting from an integer
3823 case Type::STK_Integral:
3824 switch (DestTy->getScalarTypeKind()) {
3825 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003826 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003827 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003828 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003829 case Type::STK_Bool:
3830 return CK_IntegralToBoolean;
3831 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003832 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003833 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003834 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003835 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003836 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3837 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003838 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003839 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003840 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3841 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003842 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003843 case Type::STK_MemberPointer:
3844 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003845 }
3846 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003847
John McCall8cb679e2010-11-15 09:13:47 +00003848 case Type::STK_Floating:
3849 switch (DestTy->getScalarTypeKind()) {
3850 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003851 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003852 case Type::STK_Bool:
3853 return CK_FloatingToBoolean;
3854 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003855 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003856 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003857 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3858 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003859 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003860 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003861 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3862 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003863 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003864 case Type::STK_Pointer:
3865 llvm_unreachable("valid float->pointer cast?");
3866 case Type::STK_MemberPointer:
3867 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003868 }
3869 break;
3870
John McCall8cb679e2010-11-15 09:13:47 +00003871 case Type::STK_FloatingComplex:
3872 switch (DestTy->getScalarTypeKind()) {
3873 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003874 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003875 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003876 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003877 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003878 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003879 if (S.Context.hasSameType(ET, DestTy))
3880 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003881 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003882 return CK_FloatingCast;
3883 }
John McCall8cb679e2010-11-15 09:13:47 +00003884 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003885 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003886 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003887 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3888 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003889 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003890 case Type::STK_Pointer:
3891 llvm_unreachable("valid complex float->pointer cast?");
3892 case Type::STK_MemberPointer:
3893 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003894 }
3895 break;
3896
John McCall8cb679e2010-11-15 09:13:47 +00003897 case Type::STK_IntegralComplex:
3898 switch (DestTy->getScalarTypeKind()) {
3899 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003900 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003901 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003902 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003903 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003904 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003905 if (S.Context.hasSameType(ET, DestTy))
3906 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003907 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003908 return CK_IntegralCast;
3909 }
John McCall8cb679e2010-11-15 09:13:47 +00003910 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003911 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003912 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003913 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3914 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003915 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003916 case Type::STK_Pointer:
3917 llvm_unreachable("valid complex int->pointer cast?");
3918 case Type::STK_MemberPointer:
3919 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003920 }
3921 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003922 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003923
John McCalld7646252010-11-14 08:17:51 +00003924 llvm_unreachable("Unhandled scalar cast");
3925 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003926}
3927
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003928/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003929ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3930 QualType castType, Expr *castExpr,
3931 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003932 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003933 if (castExpr->getType() == Context.UnknownAnyTy)
3934 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3935
Sebastian Redl9f831db2009-07-25 15:41:38 +00003936 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003937 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003938 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003939 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003940 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003941
John McCall3aef3d82011-04-10 19:13:55 +00003942 assert(!castExpr->getType()->isPlaceholderType());
3943
John McCall7decc9e2010-11-18 06:31:45 +00003944 // We only support r-value casts in C.
3945 VK = VK_RValue;
3946
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003947 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3948 // type needs to be scalar.
3949 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003950 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003951 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3952 if (castExprRes.isInvalid())
3953 return ExprError();
3954 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003955
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003956 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003957 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003958 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003959 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003960
John Wiegley01296292011-04-08 18:41:53 +00003961 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3962 if (castExprRes.isInvalid())
3963 return ExprError();
3964 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003965
Eli Friedmane98194d2010-07-17 20:43:49 +00003966 if (RequireCompleteType(TyR.getBegin(), castType,
3967 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003968 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003969
Anders Carlssonef918ac2009-10-16 02:35:04 +00003970 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003971 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003972 (castType->isStructureType() || castType->isUnionType())) {
3973 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003974 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003975 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3976 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003977 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003978 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003979 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003980
Anders Carlsson525b76b2009-10-16 02:48:28 +00003981 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003982 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003983 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003984 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003985 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003986 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003987 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003988 castExpr->getType()) &&
3989 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003990 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3991 << castExpr->getSourceRange();
3992 break;
3993 }
3994 }
John Wiegley01296292011-04-08 18:41:53 +00003995 if (Field == FieldEnd) {
3996 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003997 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003998 return ExprError();
3999 }
John McCalle3027922010-08-25 11:45:40 +00004000 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004001 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004002 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004003
Anders Carlsson525b76b2009-10-16 02:48:28 +00004004 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004005 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004006 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004007 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004009
John McCalld7646252010-11-14 08:17:51 +00004010 // The type we're casting to is known to be a scalar or vector.
4011
4012 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004013 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004014 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004015 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004016 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004017 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004018 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004019 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004020
4021 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004022 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004023
Anton Yartsev28ccef72011-03-27 09:32:40 +00004024 if (castType->isVectorType()) {
4025 if (castType->getAs<VectorType>()->getVectorKind() ==
4026 VectorType::AltiVecVector &&
4027 (castExpr->getType()->isIntegerType() ||
4028 castExpr->getType()->isFloatingType())) {
4029 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004030 return Owned(castExpr);
4031 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4032 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004033 } else
John Wiegley01296292011-04-08 18:41:53 +00004034 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004035 }
John Wiegley01296292011-04-08 18:41:53 +00004036 if (castExpr->getType()->isVectorType()) {
4037 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4038 return ExprError();
4039 else
4040 return Owned(castExpr);
4041 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004042
John McCalld7646252010-11-14 08:17:51 +00004043 // The source and target types are both scalars, i.e.
4044 // - arithmetic types (fundamental, enum, and complex)
4045 // - all kinds of pointers
4046 // Note that member pointers were filtered out with C++, above.
4047
John Wiegley01296292011-04-08 18:41:53 +00004048 if (isa<ObjCSelectorExpr>(castExpr)) {
4049 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4050 return ExprError();
4051 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004052
John McCalld7646252010-11-14 08:17:51 +00004053 // If either type is a pointer, the other type has to be either an
4054 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004055 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004056 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004057 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004058 castExprType->isArithmeticType()) {
4059 Diag(castExpr->getLocStart(),
4060 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004061 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004062 return ExprError();
4063 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004064 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004065 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4066 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004067 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004068 return ExprError();
4069 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004070 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004071
John McCall31168b02011-06-15 23:02:42 +00004072 if (getLangOptions().ObjCAutoRefCount) {
4073 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4074 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4075 castType, castExpr, CCK_CStyleCast);
4076
4077 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4078 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4079 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4080 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4081 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4082 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4083 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4084 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004085 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004086 << castExprType << castType << AA_Casting
4087 << castExpr->getSourceRange();
4088
4089 return ExprError();
4090 }
4091 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004092 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004093 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4094 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004095 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004096 << castExprType << castType
4097 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004098 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004099 }
4100 }
4101
John Wiegley01296292011-04-08 18:41:53 +00004102 castExprRes = Owned(castExpr);
4103 Kind = PrepareScalarCast(*this, castExprRes, castType);
4104 if (castExprRes.isInvalid())
4105 return ExprError();
4106 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004107
John McCalld7646252010-11-14 08:17:51 +00004108 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004109 CheckCastAlign(castExpr, castType, TyR);
4110
John Wiegley01296292011-04-08 18:41:53 +00004111 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004112}
4113
Anders Carlsson525b76b2009-10-16 02:48:28 +00004114bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004115 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004116 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004117
Anders Carlssonde71adf2007-11-27 05:51:55 +00004118 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004119 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004120 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004121 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004122 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004123 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004124 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004125 } else
4126 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004127 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004128 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004129
John McCalle3027922010-08-25 11:45:40 +00004130 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004131 return false;
4132}
4133
John Wiegley01296292011-04-08 18:41:53 +00004134ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4135 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004136 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004137
Anders Carlsson43d70f82009-10-16 05:23:41 +00004138 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004139
Nate Begemanc8961a42009-06-27 22:05:55 +00004140 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4141 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004142 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004143 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4144 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004145 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004146 return ExprError();
4147 }
John McCalle3027922010-08-25 11:45:40 +00004148 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004149 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004150 }
4151
Nate Begemanbd956c42009-06-28 02:36:38 +00004152 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004153 // conversion will take place first from scalar to elt type, and then
4154 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004155 if (SrcTy->isPointerType())
4156 return Diag(R.getBegin(),
4157 diag::err_invalid_conversion_between_vector_and_scalar)
4158 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004159
4160 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004161 ExprResult CastExprRes = Owned(CastExpr);
4162 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4163 if (CastExprRes.isInvalid())
4164 return ExprError();
4165 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004166
John McCalle3027922010-08-25 11:45:40 +00004167 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004168 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004169}
4170
John McCalldadc5752010-08-24 06:29:42 +00004171ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004172Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4173 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004174 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004175 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004176 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004177
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004178 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4179 if (D.isInvalidType())
4180 return ExprError();
4181
4182 if (getLangOptions().CPlusPlus) {
4183 // Check that there are no default arguments (C++ only).
4184 CheckExtraCXXDefaultArguments(D);
4185 }
4186
4187 QualType castType = castTInfo->getType();
4188 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004189
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004190 bool isVectorLiteral = false;
4191
4192 // Check for an altivec or OpenCL literal,
4193 // i.e. all the elements are integer constants.
4194 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4195 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4196 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4197 if (PLE && PLE->getNumExprs() == 0) {
4198 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4199 return ExprError();
4200 }
4201 if (PE || PLE->getNumExprs() == 1) {
4202 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4203 if (!E->getType()->isVectorType())
4204 isVectorLiteral = true;
4205 }
4206 else
4207 isVectorLiteral = true;
4208 }
4209
4210 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4211 // then handle it as such.
4212 if (isVectorLiteral)
4213 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4214
Nate Begeman5ec4b312009-08-10 23:49:36 +00004215 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004216 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4217 // sequence of BinOp comma operators.
4218 if (isa<ParenListExpr>(castExpr)) {
4219 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4220 if (Result.isInvalid()) return ExprError();
4221 castExpr = Result.take();
4222 }
John McCallebe54742010-01-15 18:56:44 +00004223
John McCallb268a282010-08-23 23:25:46 +00004224 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004225}
4226
John McCalldadc5752010-08-24 06:29:42 +00004227ExprResult
John McCallebe54742010-01-15 18:56:44 +00004228Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004229 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004230 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004231 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004232 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004233 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004234 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4235 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004236 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004237 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004238 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004239
John McCallcf142162010-08-07 06:22:56 +00004240 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004241 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004242 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004243 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004244}
4245
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004246ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4247 SourceLocation RParenLoc, Expr *E,
4248 TypeSourceInfo *TInfo) {
4249 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4250 "Expected paren or paren list expression");
4251
4252 Expr **exprs;
4253 unsigned numExprs;
4254 Expr *subExpr;
4255 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4256 exprs = PE->getExprs();
4257 numExprs = PE->getNumExprs();
4258 } else {
4259 subExpr = cast<ParenExpr>(E)->getSubExpr();
4260 exprs = &subExpr;
4261 numExprs = 1;
4262 }
4263
4264 QualType Ty = TInfo->getType();
4265 assert(Ty->isVectorType() && "Expected vector type");
4266
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004267 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004268 const VectorType *VTy = Ty->getAs<VectorType>();
4269 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4270
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004271 // '(...)' form of vector initialization in AltiVec: the number of
4272 // initializers must be one or must match the size of the vector.
4273 // If a single value is specified in the initializer then it will be
4274 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004275 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004276 // The number of initializers must be one or must match the size of the
4277 // vector. If a single value is specified in the initializer then it will
4278 // be replicated to all the components of the vector
4279 if (numExprs == 1) {
4280 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4281 ExprResult Literal = Owned(exprs[0]);
4282 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4283 PrepareScalarCast(*this, Literal, ElemTy));
4284 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4285 }
4286 else if (numExprs < numElems) {
4287 Diag(E->getExprLoc(),
4288 diag::err_incorrect_number_of_vector_initializers);
4289 return ExprError();
4290 }
4291 else
4292 for (unsigned i = 0, e = numExprs; i != e; ++i)
4293 initExprs.push_back(exprs[i]);
4294 }
Tanya Lattner83559382011-07-15 23:07:01 +00004295 else {
4296 // For OpenCL, when the number of initializers is a single value,
4297 // it will be replicated to all components of the vector.
4298 if (getLangOptions().OpenCL &&
4299 VTy->getVectorKind() == VectorType::GenericVector &&
4300 numExprs == 1) {
4301 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4302 ExprResult Literal = Owned(exprs[0]);
4303 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4304 PrepareScalarCast(*this, Literal, ElemTy));
4305 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4306 }
4307
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004308 for (unsigned i = 0, e = numExprs; i != e; ++i)
4309 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004310 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004311 // FIXME: This means that pretty-printing the final AST will produce curly
4312 // braces instead of the original commas.
4313 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4314 &initExprs[0],
4315 initExprs.size(), RParenLoc);
4316 initE->setType(Ty);
4317 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4318}
4319
Nate Begeman5ec4b312009-08-10 23:49:36 +00004320/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4321/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004322ExprResult
John McCallb268a282010-08-23 23:25:46 +00004323Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004324 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4325 if (!E)
4326 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004327
John McCalldadc5752010-08-24 06:29:42 +00004328 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004329
Nate Begeman5ec4b312009-08-10 23:49:36 +00004330 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004331 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4332 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004333
John McCallb268a282010-08-23 23:25:46 +00004334 if (Result.isInvalid()) return ExprError();
4335
4336 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004337}
4338
John McCalldadc5752010-08-24 06:29:42 +00004339ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004340 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004341 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004342 unsigned nexprs = Val.size();
4343 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004344 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4345 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004346 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004347 expr = new (Context) ParenExpr(L, R, exprs[0]);
4348 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004349 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4350 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004351 return Owned(expr);
4352}
4353
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004354/// \brief Emit a specialized diagnostic when one expression is a null pointer
4355/// constant and the other is not a pointer.
4356bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4357 SourceLocation QuestionLoc) {
4358 Expr *NullExpr = LHS;
4359 Expr *NonPointerExpr = RHS;
4360 Expr::NullPointerConstantKind NullKind =
4361 NullExpr->isNullPointerConstant(Context,
4362 Expr::NPC_ValueDependentIsNotNull);
4363
4364 if (NullKind == Expr::NPCK_NotNull) {
4365 NullExpr = RHS;
4366 NonPointerExpr = LHS;
4367 NullKind =
4368 NullExpr->isNullPointerConstant(Context,
4369 Expr::NPC_ValueDependentIsNotNull);
4370 }
4371
4372 if (NullKind == Expr::NPCK_NotNull)
4373 return false;
4374
4375 if (NullKind == Expr::NPCK_ZeroInteger) {
4376 // In this case, check to make sure that we got here from a "NULL"
4377 // string in the source code.
4378 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004379 SourceLocation loc = NullExpr->getExprLoc();
4380 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004381 return false;
4382 }
4383
4384 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4385 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4386 << NonPointerExpr->getType() << DiagType
4387 << NonPointerExpr->getSourceRange();
4388 return true;
4389}
4390
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004391/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4392/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004393/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004394QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004395 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004396 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004397
John McCall3aef3d82011-04-10 19:13:55 +00004398 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004399 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004400 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004401
John McCall3aef3d82011-04-10 19:13:55 +00004402 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004403 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004404 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004405
Sebastian Redl1a99f442009-04-16 17:51:27 +00004406 // C++ is sufficiently different to merit its own checker.
4407 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004408 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004409
4410 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004411 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004412
John Wiegley01296292011-04-08 18:41:53 +00004413 Cond = UsualUnaryConversions(Cond.take());
4414 if (Cond.isInvalid())
4415 return QualType();
4416 LHS = UsualUnaryConversions(LHS.take());
4417 if (LHS.isInvalid())
4418 return QualType();
4419 RHS = UsualUnaryConversions(RHS.take());
4420 if (RHS.isInvalid())
4421 return QualType();
4422
4423 QualType CondTy = Cond.get()->getType();
4424 QualType LHSTy = LHS.get()->getType();
4425 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004426
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004427 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004428 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004429 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4430 // Throw an error if its not either.
4431 if (getLangOptions().OpenCL) {
4432 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004433 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004434 diag::err_typecheck_cond_expect_scalar_or_vector)
4435 << CondTy;
4436 return QualType();
4437 }
4438 }
4439 else {
John Wiegley01296292011-04-08 18:41:53 +00004440 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004441 << CondTy;
4442 return QualType();
4443 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004444 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004445
Chris Lattnere2949f42008-01-06 22:42:25 +00004446 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004447 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004448 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004449
Nate Begemanabb5a732010-09-20 22:41:17 +00004450 // OpenCL: If the condition is a vector, and both operands are scalar,
4451 // attempt to implicity convert them to the vector type to act like the
4452 // built in select.
4453 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4454 // Both operands should be of scalar type.
4455 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004456 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004457 << CondTy;
4458 return QualType();
4459 }
4460 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004461 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004462 << CondTy;
4463 return QualType();
4464 }
4465 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004466 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4467 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004468 }
4469
Chris Lattnere2949f42008-01-06 22:42:25 +00004470 // If both operands have arithmetic type, do the usual arithmetic conversions
4471 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004472 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4473 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004474 if (LHS.isInvalid() || RHS.isInvalid())
4475 return QualType();
4476 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004478
Chris Lattnere2949f42008-01-06 22:42:25 +00004479 // If both operands are the same structure or union type, the result is that
4480 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004481 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4482 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004483 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004484 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004485 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004486 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004487 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004488 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004489
Chris Lattnere2949f42008-01-06 22:42:25 +00004490 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004491 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004492 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4493 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004494 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4495 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004496 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004497 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4498 << LHS.get()->getSourceRange();
4499 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4500 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004501 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004502 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004503 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4504 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004505 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004506 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004507 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004508 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004509 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004510 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004511 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004512 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4513 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004514 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004515 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004516
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004517 // All objective-c pointer type analysis is done here.
4518 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4519 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004520 if (LHS.isInvalid() || RHS.isInvalid())
4521 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004522 if (!compositeType.isNull())
4523 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004524
4525
Steve Naroff05efa972009-07-01 14:36:47 +00004526 // Handle block pointer types.
4527 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4528 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4529 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4530 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004531 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4532 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004533 return destType;
4534 }
4535 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004536 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004537 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004538 }
Steve Naroff05efa972009-07-01 14:36:47 +00004539 // We have 2 block pointer types.
4540 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4541 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004542 return LHSTy;
4543 }
Steve Naroff05efa972009-07-01 14:36:47 +00004544 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004545 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4546 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004547
Steve Naroff05efa972009-07-01 14:36:47 +00004548 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4549 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004550 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004551 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004552 // In this situation, we assume void* type. No especially good
4553 // reason, but this is what gcc does, and we do have to pick
4554 // to get a consistent AST.
4555 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004556 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4557 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004558 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004559 }
Steve Naroff05efa972009-07-01 14:36:47 +00004560 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004561 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4562 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004563 return LHSTy;
4564 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004565
Steve Naroff05efa972009-07-01 14:36:47 +00004566 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4567 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4568 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004569 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4570 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004571
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)
John McCall8ccfcb52009-09-24 19:53:00 +00004575 QualType destPointee
4576 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004577 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004578 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004579 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004580 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004581 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004582 return destType;
4583 }
4584 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004585 QualType destPointee
4586 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004587 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004588 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004589 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004590 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004591 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004592 return destType;
4593 }
4594
4595 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4596 // Two identical pointer types are always compatible.
4597 return LHSTy;
4598 }
4599 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4600 rhptee.getUnqualifiedType())) {
4601 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004602 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004603 // In this situation, we assume void* type. No especially good
4604 // reason, but this is what gcc does, and we do have to pick
4605 // to get a consistent AST.
4606 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004607 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4608 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004609 return incompatTy;
4610 }
4611 // The pointer types are compatible.
4612 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4613 // differently qualified versions of compatible types, the result type is
4614 // a pointer to an appropriately qualified version of the *composite*
4615 // type.
4616 // FIXME: Need to calculate the composite type.
4617 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004618 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4619 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004620 return LHSTy;
4621 }
Mike Stump11289f42009-09-09 15:08:12 +00004622
John McCalle84af4e2010-11-13 01:35:44 +00004623 // GCC compatibility: soften pointer/integer mismatch. Note that
4624 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004625 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4626 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004627 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4628 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004629 return RHSTy;
4630 }
4631 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4632 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004633 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4634 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004635 return LHSTy;
4636 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004637
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004638 // Emit a better diagnostic if one of the expressions is a null pointer
4639 // constant and the other is not a pointer type. In this case, the user most
4640 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004641 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004642 return QualType();
4643
Chris Lattnere2949f42008-01-06 22:42:25 +00004644 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004645 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004646 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004647 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004648}
4649
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004650/// FindCompositeObjCPointerType - Helper method to find composite type of
4651/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004652QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004653 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004654 QualType LHSTy = LHS.get()->getType();
4655 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004656
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004657 // Handle things like Class and struct objc_class*. Here we case the result
4658 // to the pseudo-builtin, because that will be implicitly cast back to the
4659 // redefinition type if an attempt is made to access its fields.
4660 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004661 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004662 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004663 return LHSTy;
4664 }
4665 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004666 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004667 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004668 return RHSTy;
4669 }
4670 // And the same for struct objc_object* / id
4671 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004672 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004673 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004674 return LHSTy;
4675 }
4676 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004677 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004678 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004679 return RHSTy;
4680 }
4681 // And the same for struct objc_selector* / SEL
4682 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004683 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004684 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004685 return LHSTy;
4686 }
4687 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004688 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004689 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004690 return RHSTy;
4691 }
4692 // Check constraints for Objective-C object pointers types.
4693 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004694
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004695 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4696 // Two identical object pointer types are always compatible.
4697 return LHSTy;
4698 }
4699 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4700 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4701 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004702
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004703 // If both operands are interfaces and either operand can be
4704 // assigned to the other, use that type as the composite
4705 // type. This allows
4706 // xxx ? (A*) a : (B*) b
4707 // where B is a subclass of A.
4708 //
4709 // Additionally, as for assignment, if either type is 'id'
4710 // allow silent coercion. Finally, if the types are
4711 // incompatible then make sure to use 'id' as the composite
4712 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004714 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4715 // It could return the composite type.
4716 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4717 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4718 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4719 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4720 } else if ((LHSTy->isObjCQualifiedIdType() ||
4721 RHSTy->isObjCQualifiedIdType()) &&
4722 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4723 // Need to handle "id<xx>" explicitly.
4724 // GCC allows qualified id and any Objective-C type to devolve to
4725 // id. Currently localizing to here until clear this should be
4726 // part of ObjCQualifiedIdTypesAreCompatible.
4727 compositeType = Context.getObjCIdType();
4728 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4729 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004730 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004731 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4732 ;
4733 else {
4734 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4735 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004737 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004738 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4739 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004740 return incompatTy;
4741 }
4742 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004743 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4744 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004745 return compositeType;
4746 }
4747 // Check Objective-C object pointer types and 'void *'
4748 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4749 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4750 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4751 QualType destPointee
4752 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4753 QualType destType = Context.getPointerType(destPointee);
4754 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004755 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004756 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004757 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004758 return destType;
4759 }
4760 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4761 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4762 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4763 QualType destPointee
4764 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4765 QualType destType = Context.getPointerType(destPointee);
4766 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004767 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004768 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004769 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004770 return destType;
4771 }
4772 return QualType();
4773}
4774
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004775/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004776/// ParenRange in parentheses.
4777static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004778 const PartialDiagnostic &Note,
4779 SourceRange ParenRange) {
4780 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4781 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4782 EndLoc.isValid()) {
4783 Self.Diag(Loc, Note)
4784 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4785 << FixItHint::CreateInsertion(EndLoc, ")");
4786 } else {
4787 // We can't display the parentheses, so just show the bare note.
4788 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004789 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004790}
4791
4792static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4793 return Opc >= BO_Mul && Opc <= BO_Shr;
4794}
4795
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004796/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4797/// expression, either using a built-in or overloaded operator,
4798/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4799static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4800 Expr **RHS) {
4801 E = E->IgnoreParenImpCasts();
4802 E = E->IgnoreConversionOperator();
4803 E = E->IgnoreParenImpCasts();
4804
4805 // Built-in binary operator.
4806 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4807 if (IsArithmeticOp(OP->getOpcode())) {
4808 *Opcode = OP->getOpcode();
4809 *RHS = OP->getRHS();
4810 return true;
4811 }
4812 }
4813
4814 // Overloaded operator.
4815 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4816 if (Call->getNumArgs() != 2)
4817 return false;
4818
4819 // Make sure this is really a binary operator that is safe to pass into
4820 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4821 OverloadedOperatorKind OO = Call->getOperator();
4822 if (OO < OO_Plus || OO > OO_Arrow)
4823 return false;
4824
4825 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4826 if (IsArithmeticOp(OpKind)) {
4827 *Opcode = OpKind;
4828 *RHS = Call->getArg(1);
4829 return true;
4830 }
4831 }
4832
4833 return false;
4834}
4835
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004836static bool IsLogicOp(BinaryOperatorKind Opc) {
4837 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4838}
4839
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004840/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4841/// or is a logical expression such as (x==y) which has int type, but is
4842/// commonly interpreted as boolean.
4843static bool ExprLooksBoolean(Expr *E) {
4844 E = E->IgnoreParenImpCasts();
4845
4846 if (E->getType()->isBooleanType())
4847 return true;
4848 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4849 return IsLogicOp(OP->getOpcode());
4850 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4851 return OP->getOpcode() == UO_LNot;
4852
4853 return false;
4854}
4855
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004856/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4857/// and binary operator are mixed in a way that suggests the programmer assumed
4858/// the conditional operator has higher precedence, for example:
4859/// "int x = a + someBinaryCondition ? 1 : 2".
4860static void DiagnoseConditionalPrecedence(Sema &Self,
4861 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004862 Expr *Condition,
4863 Expr *LHS,
4864 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004865 BinaryOperatorKind CondOpcode;
4866 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004867
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004868 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004869 return;
4870 if (!ExprLooksBoolean(CondRHS))
4871 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004872
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004873 // The condition is an arithmetic binary expression, with a right-
4874 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004875
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004876 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004877 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004878 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004879
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004880 SuggestParentheses(Self, OpLoc,
4881 Self.PDiag(diag::note_precedence_conditional_silence)
4882 << BinaryOperator::getOpcodeStr(CondOpcode),
4883 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004884
4885 SuggestParentheses(Self, OpLoc,
4886 Self.PDiag(diag::note_precedence_conditional_first),
4887 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004888}
4889
Steve Naroff83895f72007-09-16 03:34:24 +00004890/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004891/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004892ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004893 SourceLocation ColonLoc,
4894 Expr *CondExpr, Expr *LHSExpr,
4895 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004896 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4897 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004898 OpaqueValueExpr *opaqueValue = 0;
4899 Expr *commonExpr = 0;
4900 if (LHSExpr == 0) {
4901 commonExpr = CondExpr;
4902
4903 // We usually want to apply unary conversions *before* saving, except
4904 // in the special case of a C++ l-value conditional.
4905 if (!(getLangOptions().CPlusPlus
4906 && !commonExpr->isTypeDependent()
4907 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4908 && commonExpr->isGLValue()
4909 && commonExpr->isOrdinaryOrBitFieldObject()
4910 && RHSExpr->isOrdinaryOrBitFieldObject()
4911 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004912 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4913 if (commonRes.isInvalid())
4914 return ExprError();
4915 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004916 }
4917
4918 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4919 commonExpr->getType(),
4920 commonExpr->getValueKind(),
4921 commonExpr->getObjectKind());
4922 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004923 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004924
John McCall7decc9e2010-11-18 06:31:45 +00004925 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004926 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004927 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4928 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004929 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004930 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4931 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004932 return ExprError();
4933
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004934 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4935 RHS.get());
4936
John McCallc07a0c72011-02-17 10:25:35 +00004937 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004938 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4939 LHS.take(), ColonLoc,
4940 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004941
4942 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004943 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4944 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004945}
4946
John McCallaba90822011-01-31 23:13:11 +00004947// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004948// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004949// routine is it effectively iqnores the qualifiers on the top level pointee.
4950// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4951// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004952static Sema::AssignConvertType
4953checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4954 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4955 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004956
Steve Naroff1f4d7272007-05-11 04:00:31 +00004957 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004958 const Type *lhptee, *rhptee;
4959 Qualifiers lhq, rhq;
4960 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4961 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004962
John McCallaba90822011-01-31 23:13:11 +00004963 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004964
4965 // C99 6.5.16.1p1: This following citation is common to constraints
4966 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4967 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004968 Qualifiers lq;
4969
John McCall31168b02011-06-15 23:02:42 +00004970 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4971 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4972 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4973 // Ignore lifetime for further calculation.
4974 lhq.removeObjCLifetime();
4975 rhq.removeObjCLifetime();
4976 }
4977
John McCall4fff8f62011-02-01 00:10:29 +00004978 if (!lhq.compatiblyIncludes(rhq)) {
4979 // Treat address-space mismatches as fatal. TODO: address subspaces
4980 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4981 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4982
John McCall31168b02011-06-15 23:02:42 +00004983 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004984 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004985 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4986 .compatiblyIncludes(
4987 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004988 && (lhptee->isVoidType() || rhptee->isVoidType()))
4989 ; // keep old
4990
John McCall31168b02011-06-15 23:02:42 +00004991 // Treat lifetime mismatches as fatal.
4992 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4993 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4994
John McCall4fff8f62011-02-01 00:10:29 +00004995 // For GCC compatibility, other qualifier mismatches are treated
4996 // as still compatible in C.
4997 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4998 }
Steve Naroff3f597292007-05-11 22:18:03 +00004999
Mike Stump4e1f26a2009-02-19 03:04:26 +00005000 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5001 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005002 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005003 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005004 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005005 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005006
Chris Lattner0a788432008-01-03 22:56:36 +00005007 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005008 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005009 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005010 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005011
Chris Lattner0a788432008-01-03 22:56:36 +00005012 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005013 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005014 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005015
5016 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005017 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005018 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005019 }
John McCall4fff8f62011-02-01 00:10:29 +00005020
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005022 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005023 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5024 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005025 // Check if the pointee types are compatible ignoring the sign.
5026 // We explicitly check for char so that we catch "char" vs
5027 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005028 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005029 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005030 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005031 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005032
Chris Lattnerec3a1562009-10-17 20:33:28 +00005033 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005034 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005035 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005036 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005037
John McCall4fff8f62011-02-01 00:10:29 +00005038 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005039 // Types are compatible ignoring the sign. Qualifier incompatibility
5040 // takes priority over sign incompatibility because the sign
5041 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005042 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005043 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005044
John McCallaba90822011-01-31 23:13:11 +00005045 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005046 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005047
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005048 // If we are a multi-level pointer, it's possible that our issue is simply
5049 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5050 // the eventual target type is the same and the pointers have the same
5051 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005052 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005053 do {
John McCall4fff8f62011-02-01 00:10:29 +00005054 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5055 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005056 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005057
John McCall4fff8f62011-02-01 00:10:29 +00005058 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005059 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005060 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005061
Eli Friedman80160bd2009-03-22 23:59:44 +00005062 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005063 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005064 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005065 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005066}
5067
John McCallaba90822011-01-31 23:13:11 +00005068/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005069/// block pointer types are compatible or whether a block and normal pointer
5070/// are compatible. It is more restrict than comparing two function pointer
5071// types.
John McCallaba90822011-01-31 23:13:11 +00005072static Sema::AssignConvertType
5073checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5074 QualType rhsType) {
5075 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5076 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5077
Steve Naroff081c7422008-09-04 15:10:53 +00005078 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005079
Steve Naroff081c7422008-09-04 15:10:53 +00005080 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005081 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5082 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005083
John McCallaba90822011-01-31 23:13:11 +00005084 // In C++, the types have to match exactly.
5085 if (S.getLangOptions().CPlusPlus)
5086 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005087
John McCallaba90822011-01-31 23:13:11 +00005088 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005089
Steve Naroff081c7422008-09-04 15:10:53 +00005090 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005091 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5092 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005093
John McCallaba90822011-01-31 23:13:11 +00005094 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5095 return Sema::IncompatibleBlockPointer;
5096
Steve Naroff081c7422008-09-04 15:10:53 +00005097 return ConvTy;
5098}
5099
John McCallaba90822011-01-31 23:13:11 +00005100/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005101/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005102static Sema::AssignConvertType
5103checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5104 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5105 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5106
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005107 if (lhsType->isObjCBuiltinType()) {
5108 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005109 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5110 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005111 return Sema::IncompatiblePointer;
5112 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005113 }
5114 if (rhsType->isObjCBuiltinType()) {
5115 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005116 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5117 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005118 return Sema::IncompatiblePointer;
5119 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005120 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005121 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005122 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005123 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005124 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005125
John McCallaba90822011-01-31 23:13:11 +00005126 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5127 return Sema::CompatiblePointerDiscardsQualifiers;
5128
5129 if (S.Context.typesAreCompatible(lhsType, rhsType))
5130 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005131 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005132 return Sema::IncompatibleObjCQualifiedId;
5133 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005134}
5135
John McCall29600e12010-11-16 02:32:08 +00005136Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005137Sema::CheckAssignmentConstraints(SourceLocation Loc,
5138 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005139 // Fake up an opaque expression. We don't actually care about what
5140 // cast operations are required, so if CheckAssignmentConstraints
5141 // adds casts to this they'll be wasted, but fortunately that doesn't
5142 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005143 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005144 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005145 CastKind K = CK_Invalid;
5146
5147 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5148}
5149
Mike Stump4e1f26a2009-02-19 03:04:26 +00005150/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5151/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005152/// pointers. Here are some objectionable examples that GCC considers warnings:
5153///
5154/// int a, *pint;
5155/// short *pshort;
5156/// struct foo *pfoo;
5157///
5158/// pint = pshort; // warning: assignment from incompatible pointer type
5159/// a = pint; // warning: assignment makes integer from pointer without a cast
5160/// pint = a; // warning: assignment makes pointer from integer without a cast
5161/// pint = pfoo; // warning: assignment from incompatible pointer type
5162///
5163/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005164/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005165///
John McCall8cb679e2010-11-15 09:13:47 +00005166/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005167Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005168Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005169 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005170 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005171 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005172
Chris Lattnera52c2f22008-01-04 23:18:45 +00005173 // Get canonical types. We're not formatting these types, just comparing
5174 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005175 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5176 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005177
John McCalle5255932011-01-31 22:28:28 +00005178 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005179 if (lhsType == rhsType) {
5180 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005181 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005182 }
5183
Douglas Gregor6b754842008-10-28 00:22:11 +00005184 // If the left-hand side is a reference type, then we are in a
5185 // (rare!) case where we've allowed the use of references in C,
5186 // e.g., as a parameter type in a built-in function. In this case,
5187 // just make sure that the type referenced is compatible with the
5188 // right-hand side type. The caller is responsible for adjusting
5189 // lhsType so that the resulting expression does not have reference
5190 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005191 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005192 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5193 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005194 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005195 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005196 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005197 }
John McCalle5255932011-01-31 22:28:28 +00005198
Nate Begemanbd956c42009-06-28 02:36:38 +00005199 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5200 // to the same ExtVector type.
5201 if (lhsType->isExtVectorType()) {
5202 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005203 return Incompatible;
5204 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005205 // CK_VectorSplat does T -> vector T, so first cast to the
5206 // element type.
5207 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5208 if (elType != rhsType) {
5209 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005210 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005211 }
5212 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005213 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005214 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005215 }
Mike Stump11289f42009-09-09 15:08:12 +00005216
John McCalle5255932011-01-31 22:28:28 +00005217 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005218 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005219 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005220 // Allow assignments of an AltiVec vector type to an equivalent GCC
5221 // vector type and vice versa
5222 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5223 Kind = CK_BitCast;
5224 return Compatible;
5225 }
5226
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005227 // If we are allowing lax vector conversions, and LHS and RHS are both
5228 // vectors, the total size only needs to be the same. This is a bitcast;
5229 // no bits are changed but the result type is different.
5230 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005231 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005232 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005233 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005234 }
Chris Lattner881a2122008-01-04 23:32:24 +00005235 }
5236 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005237 }
Eli Friedman3360d892008-05-30 18:07:22 +00005238
John McCalle5255932011-01-31 22:28:28 +00005239 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005240 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005241 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005242 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005243 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005244 }
Eli Friedman3360d892008-05-30 18:07:22 +00005245
John McCalle5255932011-01-31 22:28:28 +00005246 // Conversions to normal pointers.
5247 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5248 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005249 if (isa<PointerType>(rhsType)) {
5250 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005251 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005252 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005253
John McCalle5255932011-01-31 22:28:28 +00005254 // int -> T*
5255 if (rhsType->isIntegerType()) {
5256 Kind = CK_IntegralToPointer; // FIXME: null?
5257 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005258 }
John McCalle5255932011-01-31 22:28:28 +00005259
5260 // C pointers are not compatible with ObjC object pointers,
5261 // with two exceptions:
5262 if (isa<ObjCObjectPointerType>(rhsType)) {
5263 // - conversions to void*
5264 if (lhsPointer->getPointeeType()->isVoidType()) {
5265 Kind = CK_AnyPointerToObjCPointerCast;
5266 return Compatible;
5267 }
5268
5269 // - conversions from 'Class' to the redefinition type
5270 if (rhsType->isObjCClassType() &&
5271 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005272 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005273 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005274 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005275
John McCalle5255932011-01-31 22:28:28 +00005276 Kind = CK_BitCast;
5277 return IncompatiblePointer;
5278 }
5279
5280 // U^ -> void*
5281 if (rhsType->getAs<BlockPointerType>()) {
5282 if (lhsPointer->getPointeeType()->isVoidType()) {
5283 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005284 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005285 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005286 }
John McCalle5255932011-01-31 22:28:28 +00005287
Steve Naroff081c7422008-09-04 15:10:53 +00005288 return Incompatible;
5289 }
5290
John McCalle5255932011-01-31 22:28:28 +00005291 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005292 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005293 // U^ -> T^
5294 if (rhsType->isBlockPointerType()) {
5295 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005296 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005297 }
5298
5299 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005300 if (rhsType->isIntegerType()) {
5301 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005302 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005303 }
5304
John McCalle5255932011-01-31 22:28:28 +00005305 // id -> T^
5306 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5307 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005308 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005309 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005310
John McCalle5255932011-01-31 22:28:28 +00005311 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005312 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005313 if (RHSPT->getPointeeType()->isVoidType()) {
5314 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005315 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005316 }
John McCall8cb679e2010-11-15 09:13:47 +00005317
Chris Lattnera52c2f22008-01-04 23:18:45 +00005318 return Incompatible;
5319 }
5320
John McCalle5255932011-01-31 22:28:28 +00005321 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005322 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005323 // A* -> B*
5324 if (rhsType->isObjCObjectPointerType()) {
5325 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005326 Sema::AssignConvertType result =
5327 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5328 if (getLangOptions().ObjCAutoRefCount &&
5329 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005330 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5331 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005332 return result;
John McCalle5255932011-01-31 22:28:28 +00005333 }
5334
5335 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005336 if (rhsType->isIntegerType()) {
5337 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005338 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005339 }
5340
John McCalle5255932011-01-31 22:28:28 +00005341 // In general, C pointers are not compatible with ObjC object pointers,
5342 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005343 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005344 // - conversions from 'void*'
5345 if (rhsType->isVoidPointerType()) {
5346 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005347 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005348 }
5349
5350 // - conversions to 'Class' from its redefinition type
5351 if (lhsType->isObjCClassType() &&
5352 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5353 Kind = CK_BitCast;
5354 return Compatible;
5355 }
5356
5357 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005358 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005359 }
John McCalle5255932011-01-31 22:28:28 +00005360
5361 // T^ -> A*
5362 if (rhsType->isBlockPointerType()) {
5363 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005364 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005365 }
5366
Steve Naroff7cae42b2009-07-10 23:34:53 +00005367 return Incompatible;
5368 }
John McCalle5255932011-01-31 22:28:28 +00005369
5370 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005371 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005372 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005373 if (lhsType == Context.BoolTy) {
5374 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005375 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005376 }
Eli Friedman3360d892008-05-30 18:07:22 +00005377
John McCalle5255932011-01-31 22:28:28 +00005378 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005379 if (lhsType->isIntegerType()) {
5380 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005381 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005382 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005383
Chris Lattnera52c2f22008-01-04 23:18:45 +00005384 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005385 }
John McCalle5255932011-01-31 22:28:28 +00005386
5387 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005388 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005389 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005390 if (lhsType == Context.BoolTy) {
5391 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005392 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005393 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005394
John McCalle5255932011-01-31 22:28:28 +00005395 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005396 if (lhsType->isIntegerType()) {
5397 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005398 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005399 }
5400
Steve Naroff7cae42b2009-07-10 23:34:53 +00005401 return Incompatible;
5402 }
Eli Friedman3360d892008-05-30 18:07:22 +00005403
John McCalle5255932011-01-31 22:28:28 +00005404 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005405 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005406 if (Context.typesAreCompatible(lhsType, rhsType)) {
5407 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005408 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005409 }
Bill Wendling216423b2007-05-30 06:30:29 +00005410 }
John McCalle5255932011-01-31 22:28:28 +00005411
Steve Naroff98cf3e92007-06-06 18:38:38 +00005412 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005413}
5414
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005415/// \brief Constructs a transparent union from an expression that is
5416/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005417static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005418 QualType UnionType, FieldDecl *Field) {
5419 // Build an initializer list that designates the appropriate member
5420 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005421 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005422 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005423 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005424 SourceLocation());
5425 Initializer->setType(UnionType);
5426 Initializer->setInitializedFieldInUnion(Field);
5427
5428 // Build a compound literal constructing a value of the transparent
5429 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005430 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005431 EResult = S.Owned(
5432 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5433 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005434}
5435
5436Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005437Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5438 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005439
Mike Stump11289f42009-09-09 15:08:12 +00005440 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005441 // transparent_union GCC extension.
5442 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005443 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005444 return Incompatible;
5445
5446 // The field to initialize within the transparent union.
5447 RecordDecl *UD = UT->getDecl();
5448 FieldDecl *InitField = 0;
5449 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005450 for (RecordDecl::field_iterator it = UD->field_begin(),
5451 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005452 it != itend; ++it) {
5453 if (it->getType()->isPointerType()) {
5454 // If the transparent union contains a pointer type, we allow:
5455 // 1) void pointer
5456 // 2) null pointer constant
5457 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005458 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005459 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005460 InitField = *it;
5461 break;
5462 }
Mike Stump11289f42009-09-09 15:08:12 +00005463
John Wiegley01296292011-04-08 18:41:53 +00005464 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005465 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005466 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005467 InitField = *it;
5468 break;
5469 }
5470 }
5471
John McCall8cb679e2010-11-15 09:13:47 +00005472 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005473 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005474 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005475 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005476 InitField = *it;
5477 break;
5478 }
5479 }
5480
5481 if (!InitField)
5482 return Incompatible;
5483
John Wiegley01296292011-04-08 18:41:53 +00005484 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005485 return Compatible;
5486}
5487
Chris Lattner9bad62c2008-01-04 18:04:52 +00005488Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005489Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005490 if (getLangOptions().CPlusPlus) {
5491 if (!lhsType->isRecordType()) {
5492 // C++ 5.17p3: If the left operand is not of class type, the
5493 // expression is implicitly converted (C++ 4) to the
5494 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005495 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5496 lhsType.getUnqualifiedType(),
5497 AA_Assigning);
5498 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005499 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005500 Sema::AssignConvertType result = Compatible;
5501 if (getLangOptions().ObjCAutoRefCount &&
5502 !CheckObjCARCUnavailableWeakConversion(lhsType, rExpr.get()->getType()))
5503 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005504 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005505 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005506 }
5507
5508 // FIXME: Currently, we fall through and treat C++ classes like C
5509 // structures.
John McCall34376a62010-12-04 03:47:34 +00005510 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005511
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005512 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5513 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005514 if ((lhsType->isPointerType() ||
5515 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005516 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005517 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005518 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005519 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005520 return Compatible;
5521 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005522
Chris Lattnere6dcd502007-10-16 02:55:40 +00005523 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005524 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005525 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005526 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005527 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005528 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005529 if (!lhsType->isReferenceType()) {
5530 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5531 if (rExpr.isInvalid())
5532 return Incompatible;
5533 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005534
John McCall8cb679e2010-11-15 09:13:47 +00005535 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005536 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005537 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005538
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005539 // C99 6.5.16.1p2: The value of the right operand is converted to the
5540 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005541 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5542 // so that we can use references in built-in functions even in C.
5543 // The getNonReferenceType() call makes sure that the resulting expression
5544 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005545 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5546 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005547 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005548}
5549
John Wiegley01296292011-04-08 18:41:53 +00005550QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005551 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005552 << lex.get()->getType() << rex.get()->getType()
5553 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005554 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005555}
5556
Eli Friedman1408bc92011-06-23 18:10:35 +00005557QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5558 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005559 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005560 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005561 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005562 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005563 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005564 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005565
Nate Begeman191a6b12008-07-14 18:02:46 +00005566 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005567 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005568 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005569
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005570 // Handle the case of equivalent AltiVec and GCC vector types
5571 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5572 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005573 if (lhsType->isExtVectorType()) {
5574 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5575 return lhsType;
5576 }
5577
5578 if (!isCompAssign)
5579 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005580 return rhsType;
5581 }
5582
Eli Friedman1408bc92011-06-23 18:10:35 +00005583 if (getLangOptions().LaxVectorConversions &&
5584 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5585 // If we are allowing lax vector conversions, and LHS and RHS are both
5586 // vectors, the total size only needs to be the same. This is a
5587 // bitcast; no bits are changed but the result type is different.
5588 // FIXME: Should we really be allowing this?
5589 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5590 return lhsType;
5591 }
5592
Nate Begemanbd956c42009-06-28 02:36:38 +00005593 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5594 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5595 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005596 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005597 swapped = true;
5598 std::swap(rex, lex);
5599 std::swap(rhsType, lhsType);
5600 }
Mike Stump11289f42009-09-09 15:08:12 +00005601
Nate Begeman886448d2009-06-28 19:12:57 +00005602 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005603 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005604 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005605 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005606 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5607 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005608 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005609 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005610 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005611 if (swapped) std::swap(rex, lex);
5612 return lhsType;
5613 }
5614 }
5615 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5616 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005617 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5618 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005619 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005620 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005621 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005622 if (swapped) std::swap(rex, lex);
5623 return lhsType;
5624 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005625 }
5626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
Nate Begeman886448d2009-06-28 19:12:57 +00005628 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005629 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005630 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005631 << lex.get()->getType() << rex.get()->getType()
5632 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005633 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005634}
5635
Chris Lattnerfaa54172010-01-12 21:23:57 +00005636QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005637 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5638 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005639 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005640
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005641 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005642 if (lex.isInvalid() || rex.isInvalid())
5643 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005644
John Wiegley01296292011-04-08 18:41:53 +00005645 if (!lex.get()->getType()->isArithmeticType() ||
5646 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005647 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005648
Chris Lattnerfaa54172010-01-12 21:23:57 +00005649 // Check for division by zero.
5650 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005651 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5652 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5653 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005654
Chris Lattnerfaa54172010-01-12 21:23:57 +00005655 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005656}
5657
Chris Lattnerfaa54172010-01-12 21:23:57 +00005658QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005659 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5660 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5661 if (lex.get()->getType()->hasIntegerRepresentation() &&
5662 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005663 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005664 return InvalidOperands(Loc, lex, rex);
5665 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005666
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005667 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005668 if (lex.isInvalid() || rex.isInvalid())
5669 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005670
John Wiegley01296292011-04-08 18:41:53 +00005671 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005672 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005673
Chris Lattnerfaa54172010-01-12 21:23:57 +00005674 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005675 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5676 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5677 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005678
Chris Lattnerfaa54172010-01-12 21:23:57 +00005679 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005680}
5681
Chandler Carruthc9332212011-06-27 08:02:19 +00005682/// \brief Diagnose invalid arithmetic on two void pointers.
5683static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5684 Expr *LHS, Expr *RHS) {
5685 S.Diag(Loc, S.getLangOptions().CPlusPlus
5686 ? diag::err_typecheck_pointer_arith_void_type
5687 : diag::ext_gnu_void_ptr)
5688 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5689}
5690
5691/// \brief Diagnose invalid arithmetic on a void pointer.
5692static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5693 Expr *Pointer) {
5694 S.Diag(Loc, S.getLangOptions().CPlusPlus
5695 ? diag::err_typecheck_pointer_arith_void_type
5696 : diag::ext_gnu_void_ptr)
5697 << 0 /* one pointer */ << Pointer->getSourceRange();
5698}
5699
5700/// \brief Diagnose invalid arithmetic on two function pointers.
5701static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5702 Expr *LHS, Expr *RHS) {
5703 assert(LHS->getType()->isAnyPointerType());
5704 assert(RHS->getType()->isAnyPointerType());
5705 S.Diag(Loc, S.getLangOptions().CPlusPlus
5706 ? diag::err_typecheck_pointer_arith_function_type
5707 : diag::ext_gnu_ptr_func_arith)
5708 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5709 // We only show the second type if it differs from the first.
5710 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5711 RHS->getType())
5712 << RHS->getType()->getPointeeType()
5713 << LHS->getSourceRange() << RHS->getSourceRange();
5714}
5715
5716/// \brief Diagnose invalid arithmetic on a function pointer.
5717static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5718 Expr *Pointer) {
5719 assert(Pointer->getType()->isAnyPointerType());
5720 S.Diag(Loc, S.getLangOptions().CPlusPlus
5721 ? diag::err_typecheck_pointer_arith_function_type
5722 : diag::ext_gnu_ptr_func_arith)
5723 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5724 << 0 /* one pointer, so only one type */
5725 << Pointer->getSourceRange();
5726}
5727
5728/// \brief Check the validity of an arithmetic pointer operand.
5729///
5730/// If the operand has pointer type, this code will check for pointer types
5731/// which are invalid in arithmetic operations. These will be diagnosed
5732/// appropriately, including whether or not the use is supported as an
5733/// extension.
5734///
5735/// \returns True when the operand is valid to use (even if as an extension).
5736static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5737 Expr *Operand) {
5738 if (!Operand->getType()->isAnyPointerType()) return true;
5739
5740 QualType PointeeTy = Operand->getType()->getPointeeType();
5741 if (PointeeTy->isVoidType()) {
5742 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5743 return !S.getLangOptions().CPlusPlus;
5744 }
5745 if (PointeeTy->isFunctionType()) {
5746 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5747 return !S.getLangOptions().CPlusPlus;
5748 }
5749
5750 if ((Operand->getType()->isPointerType() &&
5751 !Operand->getType()->isDependentType()) ||
5752 Operand->getType()->isObjCObjectPointerType()) {
5753 QualType PointeeTy = Operand->getType()->getPointeeType();
5754 if (S.RequireCompleteType(
5755 Loc, PointeeTy,
5756 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5757 << PointeeTy << Operand->getSourceRange()))
5758 return false;
5759 }
5760
5761 return true;
5762}
5763
5764/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5765/// operands.
5766///
5767/// This routine will diagnose any invalid arithmetic on pointer operands much
5768/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5769/// for emitting a single diagnostic even for operations where both LHS and RHS
5770/// are (potentially problematic) pointers.
5771///
5772/// \returns True when the operand is valid to use (even if as an extension).
5773static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5774 Expr *LHS, Expr *RHS) {
5775 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5776 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5777 if (!isLHSPointer && !isRHSPointer) return true;
5778
5779 QualType LHSPointeeTy, RHSPointeeTy;
5780 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5781 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5782
5783 // Check for arithmetic on pointers to incomplete types.
5784 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5785 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5786 if (isLHSVoidPtr || isRHSVoidPtr) {
5787 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5788 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5789 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5790
5791 return !S.getLangOptions().CPlusPlus;
5792 }
5793
5794 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5795 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5796 if (isLHSFuncPtr || isRHSFuncPtr) {
5797 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5798 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5799 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5800
5801 return !S.getLangOptions().CPlusPlus;
5802 }
5803
5804 Expr *Operands[] = { LHS, RHS };
5805 for (unsigned i = 0; i < 2; ++i) {
5806 Expr *Operand = Operands[i];
5807 if ((Operand->getType()->isPointerType() &&
5808 !Operand->getType()->isDependentType()) ||
5809 Operand->getType()->isObjCObjectPointerType()) {
5810 QualType PointeeTy = Operand->getType()->getPointeeType();
5811 if (S.RequireCompleteType(
5812 Loc, PointeeTy,
5813 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5814 << PointeeTy << Operand->getSourceRange()))
5815 return false;
5816 }
5817 }
5818 return true;
5819}
5820
Chris Lattnerfaa54172010-01-12 21:23:57 +00005821QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005822 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5823 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005824 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005825 if (CompLHSTy) *CompLHSTy = compType;
5826 return compType;
5827 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005828
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005829 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005830 if (lex.isInvalid() || rex.isInvalid())
5831 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005832
Steve Naroffe4718892007-04-27 18:30:00 +00005833 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005834 if (lex.get()->getType()->isArithmeticType() &&
5835 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005836 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005837 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005838 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005839
Eli Friedman8e122982008-05-18 18:08:51 +00005840 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005841 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005842 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005843 std::swap(PExp, IExp);
5844
Steve Naroff6b712a72009-07-14 18:25:06 +00005845 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005846 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005847 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5848 return QualType();
5849
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005850 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005851
Chris Lattner12bdebb2009-04-24 23:50:08 +00005852 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005853 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005854 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5855 << PointeeTy << PExp->getSourceRange();
5856 return QualType();
5857 }
Mike Stump11289f42009-09-09 15:08:12 +00005858
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005859 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005860 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005861 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005862 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005863 if (LHSTy->isPromotableIntegerType())
5864 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005865 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005866 *CompLHSTy = LHSTy;
5867 }
Eli Friedman8e122982008-05-18 18:08:51 +00005868 return PExp->getType();
5869 }
5870 }
5871
Chris Lattner326f7572008-11-18 01:30:42 +00005872 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005873}
5874
Chris Lattner2a3569b2008-04-07 05:30:13 +00005875// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005876QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005877 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005878 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005879 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005880 if (CompLHSTy) *CompLHSTy = compType;
5881 return compType;
5882 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005883
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005884 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005885 if (lex.isInvalid() || rex.isInvalid())
5886 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005887
Chris Lattner4d62f422007-12-09 21:53:25 +00005888 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005889
Chris Lattner4d62f422007-12-09 21:53:25 +00005890 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005891 if (lex.get()->getType()->isArithmeticType() &&
5892 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005893 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005894 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005895 }
Mike Stump11289f42009-09-09 15:08:12 +00005896
Chris Lattner4d62f422007-12-09 21:53:25 +00005897 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005898 if (lex.get()->getType()->isAnyPointerType()) {
5899 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005900
Chris Lattner12bdebb2009-04-24 23:50:08 +00005901 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005902 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005903 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005904 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005905 return QualType();
5906 }
Mike Stump11289f42009-09-09 15:08:12 +00005907
Chris Lattner4d62f422007-12-09 21:53:25 +00005908 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005909 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005910 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5911 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005912
John Wiegley01296292011-04-08 18:41:53 +00005913 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5914 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005915 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005916
Chris Lattner4d62f422007-12-09 21:53:25 +00005917 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005918 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005919 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Eli Friedman168fe152009-05-16 13:54:38 +00005921 if (getLangOptions().CPlusPlus) {
5922 // Pointee types must be the same: C++ [expr.add]
5923 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5924 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005925 << lex.get()->getType() << rex.get()->getType()
5926 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005927 return QualType();
5928 }
5929 } else {
5930 // Pointee types must be compatible C99 6.5.6p3
5931 if (!Context.typesAreCompatible(
5932 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5933 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5934 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005935 << lex.get()->getType() << rex.get()->getType()
5936 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005937 return QualType();
5938 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005939 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005940
Chandler Carruthc9332212011-06-27 08:02:19 +00005941 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5942 lex.get(), rex.get()))
5943 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005944
John Wiegley01296292011-04-08 18:41:53 +00005945 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005946 return Context.getPointerDiffType();
5947 }
5948 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005949
Chris Lattner326f7572008-11-18 01:30:42 +00005950 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005951}
5952
Douglas Gregor0bf31402010-10-08 23:50:27 +00005953static bool isScopedEnumerationType(QualType T) {
5954 if (const EnumType *ET = dyn_cast<EnumType>(T))
5955 return ET->getDecl()->isScoped();
5956 return false;
5957}
5958
John Wiegley01296292011-04-08 18:41:53 +00005959static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005960 SourceLocation Loc, unsigned Opc,
5961 QualType LHSTy) {
5962 llvm::APSInt Right;
5963 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005964 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005965 return;
5966
5967 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005968 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005969 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005970 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005971 return;
5972 }
5973 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005974 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005975 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005976 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005977 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005978 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005979 return;
5980 }
5981 if (Opc != BO_Shl)
5982 return;
5983
5984 // When left shifting an ICE which is signed, we can check for overflow which
5985 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5986 // integers have defined behavior modulo one more than the maximum value
5987 // representable in the result type, so never warn for those.
5988 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005989 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005990 LHSTy->hasUnsignedIntegerRepresentation())
5991 return;
5992 llvm::APInt ResultBits =
5993 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5994 if (LeftBits.uge(ResultBits))
5995 return;
5996 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5997 Result = Result.shl(Right);
5998
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005999 // Print the bit representation of the signed integer as an unsigned
6000 // hexadecimal number.
6001 llvm::SmallString<40> HexResult;
6002 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6003
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006004 // If we are only missing a sign bit, this is less likely to result in actual
6005 // bugs -- if the result is cast back to an unsigned type, it will have the
6006 // expected value. Thus we place this behind a different warning that can be
6007 // turned off separately if needed.
6008 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006009 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6010 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006011 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006012 return;
6013 }
6014
6015 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006016 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006017 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006018}
6019
Chris Lattner2a3569b2008-04-07 05:30:13 +00006020// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00006021QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006022 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006023 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006024 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6025 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006026 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006027
Douglas Gregor0bf31402010-10-08 23:50:27 +00006028 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6029 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006030 if (isScopedEnumerationType(lex.get()->getType()) ||
6031 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006032 return InvalidOperands(Loc, lex, rex);
6033 }
6034
Nate Begemane46ee9a2009-10-25 02:26:48 +00006035 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00006036 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006037 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006038
Chris Lattner5c11c412007-12-12 05:47:28 +00006039 // Shifts don't perform usual arithmetic conversions, they just do integer
6040 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006041
John McCall57cdd882010-12-16 19:28:59 +00006042 // For the LHS, do usual unary conversions, but then reset them away
6043 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006044 ExprResult old_lex = lex;
6045 lex = UsualUnaryConversions(lex.take());
6046 if (lex.isInvalid())
6047 return QualType();
6048 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006049 if (isCompAssign) lex = old_lex;
6050
6051 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006052 rex = UsualUnaryConversions(rex.take());
6053 if (rex.isInvalid())
6054 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006055
Ryan Flynnf53fab82009-08-07 16:20:20 +00006056 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006057 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006058
Chris Lattner5c11c412007-12-12 05:47:28 +00006059 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006060 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006061}
6062
Chandler Carruth17773fc2010-07-10 12:30:03 +00006063static bool IsWithinTemplateSpecialization(Decl *D) {
6064 if (DeclContext *DC = D->getDeclContext()) {
6065 if (isa<ClassTemplateSpecializationDecl>(DC))
6066 return true;
6067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6068 return FD->isFunctionTemplateSpecialization();
6069 }
6070 return false;
6071}
6072
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006073// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00006074QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006075 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006076 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006077
Chris Lattner9a152e22009-12-05 05:40:13 +00006078 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006079 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006080 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006081
John Wiegley01296292011-04-08 18:41:53 +00006082 QualType lType = lex.get()->getType();
6083 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006084
John Wiegley01296292011-04-08 18:41:53 +00006085 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6086 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006087 QualType LHSStrippedType = LHSStripped->getType();
6088 QualType RHSStrippedType = RHSStripped->getType();
6089
Douglas Gregor1beec452011-03-12 01:48:56 +00006090
6091
Chandler Carruth712563b2011-02-17 08:37:06 +00006092 // Two different enums will raise a warning when compared.
6093 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6094 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6095 if (LHSEnumType->getDecl()->getIdentifier() &&
6096 RHSEnumType->getDecl()->getIdentifier() &&
6097 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6098 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6099 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006100 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006101 }
6102 }
6103 }
6104
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006105 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006106 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006107 !lex.get()->getLocStart().isMacroID() &&
6108 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006109 // For non-floating point types, check for self-comparisons of the form
6110 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6111 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006112 //
6113 // NOTE: Don't warn about comparison expressions resulting from macro
6114 // expansion. Also don't warn about comparisons which are only self
6115 // comparisons within a template specialization. The warnings should catch
6116 // obvious cases in the definition of the template anyways. The idea is to
6117 // warn when the typed comparison operator will always evaluate to the same
6118 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006119 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006120 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006121 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006122 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006123 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006124 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006125 << (Opc == BO_EQ
6126 || Opc == BO_LE
6127 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006128 } else if (lType->isArrayType() && rType->isArrayType() &&
6129 !DRL->getDecl()->getType()->isReferenceType() &&
6130 !DRR->getDecl()->getType()->isReferenceType()) {
6131 // what is it always going to eval to?
6132 char always_evals_to;
6133 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006134 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006135 always_evals_to = 0; // false
6136 break;
John McCalle3027922010-08-25 11:45:40 +00006137 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006138 always_evals_to = 1; // true
6139 break;
6140 default:
6141 // best we can say is 'a constant'
6142 always_evals_to = 2; // e.g. array1 <= array2
6143 break;
6144 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006145 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006146 << 1 // array
6147 << always_evals_to);
6148 }
6149 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006150 }
Mike Stump11289f42009-09-09 15:08:12 +00006151
Chris Lattner222b8bd2009-03-08 19:39:53 +00006152 if (isa<CastExpr>(LHSStripped))
6153 LHSStripped = LHSStripped->IgnoreParenCasts();
6154 if (isa<CastExpr>(RHSStripped))
6155 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Chris Lattner222b8bd2009-03-08 19:39:53 +00006157 // Warn about comparisons against a string constant (unless the other
6158 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006159 Expr *literalString = 0;
6160 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006161 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006162 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006163 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006164 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006165 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006166 } else if ((isa<StringLiteral>(RHSStripped) ||
6167 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006168 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006169 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006170 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006171 literalStringStripped = RHSStripped;
6172 }
6173
6174 if (literalString) {
6175 std::string resultComparison;
6176 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006177 case BO_LT: resultComparison = ") < 0"; break;
6178 case BO_GT: resultComparison = ") > 0"; break;
6179 case BO_LE: resultComparison = ") <= 0"; break;
6180 case BO_GE: resultComparison = ") >= 0"; break;
6181 case BO_EQ: resultComparison = ") == 0"; break;
6182 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006183 default: assert(false && "Invalid comparison operator");
6184 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006185
Ted Kremenek3427fac2011-02-23 01:52:04 +00006186 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006187 PDiag(diag::warn_stringcompare)
6188 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006189 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006190 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006191 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006192
Douglas Gregorec170db2010-06-08 19:50:34 +00006193 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006194 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006195 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006196 if (lex.isInvalid() || rex.isInvalid())
6197 return QualType();
6198 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006199 else {
John Wiegley01296292011-04-08 18:41:53 +00006200 lex = UsualUnaryConversions(lex.take());
6201 if (lex.isInvalid())
6202 return QualType();
6203
6204 rex = UsualUnaryConversions(rex.take());
6205 if (rex.isInvalid())
6206 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006207 }
6208
John Wiegley01296292011-04-08 18:41:53 +00006209 lType = lex.get()->getType();
6210 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006211
Douglas Gregorca63811b2008-11-19 03:25:36 +00006212 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006213 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006214
Chris Lattnerb620c342007-08-26 01:18:55 +00006215 if (isRelational) {
6216 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006217 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006218 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006219 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006220 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006221 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006222
Chris Lattnerb620c342007-08-26 01:18:55 +00006223 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006224 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006225 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006226
John Wiegley01296292011-04-08 18:41:53 +00006227 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006228 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006229 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006230 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006231
Douglas Gregorf267edd2010-06-15 21:38:40 +00006232 // All of the following pointer-related warnings are GCC extensions, except
6233 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006234 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006235 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006236 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006237 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006238 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006239
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006240 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006241 if (LCanPointeeTy == RCanPointeeTy)
6242 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006243 if (!isRelational &&
6244 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6245 // Valid unless comparison between non-null pointer and function pointer
6246 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006247 // In a SFINAE context, we treat this as a hard error to maintain
6248 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006249 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6250 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006251 Diag(Loc,
6252 isSFINAEContext()?
6253 diag::err_typecheck_comparison_of_fptr_to_void
6254 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006255 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006256
6257 if (isSFINAEContext())
6258 return QualType();
6259
John Wiegley01296292011-04-08 18:41:53 +00006260 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006261 return ResultTy;
6262 }
6263 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006264
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006265 // C++ [expr.rel]p2:
6266 // [...] Pointer conversions (4.10) and qualification
6267 // conversions (4.4) are performed on pointer operands (or on
6268 // a pointer operand and a null pointer constant) to bring
6269 // them to their composite pointer type. [...]
6270 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006271 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006272 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006273 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006274 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006275 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006276 if (T.isNull()) {
6277 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006278 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006279 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006280 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006281 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006282 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006283 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006284 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006285 }
6286
John Wiegley01296292011-04-08 18:41:53 +00006287 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6288 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006289 return ResultTy;
6290 }
Eli Friedman16c209612009-08-23 00:27:47 +00006291 // C99 6.5.9p2 and C99 6.5.8p2
6292 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6293 RCanPointeeTy.getUnqualifiedType())) {
6294 // Valid unless a relational comparison of function pointers
6295 if (isRelational && LCanPointeeTy->isFunctionType()) {
6296 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006297 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006298 }
6299 } else if (!isRelational &&
6300 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6301 // Valid unless comparison between non-null pointer and function pointer
6302 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6303 && !LHSIsNull && !RHSIsNull) {
6304 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006305 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006306 }
6307 } else {
6308 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006309 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006310 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006311 }
John McCall7684dde2011-03-11 04:25:25 +00006312 if (LCanPointeeTy != RCanPointeeTy) {
6313 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006314 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006315 else
John Wiegley01296292011-04-08 18:41:53 +00006316 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006317 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006318 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006319 }
Mike Stump11289f42009-09-09 15:08:12 +00006320
Sebastian Redl576fd422009-05-10 18:38:11 +00006321 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006322 // Comparison of nullptr_t with itself.
6323 if (lType->isNullPtrType() && rType->isNullPtrType())
6324 return ResultTy;
6325
Mike Stump11289f42009-09-09 15:08:12 +00006326 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006327 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006328 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006329 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006330 (!isRelational &&
6331 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006332 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006333 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006334 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006335 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006336 return ResultTy;
6337 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006338 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006339 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006340 (!isRelational &&
6341 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006342 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006343 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006344 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006345 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006346 return ResultTy;
6347 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006348
6349 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006350 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006351 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6352 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006353 // In addition, pointers to members can be compared, or a pointer to
6354 // member and a null pointer constant. Pointer to member conversions
6355 // (4.11) and qualification conversions (4.4) are performed to bring
6356 // them to a common type. If one operand is a null pointer constant,
6357 // the common type is the type of the other operand. Otherwise, the
6358 // common type is a pointer to member type similar (4.4) to the type
6359 // of one of the operands, with a cv-qualification signature (4.4)
6360 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006361 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006362 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006363 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006364 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006365 if (T.isNull()) {
6366 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006367 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006368 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006369 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006370 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006371 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006372 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006373 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006374 }
Mike Stump11289f42009-09-09 15:08:12 +00006375
John Wiegley01296292011-04-08 18:41:53 +00006376 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6377 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006378 return ResultTy;
6379 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006380
6381 // Handle scoped enumeration types specifically, since they don't promote
6382 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006383 if (lex.get()->getType()->isEnumeralType() &&
6384 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006385 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006386 }
Mike Stump11289f42009-09-09 15:08:12 +00006387
Steve Naroff081c7422008-09-04 15:10:53 +00006388 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006389 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006390 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6391 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006392
Steve Naroff081c7422008-09-04 15:10:53 +00006393 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006394 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006395 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006396 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006397 }
John Wiegley01296292011-04-08 18:41:53 +00006398 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006399 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006400 }
John Wiegley01296292011-04-08 18:41:53 +00006401
Steve Naroffe18f94c2008-09-28 01:11:11 +00006402 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006403 if (!isRelational
6404 && ((lType->isBlockPointerType() && rType->isPointerType())
6405 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006406 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006407 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006408 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006409 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006410 ->getPointeeType()->isVoidType())))
6411 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006412 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006413 }
John McCall7684dde2011-03-11 04:25:25 +00006414 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006415 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006416 else
John Wiegley01296292011-04-08 18:41:53 +00006417 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006418 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006419 }
Steve Naroff081c7422008-09-04 15:10:53 +00006420
John McCall7684dde2011-03-11 04:25:25 +00006421 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6422 const PointerType *LPT = lType->getAs<PointerType>();
6423 const PointerType *RPT = rType->getAs<PointerType>();
6424 if (LPT || RPT) {
6425 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6426 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006427
Steve Naroff753567f2008-11-17 19:49:16 +00006428 if (!LPtrToVoid && !RPtrToVoid &&
6429 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006430 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006431 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006432 }
John McCall7684dde2011-03-11 04:25:25 +00006433 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006434 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006435 else
John Wiegley01296292011-04-08 18:41:53 +00006436 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006437 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006438 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006439 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006440 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006441 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006442 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006443 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006444 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006445 else
John Wiegley01296292011-04-08 18:41:53 +00006446 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006447 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006448 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006449 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006450 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6451 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006452 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006453 bool isError = false;
6454 if ((LHSIsNull && lType->isIntegerType()) ||
6455 (RHSIsNull && rType->isIntegerType())) {
6456 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006457 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006458 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006459 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006460 else if (getLangOptions().CPlusPlus) {
6461 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6462 isError = true;
6463 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006464 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006465
Chris Lattnerd99bd522009-08-23 00:03:44 +00006466 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006467 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006468 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006469 if (isError)
6470 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006471 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006472
6473 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006474 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006475 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006476 else
John Wiegley01296292011-04-08 18:41:53 +00006477 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006478 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006479 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006480 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006481
Steve Naroff4b191572008-09-04 16:56:14 +00006482 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006483 if (!isRelational && RHSIsNull
6484 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006485 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006486 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006487 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006488 if (!isRelational && LHSIsNull
6489 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006490 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006491 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006492 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006493
Chris Lattner326f7572008-11-18 01:30:42 +00006494 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006495}
6496
Nate Begeman191a6b12008-07-14 18:02:46 +00006497/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006498/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006499/// like a scalar comparison, a vector comparison produces a vector of integer
6500/// types.
John Wiegley01296292011-04-08 18:41:53 +00006501QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006502 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006503 bool isRelational) {
6504 // Check to make sure we're operating on vectors of the same type and width,
6505 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006506 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006507 if (vType.isNull())
6508 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006509
John Wiegley01296292011-04-08 18:41:53 +00006510 QualType lType = lex.get()->getType();
6511 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Anton Yartsev530deb92011-03-27 15:36:07 +00006513 // If AltiVec, the comparison results in a numeric type, i.e.
6514 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006515 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006516 return Context.getLogicalOperationType();
6517
Nate Begeman191a6b12008-07-14 18:02:46 +00006518 // For non-floating point types, check for self-comparisons of the form
6519 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6520 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006521 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006522 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6523 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006524 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006525 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006526 PDiag(diag::warn_comparison_always)
6527 << 0 // self-
6528 << 2 // "a constant"
6529 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006530 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006531
Nate Begeman191a6b12008-07-14 18:02:46 +00006532 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006533 if (!isRelational && lType->hasFloatingRepresentation()) {
6534 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006535 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006536 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006537
Nate Begeman191a6b12008-07-14 18:02:46 +00006538 // Return the type for the comparison, which is the same as vector type for
6539 // integer vectors, or an integer type of identical size and number of
6540 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006541 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006542 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006543
John McCall9dd450b2009-09-21 23:43:11 +00006544 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006545 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006546 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006547 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006548 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006549 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6550
Mike Stump4e1f26a2009-02-19 03:04:26 +00006551 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006552 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006553 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6554}
6555
Steve Naroff218bc2b2007-05-04 21:54:46 +00006556inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006557 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6558 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6559 if (lex.get()->getType()->hasIntegerRepresentation() &&
6560 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006561 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006562
6563 return InvalidOperands(Loc, lex, rex);
6564 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006565
John Wiegley01296292011-04-08 18:41:53 +00006566 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6567 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6568 if (lexResult.isInvalid() || rexResult.isInvalid())
6569 return QualType();
6570 lex = lexResult.take();
6571 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006572
John Wiegley01296292011-04-08 18:41:53 +00006573 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6574 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006575 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006576 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006577}
6578
Steve Naroff218bc2b2007-05-04 21:54:46 +00006579inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006580 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006581
6582 // Diagnose cases where the user write a logical and/or but probably meant a
6583 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6584 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006585 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6586 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006587 // Don't warn in macros or template instantiations.
6588 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006589 // If the RHS can be constant folded, and if it constant folds to something
6590 // that isn't 0 or 1 (which indicate a potential logical operation that
6591 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006592 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006593 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006594 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6595 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6596 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6597 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6598 << rex.get()->getSourceRange()
6599 << (Opc == BO_LAnd ? "&&" : "||")
6600 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006601 }
6602 }
Chris Lattner8406c512010-07-13 19:41:32 +00006603
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006604 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006605 lex = UsualUnaryConversions(lex.take());
6606 if (lex.isInvalid())
6607 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006608
John Wiegley01296292011-04-08 18:41:53 +00006609 rex = UsualUnaryConversions(rex.take());
6610 if (rex.isInvalid())
6611 return QualType();
6612
6613 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006614 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006615
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006616 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006617 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006618
John McCall4a2429a2010-06-04 00:29:51 +00006619 // The following is safe because we only use this method for
6620 // non-overloadable operands.
6621
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006622 // C++ [expr.log.and]p1
6623 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006624 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006625 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6626 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006627 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006628 lex = move(lexRes);
6629
6630 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6631 if (rexRes.isInvalid())
6632 return InvalidOperands(Loc, lex, rex);
6633 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006634
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006635 // C++ [expr.log.and]p2
6636 // C++ [expr.log.or]p2
6637 // The result is a bool.
6638 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006639}
6640
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006641/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6642/// is a read-only property; return true if so. A readonly property expression
6643/// depends on various declarations and thus must be treated specially.
6644///
Mike Stump11289f42009-09-09 15:08:12 +00006645static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006646 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6647 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006648 if (PropExpr->isImplicitProperty()) return false;
6649
6650 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6651 QualType BaseType = PropExpr->isSuperReceiver() ?
6652 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006653 PropExpr->getBase()->getType();
6654
John McCallb7bd14f2010-12-02 01:19:52 +00006655 if (const ObjCObjectPointerType *OPT =
6656 BaseType->getAsObjCInterfacePointerType())
6657 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6658 if (S.isPropertyReadonly(PDecl, IFace))
6659 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006660 }
6661 return false;
6662}
6663
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006664static bool IsConstProperty(Expr *E, Sema &S) {
6665 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6666 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6667 if (PropExpr->isImplicitProperty()) return false;
6668
6669 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6670 QualType T = PDecl->getType();
6671 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006672 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006673 CanQualType CT = S.Context.getCanonicalType(T);
6674 return CT.isConstQualified();
6675 }
6676 return false;
6677}
6678
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006679static bool IsReadonlyMessage(Expr *E, Sema &S) {
6680 if (E->getStmtClass() != Expr::MemberExprClass)
6681 return false;
6682 const MemberExpr *ME = cast<MemberExpr>(E);
6683 NamedDecl *Member = ME->getMemberDecl();
6684 if (isa<FieldDecl>(Member)) {
6685 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6686 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6687 return false;
6688 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6689 }
6690 return false;
6691}
6692
Chris Lattner30bd3272008-11-18 01:22:49 +00006693/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6694/// emit an error and return true. If so, return false.
6695static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006696 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006697 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006698 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006699 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6700 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006701 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6702 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006703 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6704 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006705 if (IsLV == Expr::MLV_Valid)
6706 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006707
Chris Lattner30bd3272008-11-18 01:22:49 +00006708 unsigned Diag = 0;
6709 bool NeedType = false;
6710 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006711 case Expr::MLV_ConstQualified:
6712 Diag = diag::err_typecheck_assign_const;
6713
John McCalld4631322011-06-17 06:42:21 +00006714 // In ARC, use some specialized diagnostics for occasions where we
6715 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006716 if (S.getLangOptions().ObjCAutoRefCount) {
6717 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6718 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6719 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6720
John McCalld4631322011-06-17 06:42:21 +00006721 // Use the normal diagnostic if it's pseudo-__strong but the
6722 // user actually wrote 'const'.
6723 if (var->isARCPseudoStrong() &&
6724 (!var->getTypeSourceInfo() ||
6725 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6726 // There are two pseudo-strong cases:
6727 // - self
John McCall31168b02011-06-15 23:02:42 +00006728 ObjCMethodDecl *method = S.getCurMethodDecl();
6729 if (method && var == method->getSelfDecl())
6730 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006731
6732 // - fast enumeration variables
6733 else
John McCall31168b02011-06-15 23:02:42 +00006734 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006735
John McCall31168b02011-06-15 23:02:42 +00006736 SourceRange Assign;
6737 if (Loc != OrigLoc)
6738 Assign = SourceRange(OrigLoc, OrigLoc);
6739 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6740 // We need to preserve the AST regardless, so migration tool
6741 // can do its job.
6742 return false;
6743 }
6744 }
6745 }
6746
6747 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006748 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006749 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6750 NeedType = true;
6751 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006752 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006753 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6754 NeedType = true;
6755 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006756 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006757 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6758 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006759 case Expr::MLV_Valid:
6760 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006761 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006762 case Expr::MLV_MemberFunction:
6763 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006764 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6765 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006766 case Expr::MLV_IncompleteType:
6767 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006768 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006769 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006770 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006771 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006772 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6773 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006774 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006775 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6776 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006777 case Expr::MLV_ReadonlyProperty:
6778 Diag = diag::error_readonly_property_assignment;
6779 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006780 case Expr::MLV_NoSetterProperty:
6781 Diag = diag::error_nosetter_property_assignment;
6782 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006783 case Expr::MLV_InvalidMessageExpression:
6784 Diag = diag::error_readonly_message_assignment;
6785 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006786 case Expr::MLV_SubObjCPropertySetting:
6787 Diag = diag::error_no_subobject_property_setting;
6788 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006789 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006790
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006791 SourceRange Assign;
6792 if (Loc != OrigLoc)
6793 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006794 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006795 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006796 else
Mike Stump11289f42009-09-09 15:08:12 +00006797 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006798 return true;
6799}
6800
6801
6802
6803// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006804QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006805 SourceLocation Loc,
6806 QualType CompoundType) {
6807 // Verify that LHS is a modifiable lvalue, and emit error if not.
6808 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006809 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006810
6811 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006812 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006813 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006814 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006815 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006816 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006817 if (LHS->getObjectKind() == OK_ObjCProperty) {
6818 ExprResult LHSResult = Owned(LHS);
6819 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6820 if (LHSResult.isInvalid())
6821 return QualType();
6822 LHS = LHSResult.take();
6823 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006824 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006825 if (RHS.isInvalid())
6826 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006827 // Special case of NSObject attributes on c-style pointer types.
6828 if (ConvTy == IncompatiblePointer &&
6829 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006830 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006831 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006832 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006833 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006834
John McCall7decc9e2010-11-18 06:31:45 +00006835 if (ConvTy == Compatible &&
6836 getLangOptions().ObjCNonFragileABI &&
6837 LHSType->isObjCObjectType())
6838 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6839 << LHSType;
6840
Chris Lattnerea714382008-08-21 18:04:13 +00006841 // If the RHS is a unary plus or minus, check to see if they = and + are
6842 // right next to each other. If so, the user may have typo'd "x =+ 4"
6843 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006844 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006845 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6846 RHSCheck = ICE->getSubExpr();
6847 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006848 if ((UO->getOpcode() == UO_Plus ||
6849 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006850 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006851 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006852 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6853 // And there is a space or other character before the subexpr of the
6854 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006855 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6856 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006857 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006858 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006859 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006860 }
Chris Lattnerea714382008-08-21 18:04:13 +00006861 }
John McCall31168b02011-06-15 23:02:42 +00006862
6863 if (ConvTy == Compatible) {
6864 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6865 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006866 else if (getLangOptions().ObjCAutoRefCount)
6867 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006868 }
Chris Lattnerea714382008-08-21 18:04:13 +00006869 } else {
6870 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006871 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006872 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006873
Chris Lattner326f7572008-11-18 01:30:42 +00006874 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006875 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006876 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006877
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006878 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006879 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006880 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006881
Steve Naroff98cf3e92007-06-06 18:38:38 +00006882 // C99 6.5.16p3: The type of an assignment expression is the type of the
6883 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006884 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006885 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6886 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006887 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006888 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006889 return (getLangOptions().CPlusPlus
6890 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006891}
6892
Chris Lattner326f7572008-11-18 01:30:42 +00006893// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006894static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006895 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006896 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006897
John McCall3aef3d82011-04-10 19:13:55 +00006898 LHS = S.CheckPlaceholderExpr(LHS.take());
6899 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006900 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006901 return QualType();
6902
John McCall73d36182010-10-12 07:14:40 +00006903 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6904 // operands, but not unary promotions.
6905 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006906
John McCall34376a62010-12-04 03:47:34 +00006907 // So we treat the LHS as a ignored value, and in C++ we allow the
6908 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006909 LHS = S.IgnoredValueConversions(LHS.take());
6910 if (LHS.isInvalid())
6911 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006912
6913 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006914 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6915 if (RHS.isInvalid())
6916 return QualType();
6917 if (!RHS.get()->getType()->isVoidType())
6918 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006919 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006920
John Wiegley01296292011-04-08 18:41:53 +00006921 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006922}
6923
Steve Naroff7a5af782007-07-13 16:58:59 +00006924/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6925/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006926static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6927 ExprValueKind &VK,
6928 SourceLocation OpLoc,
6929 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006930 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006931 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006932
Chris Lattner6b0cf142008-11-21 07:05:48 +00006933 QualType ResType = Op->getType();
6934 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006935
John McCall4bc41ae2010-11-18 19:01:18 +00006936 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006937 // Decrement of bool is not allowed.
6938 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006939 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006940 return QualType();
6941 }
6942 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006943 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006944 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006945 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006946 } else if (ResType->isAnyPointerType()) {
6947 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006948
Chris Lattner6b0cf142008-11-21 07:05:48 +00006949 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006950 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006951 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006952
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006953 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006954 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6955 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006956 << PointeeTy << Op->getSourceRange();
6957 return QualType();
6958 }
Eli Friedman090addd2010-01-03 00:20:48 +00006959 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006960 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006961 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006962 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006963 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006964 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006965 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006966 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6967 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006968 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6969 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006970 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006971 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006972 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006973 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006974 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006975 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006976 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006977 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006978 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006979 // In C++, a prefix increment is the same type as the operand. Otherwise
6980 // (in C or with postfix), the increment is the unqualified type of the
6981 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006982 if (isPrefix && S.getLangOptions().CPlusPlus) {
6983 VK = VK_LValue;
6984 return ResType;
6985 } else {
6986 VK = VK_RValue;
6987 return ResType.getUnqualifiedType();
6988 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006989}
6990
John Wiegley01296292011-04-08 18:41:53 +00006991ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006992 assert(E->getValueKind() == VK_LValue &&
6993 E->getObjectKind() == OK_ObjCProperty);
6994 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6995
Douglas Gregor33823722011-06-11 01:09:30 +00006996 QualType T = E->getType();
6997 QualType ReceiverType;
6998 if (PRE->isObjectReceiver())
6999 ReceiverType = PRE->getBase()->getType();
7000 else if (PRE->isSuperReceiver())
7001 ReceiverType = PRE->getSuperReceiverType();
7002 else
7003 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7004
John McCall34376a62010-12-04 03:47:34 +00007005 ExprValueKind VK = VK_RValue;
7006 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007007 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007008 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007009 T = getMessageSendResultType(ReceiverType, GetterMethod,
7010 PRE->isClassReceiver(),
7011 PRE->isSuperReceiver());
7012 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007013 }
7014 else {
7015 Diag(PRE->getLocation(), diag::err_getter_not_found)
7016 << PRE->getBase()->getType();
7017 }
John McCall34376a62010-12-04 03:47:34 +00007018 }
Douglas Gregor33823722011-06-11 01:09:30 +00007019
7020 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007021 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007022
7023 ExprResult Result = MaybeBindToTemporary(E);
7024 if (!Result.isInvalid())
7025 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007026
7027 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007028}
7029
John Wiegley01296292011-04-08 18:41:53 +00007030void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
7031 assert(LHS.get()->getValueKind() == VK_LValue &&
7032 LHS.get()->getObjectKind() == OK_ObjCProperty);
7033 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007034
John McCall31168b02011-06-15 23:02:42 +00007035 bool Consumed = false;
7036
John Wiegley01296292011-04-08 18:41:53 +00007037 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007038 // If using property-dot syntax notation for assignment, and there is a
7039 // setter, RHS expression is being passed to the setter argument. So,
7040 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007041 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007042 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7043 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007044 Consumed = (getLangOptions().ObjCAutoRefCount &&
7045 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007046
7047 // Otherwise, if the getter returns an l-value, just call that.
7048 } else {
John Wiegley01296292011-04-08 18:41:53 +00007049 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007050 ExprValueKind VK = Expr::getValueKindForType(Result);
7051 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007052 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7053 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007054 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007055 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007056 }
John McCall31168b02011-06-15 23:02:42 +00007057 } else if (getLangOptions().ObjCAutoRefCount) {
7058 const ObjCMethodDecl *setter
7059 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7060 if (setter) {
7061 ObjCMethodDecl::param_iterator P = setter->param_begin();
7062 LHSTy = (*P)->getType();
7063 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7064 }
John McCall34376a62010-12-04 03:47:34 +00007065 }
7066
John McCall31168b02011-06-15 23:02:42 +00007067 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7068 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007069 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007070 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007071 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007072 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007073 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007074 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7075 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7076 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007077 }
7078}
7079
7080
Anders Carlsson806700f2008-02-01 07:15:58 +00007081/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007082/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007083/// where the declaration is needed for type checking. We only need to
7084/// handle cases when the expression references a function designator
7085/// or is an lvalue. Here are some examples:
7086/// - &(x) => x
7087/// - &*****f => f for f a function designator.
7088/// - &s.xx => s
7089/// - &s.zz[1].yy -> s, if zz is an array
7090/// - *(x + 1) -> x, if x is an array
7091/// - &"123"[2] -> 0
7092/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007093static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007094 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007095 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007096 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007097 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007098 // If this is an arrow operator, the address is an offset from
7099 // the base's value, so the object the base refers to is
7100 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007101 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007102 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007103 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007104 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007105 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007106 // FIXME: This code shouldn't be necessary! We should catch the implicit
7107 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007108 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7109 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7110 if (ICE->getSubExpr()->getType()->isArrayType())
7111 return getPrimaryDecl(ICE->getSubExpr());
7112 }
7113 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007114 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007115 case Stmt::UnaryOperatorClass: {
7116 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007117
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007118 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007119 case UO_Real:
7120 case UO_Imag:
7121 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007122 return getPrimaryDecl(UO->getSubExpr());
7123 default:
7124 return 0;
7125 }
7126 }
Steve Naroff47500512007-04-19 23:00:49 +00007127 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007128 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007129 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007130 // If the result of an implicit cast is an l-value, we care about
7131 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007132 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007133 default:
7134 return 0;
7135 }
7136}
7137
7138/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007139/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007140/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007141/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007142/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007143/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007144/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007145static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7146 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007147 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007148 return S.Context.DependentTy;
7149 if (OrigOp->getType() == S.Context.OverloadTy)
7150 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007151 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7152 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007153 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7154 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7155 << OrigOp->getSourceRange();
7156 return QualType();
7157 }
John McCall8d08b9b2010-08-27 09:08:28 +00007158
John McCall2979fe02011-04-12 00:42:48 +00007159 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007160
John McCall8d08b9b2010-08-27 09:08:28 +00007161 // Make sure to ignore parentheses in subsequent checks
7162 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007163
John McCall4bc41ae2010-11-18 19:01:18 +00007164 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007165 // Implement C99-only parts of addressof rules.
7166 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007167 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007168 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7169 // (assuming the deref expression is valid).
7170 return uOp->getSubExpr()->getType();
7171 }
7172 // Technically, there should be a check for array subscript
7173 // expressions here, but the result of one is always an lvalue anyway.
7174 }
John McCallf3a88602011-02-03 08:15:49 +00007175 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007176 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007177
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007178 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007179 bool sfinae = S.isSFINAEContext();
7180 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7181 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007182 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007183 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007184 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007185 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007186 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007187 } else if (lval == Expr::LV_MemberFunction) {
7188 // If it's an instance method, make a member pointer.
7189 // The expression must have exactly the form &A::foo.
7190
7191 // If the underlying expression isn't a decl ref, give up.
7192 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007193 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007194 << OrigOp->getSourceRange();
7195 return QualType();
7196 }
7197 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7198 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7199
7200 // The id-expression was parenthesized.
7201 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007202 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007203 << OrigOp->getSourceRange();
7204
7205 // The method was named without a qualifier.
7206 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007207 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007208 << op->getSourceRange();
7209 }
7210
John McCall4bc41ae2010-11-18 19:01:18 +00007211 return S.Context.getMemberPointerType(op->getType(),
7212 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007213 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007214 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007215 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007216 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007217 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007218 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007219 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007220 return QualType();
7221 }
John McCall086a4642010-11-24 05:12:34 +00007222 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007223 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007224 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007225 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007226 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007227 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007228 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007229 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007230 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007231 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007232 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007233 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007234 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007235 << "property expression" << op->getSourceRange();
7236 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007237 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007238 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007239 // with the register storage-class specifier.
7240 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007241 // in C++ it is not error to take address of a register
7242 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007243 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007244 !S.getLangOptions().CPlusPlus) {
7245 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007246 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007247 return QualType();
7248 }
John McCalld14a8642009-11-21 08:51:07 +00007249 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007250 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007251 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007252 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007253 // Could be a pointer to member, though, if there is an explicit
7254 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007255 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007256 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007257 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007258 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007259 S.Diag(OpLoc,
7260 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007261 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007262 return QualType();
7263 }
Mike Stump11289f42009-09-09 15:08:12 +00007264
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007265 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7266 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007267 return S.Context.getMemberPointerType(op->getType(),
7268 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007269 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007270 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007271 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007272 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007273 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007274
Eli Friedmance7f9002009-05-16 23:27:50 +00007275 if (lval == Expr::LV_IncompleteVoidType) {
7276 // Taking the address of a void variable is technically illegal, but we
7277 // allow it in cases which are otherwise valid.
7278 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007279 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007280 }
7281
Steve Naroff47500512007-04-19 23:00:49 +00007282 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007283 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007284 return S.Context.getObjCObjectPointerType(op->getType());
7285 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007286}
7287
Chris Lattner9156f1b2010-07-05 19:17:26 +00007288/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007289static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7290 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007291 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007292 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007293
John Wiegley01296292011-04-08 18:41:53 +00007294 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7295 if (ConvResult.isInvalid())
7296 return QualType();
7297 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007298 QualType OpTy = Op->getType();
7299 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007300
7301 if (isa<CXXReinterpretCastExpr>(Op)) {
7302 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7303 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7304 Op->getSourceRange());
7305 }
7306
Chris Lattner9156f1b2010-07-05 19:17:26 +00007307 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7308 // is an incomplete type or void. It would be possible to warn about
7309 // dereferencing a void pointer, but it's completely well-defined, and such a
7310 // warning is unlikely to catch any mistakes.
7311 if (const PointerType *PT = OpTy->getAs<PointerType>())
7312 Result = PT->getPointeeType();
7313 else if (const ObjCObjectPointerType *OPT =
7314 OpTy->getAs<ObjCObjectPointerType>())
7315 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007316 else {
John McCall3aef3d82011-04-10 19:13:55 +00007317 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007318 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007319 if (PR.take() != Op)
7320 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007321 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007322
Chris Lattner9156f1b2010-07-05 19:17:26 +00007323 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007324 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007325 << OpTy << Op->getSourceRange();
7326 return QualType();
7327 }
John McCall4bc41ae2010-11-18 19:01:18 +00007328
7329 // Dereferences are usually l-values...
7330 VK = VK_LValue;
7331
7332 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007333 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007334 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007335
7336 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007337}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007338
John McCalle3027922010-08-25 11:45:40 +00007339static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007340 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007341 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007342 switch (Kind) {
7343 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007344 case tok::periodstar: Opc = BO_PtrMemD; break;
7345 case tok::arrowstar: Opc = BO_PtrMemI; break;
7346 case tok::star: Opc = BO_Mul; break;
7347 case tok::slash: Opc = BO_Div; break;
7348 case tok::percent: Opc = BO_Rem; break;
7349 case tok::plus: Opc = BO_Add; break;
7350 case tok::minus: Opc = BO_Sub; break;
7351 case tok::lessless: Opc = BO_Shl; break;
7352 case tok::greatergreater: Opc = BO_Shr; break;
7353 case tok::lessequal: Opc = BO_LE; break;
7354 case tok::less: Opc = BO_LT; break;
7355 case tok::greaterequal: Opc = BO_GE; break;
7356 case tok::greater: Opc = BO_GT; break;
7357 case tok::exclaimequal: Opc = BO_NE; break;
7358 case tok::equalequal: Opc = BO_EQ; break;
7359 case tok::amp: Opc = BO_And; break;
7360 case tok::caret: Opc = BO_Xor; break;
7361 case tok::pipe: Opc = BO_Or; break;
7362 case tok::ampamp: Opc = BO_LAnd; break;
7363 case tok::pipepipe: Opc = BO_LOr; break;
7364 case tok::equal: Opc = BO_Assign; break;
7365 case tok::starequal: Opc = BO_MulAssign; break;
7366 case tok::slashequal: Opc = BO_DivAssign; break;
7367 case tok::percentequal: Opc = BO_RemAssign; break;
7368 case tok::plusequal: Opc = BO_AddAssign; break;
7369 case tok::minusequal: Opc = BO_SubAssign; break;
7370 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7371 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7372 case tok::ampequal: Opc = BO_AndAssign; break;
7373 case tok::caretequal: Opc = BO_XorAssign; break;
7374 case tok::pipeequal: Opc = BO_OrAssign; break;
7375 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007376 }
7377 return Opc;
7378}
7379
John McCalle3027922010-08-25 11:45:40 +00007380static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007381 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007382 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007383 switch (Kind) {
7384 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007385 case tok::plusplus: Opc = UO_PreInc; break;
7386 case tok::minusminus: Opc = UO_PreDec; break;
7387 case tok::amp: Opc = UO_AddrOf; break;
7388 case tok::star: Opc = UO_Deref; break;
7389 case tok::plus: Opc = UO_Plus; break;
7390 case tok::minus: Opc = UO_Minus; break;
7391 case tok::tilde: Opc = UO_Not; break;
7392 case tok::exclaim: Opc = UO_LNot; break;
7393 case tok::kw___real: Opc = UO_Real; break;
7394 case tok::kw___imag: Opc = UO_Imag; break;
7395 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007396 }
7397 return Opc;
7398}
7399
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007400/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7401/// This warning is only emitted for builtin assignment operations. It is also
7402/// suppressed in the event of macro expansions.
7403static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7404 SourceLocation OpLoc) {
7405 if (!S.ActiveTemplateInstantiations.empty())
7406 return;
7407 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7408 return;
7409 lhs = lhs->IgnoreParenImpCasts();
7410 rhs = rhs->IgnoreParenImpCasts();
7411 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7412 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7413 if (!LeftDeclRef || !RightDeclRef ||
7414 LeftDeclRef->getLocation().isMacroID() ||
7415 RightDeclRef->getLocation().isMacroID())
7416 return;
7417 const ValueDecl *LeftDecl =
7418 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7419 const ValueDecl *RightDecl =
7420 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7421 if (LeftDecl != RightDecl)
7422 return;
7423 if (LeftDecl->getType().isVolatileQualified())
7424 return;
7425 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7426 if (RefTy->getPointeeType().isVolatileQualified())
7427 return;
7428
7429 S.Diag(OpLoc, diag::warn_self_assignment)
7430 << LeftDeclRef->getType()
7431 << lhs->getSourceRange() << rhs->getSourceRange();
7432}
7433
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007434/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7435/// operator @p Opc at location @c TokLoc. This routine only supports
7436/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007437ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007438 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007439 Expr *lhsExpr, Expr *rhsExpr) {
7440 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007441 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007442 // The following two variables are used for compound assignment operators
7443 QualType CompLHSTy; // Type of LHS after promotions for computation
7444 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007445 ExprValueKind VK = VK_RValue;
7446 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007447
Douglas Gregor1beec452011-03-12 01:48:56 +00007448 // Check if a 'foo<int>' involved in a binary op, identifies a single
7449 // function unambiguously (i.e. an lvalue ala 13.4)
7450 // But since an assignment can trigger target based overload, exclude it in
7451 // our blind search. i.e:
7452 // template<class T> void f(); template<class T, class U> void f(U);
7453 // f<int> == 0; // resolve f<int> blindly
7454 // void (*p)(int); p = f<int>; // resolve f<int> using target
7455 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007456 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007457 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007458 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007459
John McCall3aef3d82011-04-10 19:13:55 +00007460 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007461 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007462 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007463 }
7464
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007465 // The canonical way to check for a GNU null is with isNullPointerConstant,
7466 // but we use a bit of a hack here for speed; this is a relatively
7467 // hot path, and isNullPointerConstant is slow.
7468 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7469 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007470
7471 // Detect when a NULL constant is used improperly in an expression. These
7472 // are mainly cases where the null pointer is used as an integer instead
7473 // of a pointer.
7474 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007475 // Avoid analyzing cases where the result will either be invalid (and
7476 // diagnosed as such) or entirely valid and not something to warn about.
7477 QualType LeftType = lhs.get()->getType();
7478 QualType RightType = rhs.get()->getType();
7479 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7480 !LeftType->isFunctionType() &&
7481 !RightType->isBlockPointerType() &&
7482 !RightType->isMemberPointerType() &&
7483 !RightType->isFunctionType()) {
7484 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7485 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7486 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7487 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7488 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7489 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7490 // These are the operations that would not make sense with a null pointer
7491 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007492 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007493 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7494 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7495 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7496 Opc == BO_EQ || Opc == BO_NE) {
7497 // These are the operations that would not make sense with a null pointer
7498 // if the other expression the other expression is not a pointer.
7499 if (LeftNull != RightNull &&
7500 !LeftType->isAnyPointerType() &&
7501 !LeftType->canDecayToPointerType() &&
7502 !RightType->isAnyPointerType() &&
7503 !RightType->canDecayToPointerType()) {
7504 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7505 << (LeftNull ? lhs.get()->getSourceRange()
7506 : rhs.get()->getSourceRange());
7507 }
Richard Trieu701fb362011-06-16 21:36:56 +00007508 }
7509 }
7510 }
7511
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007512 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007513 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007514 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007515 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007516 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7517 VK = lhs.get()->getValueKind();
7518 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007519 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007520 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007521 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007522 break;
John McCalle3027922010-08-25 11:45:40 +00007523 case BO_PtrMemD:
7524 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007525 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007526 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007527 break;
John McCalle3027922010-08-25 11:45:40 +00007528 case BO_Mul:
7529 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007530 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007531 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007532 break;
John McCalle3027922010-08-25 11:45:40 +00007533 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007534 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7535 break;
John McCalle3027922010-08-25 11:45:40 +00007536 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007537 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7538 break;
John McCalle3027922010-08-25 11:45:40 +00007539 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007540 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7541 break;
John McCalle3027922010-08-25 11:45:40 +00007542 case BO_Shl:
7543 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007544 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007545 break;
John McCalle3027922010-08-25 11:45:40 +00007546 case BO_LE:
7547 case BO_LT:
7548 case BO_GE:
7549 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007550 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007551 break;
John McCalle3027922010-08-25 11:45:40 +00007552 case BO_EQ:
7553 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007554 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007555 break;
John McCalle3027922010-08-25 11:45:40 +00007556 case BO_And:
7557 case BO_Xor:
7558 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007559 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7560 break;
John McCalle3027922010-08-25 11:45:40 +00007561 case BO_LAnd:
7562 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007563 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007564 break;
John McCalle3027922010-08-25 11:45:40 +00007565 case BO_MulAssign:
7566 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007567 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007568 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007569 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007570 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7571 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007572 break;
John McCalle3027922010-08-25 11:45:40 +00007573 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007574 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7575 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007576 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7577 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007578 break;
John McCalle3027922010-08-25 11:45:40 +00007579 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007580 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007581 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7582 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007583 break;
John McCalle3027922010-08-25 11:45:40 +00007584 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007585 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007586 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7587 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007588 break;
John McCalle3027922010-08-25 11:45:40 +00007589 case BO_ShlAssign:
7590 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007591 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007592 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007593 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7594 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007595 break;
John McCalle3027922010-08-25 11:45:40 +00007596 case BO_AndAssign:
7597 case BO_XorAssign:
7598 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007599 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7600 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007601 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7602 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007603 break;
John McCalle3027922010-08-25 11:45:40 +00007604 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007605 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007606 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7607 VK = rhs.get()->getValueKind();
7608 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007609 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007610 break;
7611 }
John Wiegley01296292011-04-08 18:41:53 +00007612 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007613 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007614 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007615 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7616 ResultTy, VK, OK, OpLoc));
7617 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007618 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007619 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007620 }
John Wiegley01296292011-04-08 18:41:53 +00007621 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7622 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007623 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007624}
7625
Sebastian Redl44615072009-10-27 12:10:02 +00007626/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7627/// operators are mixed in a way that suggests that the programmer forgot that
7628/// comparison operators have higher precedence. The most typical example of
7629/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007630static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007631 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007632 typedef BinaryOperator BinOp;
7633 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7634 rhsopc = static_cast<BinOp::Opcode>(-1);
7635 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007636 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007637 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007638 rhsopc = BO->getOpcode();
7639
7640 // Subs are not binary operators.
7641 if (lhsopc == -1 && rhsopc == -1)
7642 return;
7643
7644 // Bitwise operations are sometimes used as eager logical ops.
7645 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007646 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7647 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007648 return;
7649
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007650 if (BinOp::isComparisonOp(lhsopc)) {
7651 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7652 << SourceRange(lhs->getLocStart(), OpLoc)
7653 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007654 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007655 Self.PDiag(diag::note_precedence_bitwise_silence)
7656 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007657 lhs->getSourceRange());
7658 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007659 Self.PDiag(diag::note_precedence_bitwise_first)
7660 << BinOp::getOpcodeStr(Opc),
7661 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007662 } else if (BinOp::isComparisonOp(rhsopc)) {
7663 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7664 << SourceRange(OpLoc, rhs->getLocEnd())
7665 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007666 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007667 Self.PDiag(diag::note_precedence_bitwise_silence)
7668 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007669 rhs->getSourceRange());
7670 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007671 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007672 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007673 SourceRange(lhs->getLocStart(),
7674 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007675 }
Sebastian Redl43028242009-10-26 15:24:15 +00007676}
7677
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007678/// \brief It accepts a '&' expr that is inside a '|' one.
7679/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7680/// in parentheses.
7681static void
7682EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7683 BinaryOperator *Bop) {
7684 assert(Bop->getOpcode() == BO_And);
7685 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7686 << Bop->getSourceRange() << OpLoc;
7687 SuggestParentheses(Self, Bop->getOperatorLoc(),
7688 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7689 Bop->getSourceRange());
7690}
7691
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007692/// \brief It accepts a '&&' expr that is inside a '||' one.
7693/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7694/// in parentheses.
7695static void
7696EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007697 BinaryOperator *Bop) {
7698 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007699 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7700 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007701 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007702 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007703 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007704}
7705
7706/// \brief Returns true if the given expression can be evaluated as a constant
7707/// 'true'.
7708static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7709 bool Res;
7710 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7711}
7712
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007713/// \brief Returns true if the given expression can be evaluated as a constant
7714/// 'false'.
7715static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7716 bool Res;
7717 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7718}
7719
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007720/// \brief Look for '&&' in the left hand of a '||' expr.
7721static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007722 Expr *OrLHS, Expr *OrRHS) {
7723 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007724 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007725 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7726 if (EvaluatesAsFalse(S, OrRHS))
7727 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007728 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7729 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7730 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7731 } else if (Bop->getOpcode() == BO_LOr) {
7732 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7733 // If it's "a || b && 1 || c" we didn't warn earlier for
7734 // "a || b && 1", but warn now.
7735 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7736 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7737 }
7738 }
7739 }
7740}
7741
7742/// \brief Look for '&&' in the right hand of a '||' expr.
7743static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007744 Expr *OrLHS, Expr *OrRHS) {
7745 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007746 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007747 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7748 if (EvaluatesAsFalse(S, OrLHS))
7749 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007750 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7751 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7752 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007753 }
7754 }
7755}
7756
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007757/// \brief Look for '&' in the left or right hand of a '|' expr.
7758static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7759 Expr *OrArg) {
7760 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7761 if (Bop->getOpcode() == BO_And)
7762 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7763 }
7764}
7765
Sebastian Redl43028242009-10-26 15:24:15 +00007766/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007767/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007768static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007769 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007770 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007771 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007772 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7773
7774 // Diagnose "arg1 & arg2 | arg3"
7775 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7776 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7777 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7778 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007779
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007780 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7781 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007782 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007783 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7784 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007785 }
Sebastian Redl43028242009-10-26 15:24:15 +00007786}
7787
Steve Naroff218bc2b2007-05-04 21:54:46 +00007788// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007789ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007790 tok::TokenKind Kind,
7791 Expr *lhs, Expr *rhs) {
7792 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007793 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7794 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007795
Sebastian Redl43028242009-10-26 15:24:15 +00007796 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7797 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7798
Douglas Gregor5287f092009-11-05 00:51:44 +00007799 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7800}
7801
John McCalldadc5752010-08-24 06:29:42 +00007802ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007803 BinaryOperatorKind Opc,
7804 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007805 if (getLangOptions().CPlusPlus) {
7806 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007807
John McCall622114c2010-12-06 05:26:58 +00007808 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7809 UseBuiltinOperator = false;
7810 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7811 UseBuiltinOperator = true;
7812 } else {
7813 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7814 !rhs->getType()->isOverloadableType();
7815 }
7816
7817 if (!UseBuiltinOperator) {
7818 // Find all of the overloaded operators visible from this
7819 // point. We perform both an operator-name lookup from the local
7820 // scope and an argument-dependent lookup based on the types of
7821 // the arguments.
7822 UnresolvedSet<16> Functions;
7823 OverloadedOperatorKind OverOp
7824 = BinaryOperator::getOverloadedOperator(Opc);
7825 if (S && OverOp != OO_None)
7826 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7827 Functions);
7828
7829 // Build the (potentially-overloaded, potentially-dependent)
7830 // binary operation.
7831 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7832 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007833 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007834
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007835 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007836 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007837}
7838
John McCalldadc5752010-08-24 06:29:42 +00007839ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007840 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007841 Expr *InputExpr) {
7842 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007843 ExprValueKind VK = VK_RValue;
7844 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007845 QualType resultType;
7846 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007847 case UO_PreInc:
7848 case UO_PreDec:
7849 case UO_PostInc:
7850 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007851 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007852 Opc == UO_PreInc ||
7853 Opc == UO_PostInc,
7854 Opc == UO_PreInc ||
7855 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007856 break;
John McCalle3027922010-08-25 11:45:40 +00007857 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007858 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007859 break;
John McCall31996342011-04-07 08:22:57 +00007860 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007861 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007862 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007863 Input = move(resolved);
7864 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7865 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007866 break;
John McCall31996342011-04-07 08:22:57 +00007867 }
John McCalle3027922010-08-25 11:45:40 +00007868 case UO_Plus:
7869 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007870 Input = UsualUnaryConversions(Input.take());
7871 if (Input.isInvalid()) return ExprError();
7872 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007873 if (resultType->isDependentType())
7874 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007875 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7876 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007877 break;
7878 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7879 resultType->isEnumeralType())
7880 break;
7881 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007882 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007883 resultType->isPointerType())
7884 break;
John McCall36226622010-10-12 02:09:17 +00007885 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007886 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007887 if (Input.isInvalid()) return ExprError();
7888 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007889 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007890
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007892 << resultType << Input.get()->getSourceRange());
7893
John McCalle3027922010-08-25 11:45:40 +00007894 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007895 Input = UsualUnaryConversions(Input.take());
7896 if (Input.isInvalid()) return ExprError();
7897 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007898 if (resultType->isDependentType())
7899 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007900 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7901 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7902 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007903 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007904 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007905 else if (resultType->hasIntegerRepresentation())
7906 break;
7907 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007908 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007909 if (Input.isInvalid()) return ExprError();
7910 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007911 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007912 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007913 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007914 }
Steve Naroff35d85152007-05-07 00:24:15 +00007915 break;
John Wiegley01296292011-04-08 18:41:53 +00007916
John McCalle3027922010-08-25 11:45:40 +00007917 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007918 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007919 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7920 if (Input.isInvalid()) return ExprError();
7921 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007922 if (resultType->isDependentType())
7923 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007924 if (resultType->isScalarType()) {
7925 // C99 6.5.3.3p1: ok, fallthrough;
7926 if (Context.getLangOptions().CPlusPlus) {
7927 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7928 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007929 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7930 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007931 }
John McCall36226622010-10-12 02:09:17 +00007932 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007933 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007934 if (Input.isInvalid()) return ExprError();
7935 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007936 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007937 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007938 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007939 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007940
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007941 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007942 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007943 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007944 break;
John McCalle3027922010-08-25 11:45:40 +00007945 case UO_Real:
7946 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007947 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007948 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007949 if (Input.isInvalid()) return ExprError();
7950 if (Input.get()->getValueKind() != VK_RValue &&
7951 Input.get()->getObjectKind() == OK_Ordinary)
7952 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007953 break;
John McCalle3027922010-08-25 11:45:40 +00007954 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007955 resultType = Input.get()->getType();
7956 VK = Input.get()->getValueKind();
7957 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007958 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007959 }
John Wiegley01296292011-04-08 18:41:53 +00007960 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007961 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007962
John Wiegley01296292011-04-08 18:41:53 +00007963 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007964 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007965}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007966
John McCalldadc5752010-08-24 06:29:42 +00007967ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007968 UnaryOperatorKind Opc,
7969 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007970 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007971 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007972 // Find all of the overloaded operators visible from this
7973 // point. We perform both an operator-name lookup from the local
7974 // scope and an argument-dependent lookup based on the types of
7975 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007976 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007977 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007978 if (S && OverOp != OO_None)
7979 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7980 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007981
John McCallb268a282010-08-23 23:25:46 +00007982 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007984
John McCallb268a282010-08-23 23:25:46 +00007985 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007986}
7987
Douglas Gregor5287f092009-11-05 00:51:44 +00007988// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007989ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007990 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007991 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007992}
7993
Steve Naroff66356bd2007-09-16 14:56:35 +00007994/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007995ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007996 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007997 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007998 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007999 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008000 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008001}
8002
John McCall31168b02011-06-15 23:02:42 +00008003/// Given the last statement in a statement-expression, check whether
8004/// the result is a producing expression (like a call to an
8005/// ns_returns_retained function) and, if so, rebuild it to hoist the
8006/// release out of the full-expression. Otherwise, return null.
8007/// Cannot fail.
8008static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8009 // Should always be wrapped with one of these.
8010 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8011 if (!cleanups) return 0;
8012
8013 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8014 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8015 return 0;
8016
8017 // Splice out the cast. This shouldn't modify any interesting
8018 // features of the statement.
8019 Expr *producer = cast->getSubExpr();
8020 assert(producer->getType() == cast->getType());
8021 assert(producer->getValueKind() == cast->getValueKind());
8022 cleanups->setSubExpr(producer);
8023 return cleanups;
8024}
8025
John McCalldadc5752010-08-24 06:29:42 +00008026ExprResult
John McCallb268a282010-08-23 23:25:46 +00008027Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008028 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008029 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8030 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8031
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008032 bool isFileScope
8033 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008034 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008035 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008036
Chris Lattner366727f2007-07-24 16:58:17 +00008037 // FIXME: there are a variety of strange constraints to enforce here, for
8038 // example, it is not possible to goto into a stmt expression apparently.
8039 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008040
Chris Lattner366727f2007-07-24 16:58:17 +00008041 // If there are sub stmts in the compound stmt, take the type of the last one
8042 // as the type of the stmtexpr.
8043 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008044 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008045 if (!Compound->body_empty()) {
8046 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008047 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008048 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008049 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8050 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008051 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008052 }
John McCall31168b02011-06-15 23:02:42 +00008053
John Wiegley01296292011-04-08 18:41:53 +00008054 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008055 // Do function/array conversion on the last expression, but not
8056 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008057 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8058 if (LastExpr.isInvalid())
8059 return ExprError();
8060 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008061
John Wiegley01296292011-04-08 18:41:53 +00008062 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008063 // In ARC, if the final expression ends in a consume, splice
8064 // the consume out and bind it later. In the alternate case
8065 // (when dealing with a retainable type), the result
8066 // initialization will create a produce. In both cases the
8067 // result will be +1, and we'll need to balance that out with
8068 // a bind.
8069 if (Expr *rebuiltLastStmt
8070 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8071 LastExpr = rebuiltLastStmt;
8072 } else {
8073 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008074 InitializedEntity::InitializeResult(LPLoc,
8075 Ty,
8076 false),
8077 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008078 LastExpr);
8079 }
8080
John Wiegley01296292011-04-08 18:41:53 +00008081 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008082 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008083 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008084 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008085 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008086 else
John Wiegley01296292011-04-08 18:41:53 +00008087 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008088 StmtExprMayBindToTemp = true;
8089 }
8090 }
8091 }
Chris Lattner944d3062008-07-26 19:51:01 +00008092 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008093
Eli Friedmanba961a92009-03-23 00:24:07 +00008094 // FIXME: Check that expression type is complete/non-abstract; statement
8095 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008096 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8097 if (StmtExprMayBindToTemp)
8098 return MaybeBindToTemporary(ResStmtExpr);
8099 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008100}
Steve Naroff78864672007-08-01 22:05:33 +00008101
John McCalldadc5752010-08-24 06:29:42 +00008102ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008103 TypeSourceInfo *TInfo,
8104 OffsetOfComponent *CompPtr,
8105 unsigned NumComponents,
8106 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008107 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008108 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008109 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008110
Chris Lattnerf17bd422007-08-30 17:45:32 +00008111 // We must have at least one component that refers to the type, and the first
8112 // one is known to be a field designator. Verify that the ArgTy represents
8113 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008114 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008115 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8116 << ArgTy << TypeRange);
8117
8118 // Type must be complete per C99 7.17p3 because a declaring a variable
8119 // with an incomplete type would be ill-formed.
8120 if (!Dependent
8121 && RequireCompleteType(BuiltinLoc, ArgTy,
8122 PDiag(diag::err_offsetof_incomplete_type)
8123 << TypeRange))
8124 return ExprError();
8125
Chris Lattner78502cf2007-08-31 21:49:13 +00008126 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8127 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008128 // FIXME: This diagnostic isn't actually visible because the location is in
8129 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008130 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008131 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8132 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008133
8134 bool DidWarnAboutNonPOD = false;
8135 QualType CurrentType = ArgTy;
8136 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008137 SmallVector<OffsetOfNode, 4> Comps;
8138 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008139 for (unsigned i = 0; i != NumComponents; ++i) {
8140 const OffsetOfComponent &OC = CompPtr[i];
8141 if (OC.isBrackets) {
8142 // Offset of an array sub-field. TODO: Should we allow vector elements?
8143 if (!CurrentType->isDependentType()) {
8144 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8145 if(!AT)
8146 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8147 << CurrentType);
8148 CurrentType = AT->getElementType();
8149 } else
8150 CurrentType = Context.DependentTy;
8151
8152 // The expression must be an integral expression.
8153 // FIXME: An integral constant expression?
8154 Expr *Idx = static_cast<Expr*>(OC.U.E);
8155 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8156 !Idx->getType()->isIntegerType())
8157 return ExprError(Diag(Idx->getLocStart(),
8158 diag::err_typecheck_subscript_not_integer)
8159 << Idx->getSourceRange());
8160
8161 // Record this array index.
8162 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8163 Exprs.push_back(Idx);
8164 continue;
8165 }
8166
8167 // Offset of a field.
8168 if (CurrentType->isDependentType()) {
8169 // We have the offset of a field, but we can't look into the dependent
8170 // type. Just record the identifier of the field.
8171 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8172 CurrentType = Context.DependentTy;
8173 continue;
8174 }
8175
8176 // We need to have a complete type to look into.
8177 if (RequireCompleteType(OC.LocStart, CurrentType,
8178 diag::err_offsetof_incomplete_type))
8179 return ExprError();
8180
8181 // Look for the designated field.
8182 const RecordType *RC = CurrentType->getAs<RecordType>();
8183 if (!RC)
8184 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8185 << CurrentType);
8186 RecordDecl *RD = RC->getDecl();
8187
8188 // C++ [lib.support.types]p5:
8189 // The macro offsetof accepts a restricted set of type arguments in this
8190 // International Standard. type shall be a POD structure or a POD union
8191 // (clause 9).
8192 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8193 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008194 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008195 PDiag(diag::warn_offsetof_non_pod_type)
8196 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8197 << CurrentType))
8198 DidWarnAboutNonPOD = true;
8199 }
8200
8201 // Look for the field.
8202 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8203 LookupQualifiedName(R, RD);
8204 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008205 IndirectFieldDecl *IndirectMemberDecl = 0;
8206 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008207 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008208 MemberDecl = IndirectMemberDecl->getAnonField();
8209 }
8210
Douglas Gregor882211c2010-04-28 22:16:22 +00008211 if (!MemberDecl)
8212 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8213 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8214 OC.LocEnd));
8215
Douglas Gregor10982ea2010-04-28 22:36:06 +00008216 // C99 7.17p3:
8217 // (If the specified member is a bit-field, the behavior is undefined.)
8218 //
8219 // We diagnose this as an error.
8220 if (MemberDecl->getBitWidth()) {
8221 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8222 << MemberDecl->getDeclName()
8223 << SourceRange(BuiltinLoc, RParenLoc);
8224 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8225 return ExprError();
8226 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008227
8228 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008229 if (IndirectMemberDecl)
8230 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008231
Douglas Gregord1702062010-04-29 00:18:15 +00008232 // If the member was found in a base class, introduce OffsetOfNodes for
8233 // the base class indirections.
8234 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8235 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008236 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008237 CXXBasePath &Path = Paths.front();
8238 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8239 B != BEnd; ++B)
8240 Comps.push_back(OffsetOfNode(B->Base));
8241 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008242
Francois Pichet783dd6e2010-11-21 06:08:52 +00008243 if (IndirectMemberDecl) {
8244 for (IndirectFieldDecl::chain_iterator FI =
8245 IndirectMemberDecl->chain_begin(),
8246 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8247 assert(isa<FieldDecl>(*FI));
8248 Comps.push_back(OffsetOfNode(OC.LocStart,
8249 cast<FieldDecl>(*FI), OC.LocEnd));
8250 }
8251 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008252 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008253
Douglas Gregor882211c2010-04-28 22:16:22 +00008254 CurrentType = MemberDecl->getType().getNonReferenceType();
8255 }
8256
8257 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8258 TInfo, Comps.data(), Comps.size(),
8259 Exprs.data(), Exprs.size(), RParenLoc));
8260}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008261
John McCalldadc5752010-08-24 06:29:42 +00008262ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008263 SourceLocation BuiltinLoc,
8264 SourceLocation TypeLoc,
8265 ParsedType argty,
8266 OffsetOfComponent *CompPtr,
8267 unsigned NumComponents,
8268 SourceLocation RPLoc) {
8269
Douglas Gregor882211c2010-04-28 22:16:22 +00008270 TypeSourceInfo *ArgTInfo;
8271 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8272 if (ArgTy.isNull())
8273 return ExprError();
8274
Eli Friedman06dcfd92010-08-05 10:15:45 +00008275 if (!ArgTInfo)
8276 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8277
8278 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8279 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008280}
8281
8282
John McCalldadc5752010-08-24 06:29:42 +00008283ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008284 Expr *CondExpr,
8285 Expr *LHSExpr, Expr *RHSExpr,
8286 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008287 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8288
John McCall7decc9e2010-11-18 06:31:45 +00008289 ExprValueKind VK = VK_RValue;
8290 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008291 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008292 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008293 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008294 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008295 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008296 } else {
8297 // The conditional expression is required to be a constant expression.
8298 llvm::APSInt condEval(32);
8299 SourceLocation ExpLoc;
8300 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008301 return ExprError(Diag(ExpLoc,
8302 diag::err_typecheck_choose_expr_requires_constant)
8303 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008304
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008305 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008306 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8307
8308 resType = ActiveExpr->getType();
8309 ValueDependent = ActiveExpr->isValueDependent();
8310 VK = ActiveExpr->getValueKind();
8311 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008312 }
8313
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008314 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008315 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008316 resType->isDependentType(),
8317 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008318}
8319
Steve Naroffc540d662008-09-03 18:15:37 +00008320//===----------------------------------------------------------------------===//
8321// Clang Extensions.
8322//===----------------------------------------------------------------------===//
8323
8324/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008325void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008326 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8327 PushBlockScope(BlockScope, Block);
8328 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008329 if (BlockScope)
8330 PushDeclContext(BlockScope, Block);
8331 else
8332 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008333}
8334
Mike Stump82f071f2009-02-04 22:31:32 +00008335void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008336 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008337 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008338 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008339
John McCall8cb7bdf2010-06-04 23:28:52 +00008340 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008341 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008342
John McCall3882ace2011-01-05 12:14:39 +00008343 // GetTypeForDeclarator always produces a function type for a block
8344 // literal signature. Furthermore, it is always a FunctionProtoType
8345 // unless the function was written with a typedef.
8346 assert(T->isFunctionType() &&
8347 "GetTypeForDeclarator made a non-function block signature");
8348
8349 // Look for an explicit signature in that function type.
8350 FunctionProtoTypeLoc ExplicitSignature;
8351
8352 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8353 if (isa<FunctionProtoTypeLoc>(tmp)) {
8354 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8355
8356 // Check whether that explicit signature was synthesized by
8357 // GetTypeForDeclarator. If so, don't save that as part of the
8358 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008359 if (ExplicitSignature.getLocalRangeBegin() ==
8360 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008361 // This would be much cheaper if we stored TypeLocs instead of
8362 // TypeSourceInfos.
8363 TypeLoc Result = ExplicitSignature.getResultLoc();
8364 unsigned Size = Result.getFullDataSize();
8365 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8366 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8367
8368 ExplicitSignature = FunctionProtoTypeLoc();
8369 }
John McCalla3ccba02010-06-04 11:21:44 +00008370 }
Mike Stump11289f42009-09-09 15:08:12 +00008371
John McCall3882ace2011-01-05 12:14:39 +00008372 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8373 CurBlock->FunctionType = T;
8374
8375 const FunctionType *Fn = T->getAs<FunctionType>();
8376 QualType RetTy = Fn->getResultType();
8377 bool isVariadic =
8378 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8379
John McCall8e346702010-06-04 19:02:56 +00008380 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008381
John McCalla3ccba02010-06-04 11:21:44 +00008382 // Don't allow returning a objc interface by value.
8383 if (RetTy->isObjCObjectType()) {
8384 Diag(ParamInfo.getSourceRange().getBegin(),
8385 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8386 return;
8387 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008388
John McCalla3ccba02010-06-04 11:21:44 +00008389 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008390 // return type. TODO: what should we do with declarators like:
8391 // ^ * { ... }
8392 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008393 if (RetTy != Context.DependentTy)
8394 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008395
John McCalla3ccba02010-06-04 11:21:44 +00008396 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008397 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008398 if (ExplicitSignature) {
8399 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8400 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008401 if (Param->getIdentifier() == 0 &&
8402 !Param->isImplicit() &&
8403 !Param->isInvalidDecl() &&
8404 !getLangOptions().CPlusPlus)
8405 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008406 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008407 }
John McCalla3ccba02010-06-04 11:21:44 +00008408
8409 // Fake up parameter variables if we have a typedef, like
8410 // ^ fntype { ... }
8411 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8412 for (FunctionProtoType::arg_type_iterator
8413 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8414 ParmVarDecl *Param =
8415 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8416 ParamInfo.getSourceRange().getBegin(),
8417 *I);
John McCall8e346702010-06-04 19:02:56 +00008418 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008419 }
Steve Naroffc540d662008-09-03 18:15:37 +00008420 }
John McCalla3ccba02010-06-04 11:21:44 +00008421
John McCall8e346702010-06-04 19:02:56 +00008422 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008423 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008424 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008425 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8426 CurBlock->TheDecl->param_end(),
8427 /*CheckParameterNames=*/false);
8428 }
8429
John McCalla3ccba02010-06-04 11:21:44 +00008430 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008431 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008432
John McCall8e346702010-06-04 19:02:56 +00008433 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008434 Diag(ParamInfo.getAttributes()->getLoc(),
8435 diag::warn_attribute_sentinel_not_variadic) << 1;
8436 // FIXME: remove the attribute.
8437 }
8438
8439 // Put the parameter variables in scope. We can bail out immediately
8440 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008441 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008442 return;
8443
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008444 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008445 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8446 (*AI)->setOwningFunction(CurBlock->TheDecl);
8447
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008448 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008449 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008450 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008451
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008452 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008453 }
John McCallf7b2fb52010-01-22 00:28:27 +00008454 }
Steve Naroffc540d662008-09-03 18:15:37 +00008455}
8456
8457/// ActOnBlockError - If there is an error parsing a block, this callback
8458/// is invoked to pop the information about the block from the action impl.
8459void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008460 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008461 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008462 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008463}
8464
8465/// ActOnBlockStmtExpr - This is called when the body of a block statement
8466/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008467ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008468 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008469 // If blocks are disabled, emit an error.
8470 if (!LangOpts.Blocks)
8471 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008472
Douglas Gregor9a28e842010-03-01 23:15:13 +00008473 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008474
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008475 PopDeclContext();
8476
Steve Naroffc540d662008-09-03 18:15:37 +00008477 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008478 if (!BSI->ReturnType.isNull())
8479 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008480
Mike Stump3bf1ab42009-07-28 22:04:01 +00008481 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008482 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008483
John McCallc63de662011-02-02 13:00:07 +00008484 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008485 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8486 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008487
John McCall8e346702010-06-04 19:02:56 +00008488 // If the user wrote a function type in some form, try to use that.
8489 if (!BSI->FunctionType.isNull()) {
8490 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8491
8492 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8493 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8494
8495 // Turn protoless block types into nullary block types.
8496 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008497 FunctionProtoType::ExtProtoInfo EPI;
8498 EPI.ExtInfo = Ext;
8499 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008500
8501 // Otherwise, if we don't need to change anything about the function type,
8502 // preserve its sugar structure.
8503 } else if (FTy->getResultType() == RetTy &&
8504 (!NoReturn || FTy->getNoReturnAttr())) {
8505 BlockTy = BSI->FunctionType;
8506
8507 // Otherwise, make the minimal modifications to the function type.
8508 } else {
8509 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008510 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8511 EPI.TypeQuals = 0; // FIXME: silently?
8512 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008513 BlockTy = Context.getFunctionType(RetTy,
8514 FPT->arg_type_begin(),
8515 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008516 EPI);
John McCall8e346702010-06-04 19:02:56 +00008517 }
8518
8519 // If we don't have a function type, just build one from nothing.
8520 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008521 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008522 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008523 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008524 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008525
John McCall8e346702010-06-04 19:02:56 +00008526 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8527 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008528 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008529
Chris Lattner45542ea2009-04-19 05:28:12 +00008530 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008531 if (getCurFunction()->NeedsScopeChecking() &&
8532 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008533 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008534
Chris Lattner60f84492011-02-17 23:58:47 +00008535 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008536
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008537 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8538 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8539 const VarDecl *variable = ci->getVariable();
8540 QualType T = variable->getType();
8541 QualType::DestructionKind destructKind = T.isDestructedType();
8542 if (destructKind != QualType::DK_none)
8543 getCurFunction()->setHasBranchProtectedScope();
8544 }
8545
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008546 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8547 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8548 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8549
Douglas Gregor9a28e842010-03-01 23:15:13 +00008550 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008551}
8552
John McCalldadc5752010-08-24 06:29:42 +00008553ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008554 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008555 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008556 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008557 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008558 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008559}
8560
John McCalldadc5752010-08-24 06:29:42 +00008561ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008562 Expr *E, TypeSourceInfo *TInfo,
8563 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008564 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008565
Eli Friedman121ba0c2008-08-09 23:32:40 +00008566 // Get the va_list type
8567 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008568 if (VaListType->isArrayType()) {
8569 // Deal with implicit array decay; for example, on x86-64,
8570 // va_list is an array, but it's supposed to decay to
8571 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008572 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008573 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008574 ExprResult Result = UsualUnaryConversions(E);
8575 if (Result.isInvalid())
8576 return ExprError();
8577 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008578 } else {
8579 // Otherwise, the va_list argument must be an l-value because
8580 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008581 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008582 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008583 return ExprError();
8584 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008585
Douglas Gregorad3150c2009-05-19 23:10:31 +00008586 if (!E->isTypeDependent() &&
8587 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008588 return ExprError(Diag(E->getLocStart(),
8589 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008590 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008591 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008592
David Majnemerc75d1a12011-06-14 05:17:32 +00008593 if (!TInfo->getType()->isDependentType()) {
8594 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8595 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8596 << TInfo->getTypeLoc().getSourceRange()))
8597 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008598
David Majnemerc75d1a12011-06-14 05:17:32 +00008599 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8600 TInfo->getType(),
8601 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8602 << TInfo->getTypeLoc().getSourceRange()))
8603 return ExprError();
8604
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008605 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008606 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008607 TInfo->getType()->isObjCLifetimeType()
8608 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8609 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008610 << TInfo->getType()
8611 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008612 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008613
8614 // Check for va_arg where arguments of the given type will be promoted
8615 // (i.e. this va_arg is guaranteed to have undefined behavior).
8616 QualType PromoteType;
8617 if (TInfo->getType()->isPromotableIntegerType()) {
8618 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8619 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8620 PromoteType = QualType();
8621 }
8622 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8623 PromoteType = Context.DoubleTy;
8624 if (!PromoteType.isNull())
8625 Diag(TInfo->getTypeLoc().getBeginLoc(),
8626 diag::warn_second_parameter_to_va_arg_never_compatible)
8627 << TInfo->getType()
8628 << PromoteType
8629 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008630 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008631
Abramo Bagnara27db2392010-08-10 10:06:15 +00008632 QualType T = TInfo->getType().getNonLValueExprType(Context);
8633 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008634}
8635
John McCalldadc5752010-08-24 06:29:42 +00008636ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008637 // The type of __null will be int or long, depending on the size of
8638 // pointers on the target.
8639 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008640 unsigned pw = Context.Target.getPointerWidth(0);
8641 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008642 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008643 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008644 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008645 else if (pw == Context.Target.getLongLongWidth())
8646 Ty = Context.LongLongTy;
8647 else {
8648 assert(!"I don't know size of pointer!");
8649 Ty = Context.IntTy;
8650 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008651
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008652 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008653}
8654
Alexis Huntc46382e2010-04-28 23:02:27 +00008655static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008656 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008657 if (!SemaRef.getLangOptions().ObjC1)
8658 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008659
Anders Carlssonace5d072009-11-10 04:46:30 +00008660 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8661 if (!PT)
8662 return;
8663
8664 // Check if the destination is of type 'id'.
8665 if (!PT->isObjCIdType()) {
8666 // Check if the destination is the 'NSString' interface.
8667 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8668 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8669 return;
8670 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008671
Anders Carlssonace5d072009-11-10 04:46:30 +00008672 // Strip off any parens and casts.
8673 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008674 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008675 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008676
Douglas Gregora771f462010-03-31 17:46:05 +00008677 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008678}
8679
Chris Lattner9bad62c2008-01-04 18:04:52 +00008680bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8681 SourceLocation Loc,
8682 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008683 Expr *SrcExpr, AssignmentAction Action,
8684 bool *Complained) {
8685 if (Complained)
8686 *Complained = false;
8687
Chris Lattner9bad62c2008-01-04 18:04:52 +00008688 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008689 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008690 bool isInvalid = false;
8691 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008692 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008693 ConversionFixItGenerator ConvHints;
8694 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008695
Chris Lattner9bad62c2008-01-04 18:04:52 +00008696 switch (ConvTy) {
8697 default: assert(0 && "Unknown conversion type");
8698 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008699 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008700 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008701 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8702 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008703 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008704 case IntToPointer:
8705 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008706 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8707 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008708 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008709 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008710 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008711 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008712 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8713 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008714 if (Hint.isNull() && !CheckInferredResultType) {
8715 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8716 }
8717 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008718 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008719 case IncompatiblePointerSign:
8720 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8721 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008722 case FunctionVoidPointer:
8723 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8724 break;
John McCall4fff8f62011-02-01 00:10:29 +00008725 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008726 // Perform array-to-pointer decay if necessary.
8727 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8728
John McCall4fff8f62011-02-01 00:10:29 +00008729 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8730 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8731 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8732 DiagKind = diag::err_typecheck_incompatible_address_space;
8733 break;
John McCall31168b02011-06-15 23:02:42 +00008734
8735
8736 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008737 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008738 break;
John McCall4fff8f62011-02-01 00:10:29 +00008739 }
8740
8741 llvm_unreachable("unknown error case for discarding qualifiers!");
8742 // fallthrough
8743 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008744 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008745 // If the qualifiers lost were because we were applying the
8746 // (deprecated) C++ conversion from a string literal to a char*
8747 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8748 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008749 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008750 // bit of refactoring (so that the second argument is an
8751 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008752 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008753 // C++ semantics.
8754 if (getLangOptions().CPlusPlus &&
8755 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8756 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008757 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8758 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008759 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008760 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008761 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008762 case IntToBlockPointer:
8763 DiagKind = diag::err_int_to_block_pointer;
8764 break;
8765 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008766 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008767 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008768 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008769 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008770 // it can give a more specific diagnostic.
8771 DiagKind = diag::warn_incompatible_qualified_id;
8772 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008773 case IncompatibleVectors:
8774 DiagKind = diag::warn_incompatible_vectors;
8775 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008776 case IncompatibleObjCWeakRef:
8777 DiagKind = diag::err_arc_weak_unavailable_assign;
8778 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008779 case Incompatible:
8780 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008781 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8782 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008783 isInvalid = true;
8784 break;
8785 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008786
Douglas Gregorc68e1402010-04-09 00:35:39 +00008787 QualType FirstType, SecondType;
8788 switch (Action) {
8789 case AA_Assigning:
8790 case AA_Initializing:
8791 // The destination type comes first.
8792 FirstType = DstType;
8793 SecondType = SrcType;
8794 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008795
Douglas Gregorc68e1402010-04-09 00:35:39 +00008796 case AA_Returning:
8797 case AA_Passing:
8798 case AA_Converting:
8799 case AA_Sending:
8800 case AA_Casting:
8801 // The source type comes first.
8802 FirstType = SrcType;
8803 SecondType = DstType;
8804 break;
8805 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008806
Anna Zaks3b402712011-07-28 19:51:27 +00008807 PartialDiagnostic FDiag = PDiag(DiagKind);
8808 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8809
8810 // If we can fix the conversion, suggest the FixIts.
8811 assert(ConvHints.isNull() || Hint.isNull());
8812 if (!ConvHints.isNull()) {
8813 for (llvm::SmallVector<FixItHint, 1>::iterator
8814 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8815 HI != HE; ++HI)
8816 FDiag << *HI;
8817 } else {
8818 FDiag << Hint;
8819 }
8820 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8821
8822 Diag(Loc, FDiag);
8823
Douglas Gregor33823722011-06-11 01:09:30 +00008824 if (CheckInferredResultType)
8825 EmitRelatedResultTypeNote(SrcExpr);
8826
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008827 if (Complained)
8828 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008829 return isInvalid;
8830}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008831
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008832bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008833 llvm::APSInt ICEResult;
8834 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8835 if (Result)
8836 *Result = ICEResult;
8837 return false;
8838 }
8839
Anders Carlssone54e8a12008-11-30 19:50:32 +00008840 Expr::EvalResult EvalResult;
8841
Mike Stump4e1f26a2009-02-19 03:04:26 +00008842 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008843 EvalResult.HasSideEffects) {
8844 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8845
8846 if (EvalResult.Diag) {
8847 // We only show the note if it's not the usual "invalid subexpression"
8848 // or if it's actually in a subexpression.
8849 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8850 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8851 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008853
Anders Carlssone54e8a12008-11-30 19:50:32 +00008854 return true;
8855 }
8856
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008857 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8858 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008859
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008860 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008861 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8862 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008863 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008864
Anders Carlssone54e8a12008-11-30 19:50:32 +00008865 if (Result)
8866 *Result = EvalResult.Val.getInt();
8867 return false;
8868}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008869
Douglas Gregorff790f12009-11-26 00:44:06 +00008870void
Mike Stump11289f42009-09-09 15:08:12 +00008871Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008872 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008873 ExpressionEvaluationContextRecord(NewContext,
8874 ExprTemporaries.size(),
8875 ExprNeedsCleanups));
8876 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008877}
8878
Mike Stump11289f42009-09-09 15:08:12 +00008879void
Douglas Gregorff790f12009-11-26 00:44:06 +00008880Sema::PopExpressionEvaluationContext() {
8881 // Pop the current expression evaluation context off the stack.
8882 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8883 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008884
Douglas Gregorfab31f42009-12-12 07:57:52 +00008885 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8886 if (Rec.PotentiallyReferenced) {
8887 // Mark any remaining declarations in the current position of the stack
8888 // as "referenced". If they were not meant to be referenced, semantic
8889 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008890 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008891 I = Rec.PotentiallyReferenced->begin(),
8892 IEnd = Rec.PotentiallyReferenced->end();
8893 I != IEnd; ++I)
8894 MarkDeclarationReferenced(I->first, I->second);
8895 }
8896
8897 if (Rec.PotentiallyDiagnosed) {
8898 // Emit any pending diagnostics.
8899 for (PotentiallyEmittedDiagnostics::iterator
8900 I = Rec.PotentiallyDiagnosed->begin(),
8901 IEnd = Rec.PotentiallyDiagnosed->end();
8902 I != IEnd; ++I)
8903 Diag(I->first, I->second);
8904 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008905 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008906
8907 // When are coming out of an unevaluated context, clear out any
8908 // temporaries that we may have created as part of the evaluation of
8909 // the expression in that context: they aren't relevant because they
8910 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008911 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008912 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8913 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008914 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8915
8916 // Otherwise, merge the contexts together.
8917 } else {
8918 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8919 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008920
8921 // Destroy the popped expression evaluation record.
8922 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008923}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008924
John McCall31168b02011-06-15 23:02:42 +00008925void Sema::DiscardCleanupsInEvaluationContext() {
8926 ExprTemporaries.erase(
8927 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8928 ExprTemporaries.end());
8929 ExprNeedsCleanups = false;
8930}
8931
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008932/// \brief Note that the given declaration was referenced in the source code.
8933///
8934/// This routine should be invoke whenever a given declaration is referenced
8935/// in the source code, and where that reference occurred. If this declaration
8936/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8937/// C99 6.9p3), then the declaration will be marked as used.
8938///
8939/// \param Loc the location where the declaration was referenced.
8940///
8941/// \param D the declaration that has been referenced by the source code.
8942void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8943 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008944
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008945 D->setReferenced();
8946
Douglas Gregorebada0772010-06-17 23:14:26 +00008947 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008948 return;
Mike Stump11289f42009-09-09 15:08:12 +00008949
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008950 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8951 // template or not. The reason for this is that unevaluated expressions
8952 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8953 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008954 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008955 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008956 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008957 return;
8958 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008959
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008960 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8961 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008962
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008963 // Do not mark anything as "used" within a dependent context; wait for
8964 // an instantiation.
8965 if (CurContext->isDependentContext())
8966 return;
Mike Stump11289f42009-09-09 15:08:12 +00008967
Douglas Gregorff790f12009-11-26 00:44:06 +00008968 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008969 case Unevaluated:
8970 // We are in an expression that is not potentially evaluated; do nothing.
8971 return;
Mike Stump11289f42009-09-09 15:08:12 +00008972
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008973 case PotentiallyEvaluated:
8974 // We are in a potentially-evaluated expression, so this declaration is
8975 // "used"; handle this below.
8976 break;
Mike Stump11289f42009-09-09 15:08:12 +00008977
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008978 case PotentiallyPotentiallyEvaluated:
8979 // We are in an expression that may be potentially evaluated; queue this
8980 // declaration reference until we know whether the expression is
8981 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008982 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008983 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008984
8985 case PotentiallyEvaluatedIfUsed:
8986 // Referenced declarations will only be used if the construct in the
8987 // containing expression is used.
8988 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008989 }
Mike Stump11289f42009-09-09 15:08:12 +00008990
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008991 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008992 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008993 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8994 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008995 return;
8996 if (!Constructor->isUsed(false))
8997 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008998 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008999 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009000 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009001 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009002 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009003
Douglas Gregor88d292c2010-05-13 16:44:06 +00009004 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009005 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009006 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009007 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009008 if (Destructor->isVirtual())
9009 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009010 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009011 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009012 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009013 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009014 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009015 } else if (MethodDecl->isVirtual())
9016 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009017 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009018 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009019 // Recursive functions should be marked when used from another function.
9020 if (CurContext == Function) return;
9021
Mike Stump11289f42009-09-09 15:08:12 +00009022 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009023 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009024 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009025 bool AlreadyInstantiated = false;
9026 if (FunctionTemplateSpecializationInfo *SpecInfo
9027 = Function->getTemplateSpecializationInfo()) {
9028 if (SpecInfo->getPointOfInstantiation().isInvalid())
9029 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009030 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009031 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009032 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009033 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009034 = Function->getMemberSpecializationInfo()) {
9035 if (MSInfo->getPointOfInstantiation().isInvalid())
9036 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009037 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009038 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009039 AlreadyInstantiated = true;
9040 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009041
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009042 if (!AlreadyInstantiated) {
9043 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9044 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9045 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9046 Loc));
9047 else
Chandler Carruth54080172010-08-25 08:44:16 +00009048 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009049 }
John McCall83779672011-02-19 02:53:41 +00009050 } else {
9051 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009052 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9053 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009054 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009055 MarkDeclarationReferenced(Loc, *i);
9056 }
John McCall83779672011-02-19 02:53:41 +00009057 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009058
John McCall83779672011-02-19 02:53:41 +00009059 // Keep track of used but undefined functions.
9060 if (!Function->isPure() && !Function->hasBody() &&
9061 Function->getLinkage() != ExternalLinkage) {
9062 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9063 if (old.isInvalid()) old = Loc;
9064 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009065
John McCall83779672011-02-19 02:53:41 +00009066 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009067 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009068 }
Mike Stump11289f42009-09-09 15:08:12 +00009069
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009070 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009071 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009072 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009073 Var->getInstantiatedFromStaticDataMember()) {
9074 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9075 assert(MSInfo && "Missing member specialization information?");
9076 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9077 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9078 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009079 // This is a modification of an existing AST node. Notify listeners.
9080 if (ASTMutationListener *L = getASTMutationListener())
9081 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009082 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009083 }
9084 }
Mike Stump11289f42009-09-09 15:08:12 +00009085
John McCall15dd4042011-02-21 19:25:48 +00009086 // Keep track of used but undefined variables. We make a hole in
9087 // the warning for static const data members with in-line
9088 // initializers.
John McCall83779672011-02-19 02:53:41 +00009089 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009090 && Var->getLinkage() != ExternalLinkage
9091 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009092 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9093 if (old.isInvalid()) old = Loc;
9094 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009095
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009096 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009097 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009098 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009099}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009100
Douglas Gregor5597ab42010-05-07 23:12:07 +00009101namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009102 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009103 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009104 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009105 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9106 Sema &S;
9107 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009108
Douglas Gregor5597ab42010-05-07 23:12:07 +00009109 public:
9110 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009111
Douglas Gregor5597ab42010-05-07 23:12:07 +00009112 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009113
9114 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9115 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009116 };
9117}
9118
Chandler Carruthaf80f662010-06-09 08:17:30 +00009119bool MarkReferencedDecls::TraverseTemplateArgument(
9120 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009121 if (Arg.getKind() == TemplateArgument::Declaration) {
9122 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9123 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009124
9125 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009126}
9127
Chandler Carruthaf80f662010-06-09 08:17:30 +00009128bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009129 if (ClassTemplateSpecializationDecl *Spec
9130 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9131 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009132 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009133 }
9134
Chandler Carruthc65667c2010-06-10 10:31:57 +00009135 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009136}
9137
9138void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9139 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009140 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009141}
9142
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009143namespace {
9144 /// \brief Helper class that marks all of the declarations referenced by
9145 /// potentially-evaluated subexpressions as "referenced".
9146 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9147 Sema &S;
9148
9149 public:
9150 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9151
9152 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9153
9154 void VisitDeclRefExpr(DeclRefExpr *E) {
9155 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9156 }
9157
9158 void VisitMemberExpr(MemberExpr *E) {
9159 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009160 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009161 }
9162
9163 void VisitCXXNewExpr(CXXNewExpr *E) {
9164 if (E->getConstructor())
9165 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9166 if (E->getOperatorNew())
9167 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9168 if (E->getOperatorDelete())
9169 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009170 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009171 }
9172
9173 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9174 if (E->getOperatorDelete())
9175 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009176 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9177 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9178 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9179 S.MarkDeclarationReferenced(E->getLocStart(),
9180 S.LookupDestructor(Record));
9181 }
9182
Douglas Gregor32b3de52010-09-11 23:32:50 +00009183 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009184 }
9185
9186 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9187 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009188 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009189 }
9190
9191 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9192 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9193 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009194
9195 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9196 Visit(E->getExpr());
9197 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009198 };
9199}
9200
9201/// \brief Mark any declarations that appear within this expression or any
9202/// potentially-evaluated subexpressions as "referenced".
9203void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9204 EvaluatedExprMarker(*this).Visit(E);
9205}
9206
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009207/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9208/// of the program being compiled.
9209///
9210/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009211/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009212/// possibility that the code will actually be executable. Code in sizeof()
9213/// expressions, code used only during overload resolution, etc., are not
9214/// potentially evaluated. This routine will suppress such diagnostics or,
9215/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009216/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009217/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009218///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009219/// This routine should be used for all diagnostics that describe the run-time
9220/// behavior of a program, such as passing a non-POD value through an ellipsis.
9221/// Failure to do so will likely result in spurious diagnostics or failures
9222/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009223bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009224 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009225 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009226 case Unevaluated:
9227 // The argument will never be evaluated, so don't complain.
9228 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009229
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009230 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009231 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009232 if (stmt && getCurFunctionOrMethodDecl()) {
9233 FunctionScopes.back()->PossiblyUnreachableDiags.
9234 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9235 }
9236 else
9237 Diag(Loc, PD);
9238
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009239 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009240
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009241 case PotentiallyPotentiallyEvaluated:
9242 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9243 break;
9244 }
9245
9246 return false;
9247}
9248
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009249bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9250 CallExpr *CE, FunctionDecl *FD) {
9251 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9252 return false;
9253
9254 PartialDiagnostic Note =
9255 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9256 << FD->getDeclName() : PDiag();
9257 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009258
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009259 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009260 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009261 PDiag(diag::err_call_function_incomplete_return)
9262 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009263 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009264 << CE->getSourceRange(),
9265 std::make_pair(NoteLoc, Note)))
9266 return true;
9267
9268 return false;
9269}
9270
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009271// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009272// will prevent this condition from triggering, which is what we want.
9273void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9274 SourceLocation Loc;
9275
John McCall0506e4a2009-11-11 02:41:58 +00009276 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009277 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009278
John McCalld5707ab2009-10-12 21:59:07 +00009279 if (isa<BinaryOperator>(E)) {
9280 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009281 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009282 return;
9283
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009284 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9285
John McCallb0e419e2009-11-12 00:06:05 +00009286 // Greylist some idioms by putting them into a warning subcategory.
9287 if (ObjCMessageExpr *ME
9288 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9289 Selector Sel = ME->getSelector();
9290
John McCallb0e419e2009-11-12 00:06:05 +00009291 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009292 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009293 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9294
9295 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009296 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009297 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9298 }
John McCall0506e4a2009-11-11 02:41:58 +00009299
John McCalld5707ab2009-10-12 21:59:07 +00009300 Loc = Op->getOperatorLoc();
9301 } else if (isa<CXXOperatorCallExpr>(E)) {
9302 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009303 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009304 return;
9305
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009306 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009307 Loc = Op->getOperatorLoc();
9308 } else {
9309 // Not an assignment.
9310 return;
9311 }
9312
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009313 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009314
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009315 SourceLocation Open = E->getSourceRange().getBegin();
9316 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9317 Diag(Loc, diag::note_condition_assign_silence)
9318 << FixItHint::CreateInsertion(Open, "(")
9319 << FixItHint::CreateInsertion(Close, ")");
9320
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009321 if (IsOrAssign)
9322 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9323 << FixItHint::CreateReplacement(Loc, "!=");
9324 else
9325 Diag(Loc, diag::note_condition_assign_to_comparison)
9326 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009327}
9328
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009329/// \brief Redundant parentheses over an equality comparison can indicate
9330/// that the user intended an assignment used as condition.
9331void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009332 // Don't warn if the parens came from a macro.
9333 SourceLocation parenLoc = parenE->getLocStart();
9334 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9335 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009336 // Don't warn for dependent expressions.
9337 if (parenE->isTypeDependent())
9338 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009339
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009340 Expr *E = parenE->IgnoreParens();
9341
9342 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009343 if (opE->getOpcode() == BO_EQ &&
9344 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9345 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009346 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009347
Ted Kremenekae022092011-02-02 02:20:30 +00009348 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009349 Diag(Loc, diag::note_equality_comparison_silence)
9350 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9351 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009352 Diag(Loc, diag::note_equality_comparison_to_assign)
9353 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009354 }
9355}
9356
John Wiegley01296292011-04-08 18:41:53 +00009357ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009358 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009359 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9360 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009361
John McCall0009fcc2011-04-26 20:42:42 +00009362 ExprResult result = CheckPlaceholderExpr(E);
9363 if (result.isInvalid()) return ExprError();
9364 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009365
John McCall0009fcc2011-04-26 20:42:42 +00009366 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009367 if (getLangOptions().CPlusPlus)
9368 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9369
John Wiegley01296292011-04-08 18:41:53 +00009370 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9371 if (ERes.isInvalid())
9372 return ExprError();
9373 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009374
9375 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009376 if (!T->isScalarType()) { // C99 6.8.4.1p1
9377 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9378 << T << E->getSourceRange();
9379 return ExprError();
9380 }
John McCalld5707ab2009-10-12 21:59:07 +00009381 }
9382
John Wiegley01296292011-04-08 18:41:53 +00009383 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009384}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009385
John McCalldadc5752010-08-24 06:29:42 +00009386ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9387 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009388 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009389 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009390
9391 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009392}
John McCall36e7fe32010-10-12 00:20:44 +00009393
John McCall31996342011-04-07 08:22:57 +00009394namespace {
John McCall2979fe02011-04-12 00:42:48 +00009395 /// A visitor for rebuilding a call to an __unknown_any expression
9396 /// to have an appropriate type.
9397 struct RebuildUnknownAnyFunction
9398 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9399
9400 Sema &S;
9401
9402 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9403
9404 ExprResult VisitStmt(Stmt *S) {
9405 llvm_unreachable("unexpected statement!");
9406 return ExprError();
9407 }
9408
9409 ExprResult VisitExpr(Expr *expr) {
9410 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9411 << expr->getSourceRange();
9412 return ExprError();
9413 }
9414
9415 /// Rebuild an expression which simply semantically wraps another
9416 /// expression which it shares the type and value kind of.
9417 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9418 ExprResult subResult = Visit(expr->getSubExpr());
9419 if (subResult.isInvalid()) return ExprError();
9420
9421 Expr *subExpr = subResult.take();
9422 expr->setSubExpr(subExpr);
9423 expr->setType(subExpr->getType());
9424 expr->setValueKind(subExpr->getValueKind());
9425 assert(expr->getObjectKind() == OK_Ordinary);
9426 return expr;
9427 }
9428
9429 ExprResult VisitParenExpr(ParenExpr *paren) {
9430 return rebuildSugarExpr(paren);
9431 }
9432
9433 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9434 return rebuildSugarExpr(op);
9435 }
9436
9437 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9438 ExprResult subResult = Visit(op->getSubExpr());
9439 if (subResult.isInvalid()) return ExprError();
9440
9441 Expr *subExpr = subResult.take();
9442 op->setSubExpr(subExpr);
9443 op->setType(S.Context.getPointerType(subExpr->getType()));
9444 assert(op->getValueKind() == VK_RValue);
9445 assert(op->getObjectKind() == OK_Ordinary);
9446 return op;
9447 }
9448
9449 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9450 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9451
9452 expr->setType(decl->getType());
9453
9454 assert(expr->getValueKind() == VK_RValue);
9455 if (S.getLangOptions().CPlusPlus &&
9456 !(isa<CXXMethodDecl>(decl) &&
9457 cast<CXXMethodDecl>(decl)->isInstance()))
9458 expr->setValueKind(VK_LValue);
9459
9460 return expr;
9461 }
9462
9463 ExprResult VisitMemberExpr(MemberExpr *mem) {
9464 return resolveDecl(mem, mem->getMemberDecl());
9465 }
9466
9467 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9468 return resolveDecl(ref, ref->getDecl());
9469 }
9470 };
9471}
9472
9473/// Given a function expression of unknown-any type, try to rebuild it
9474/// to have a function type.
9475static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9476 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9477 if (result.isInvalid()) return ExprError();
9478 return S.DefaultFunctionArrayConversion(result.take());
9479}
9480
9481namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009482 /// A visitor for rebuilding an expression of type __unknown_anytype
9483 /// into one which resolves the type directly on the referring
9484 /// expression. Strict preservation of the original source
9485 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009486 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009487 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009488
9489 Sema &S;
9490
9491 /// The current destination type.
9492 QualType DestType;
9493
9494 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9495 : S(S), DestType(castType) {}
9496
John McCall39439732011-04-09 22:50:59 +00009497 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009498 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009499 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009500 }
9501
John McCall2d2e8702011-04-11 07:02:50 +00009502 ExprResult VisitExpr(Expr *expr) {
9503 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9504 << expr->getSourceRange();
9505 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009506 }
9507
John McCall2d2e8702011-04-11 07:02:50 +00009508 ExprResult VisitCallExpr(CallExpr *call);
9509 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9510
John McCall39439732011-04-09 22:50:59 +00009511 /// Rebuild an expression which simply semantically wraps another
9512 /// expression which it shares the type and value kind of.
9513 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9514 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009515 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009516 Expr *subExpr = subResult.take();
9517 expr->setSubExpr(subExpr);
9518 expr->setType(subExpr->getType());
9519 expr->setValueKind(subExpr->getValueKind());
9520 assert(expr->getObjectKind() == OK_Ordinary);
9521 return expr;
9522 }
John McCall31996342011-04-07 08:22:57 +00009523
John McCall39439732011-04-09 22:50:59 +00009524 ExprResult VisitParenExpr(ParenExpr *paren) {
9525 return rebuildSugarExpr(paren);
9526 }
9527
9528 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9529 return rebuildSugarExpr(op);
9530 }
9531
John McCall2979fe02011-04-12 00:42:48 +00009532 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9533 const PointerType *ptr = DestType->getAs<PointerType>();
9534 if (!ptr) {
9535 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9536 << op->getSourceRange();
9537 return ExprError();
9538 }
9539 assert(op->getValueKind() == VK_RValue);
9540 assert(op->getObjectKind() == OK_Ordinary);
9541 op->setType(DestType);
9542
9543 // Build the sub-expression as if it were an object of the pointee type.
9544 DestType = ptr->getPointeeType();
9545 ExprResult subResult = Visit(op->getSubExpr());
9546 if (subResult.isInvalid()) return ExprError();
9547 op->setSubExpr(subResult.take());
9548 return op;
9549 }
9550
John McCall2d2e8702011-04-11 07:02:50 +00009551 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009552
John McCall2979fe02011-04-12 00:42:48 +00009553 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009554
John McCall2979fe02011-04-12 00:42:48 +00009555 ExprResult VisitMemberExpr(MemberExpr *mem) {
9556 return resolveDecl(mem, mem->getMemberDecl());
9557 }
John McCall39439732011-04-09 22:50:59 +00009558
9559 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009560 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009561 }
9562 };
9563}
9564
John McCall2d2e8702011-04-11 07:02:50 +00009565/// Rebuilds a call expression which yielded __unknown_anytype.
9566ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9567 Expr *callee = call->getCallee();
9568
9569 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009570 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009571 FK_FunctionPointer,
9572 FK_BlockPointer
9573 };
9574
9575 FnKind kind;
9576 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009577 if (type == S.Context.BoundMemberTy) {
9578 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9579 kind = FK_MemberFunction;
9580 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009581 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9582 type = ptr->getPointeeType();
9583 kind = FK_FunctionPointer;
9584 } else {
9585 type = type->castAs<BlockPointerType>()->getPointeeType();
9586 kind = FK_BlockPointer;
9587 }
9588 const FunctionType *fnType = type->castAs<FunctionType>();
9589
9590 // Verify that this is a legal result type of a function.
9591 if (DestType->isArrayType() || DestType->isFunctionType()) {
9592 unsigned diagID = diag::err_func_returning_array_function;
9593 if (kind == FK_BlockPointer)
9594 diagID = diag::err_block_returning_array_function;
9595
9596 S.Diag(call->getExprLoc(), diagID)
9597 << DestType->isFunctionType() << DestType;
9598 return ExprError();
9599 }
9600
9601 // Otherwise, go ahead and set DestType as the call's result.
9602 call->setType(DestType.getNonLValueExprType(S.Context));
9603 call->setValueKind(Expr::getValueKindForType(DestType));
9604 assert(call->getObjectKind() == OK_Ordinary);
9605
9606 // Rebuild the function type, replacing the result type with DestType.
9607 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9608 DestType = S.Context.getFunctionType(DestType,
9609 proto->arg_type_begin(),
9610 proto->getNumArgs(),
9611 proto->getExtProtoInfo());
9612 else
9613 DestType = S.Context.getFunctionNoProtoType(DestType,
9614 fnType->getExtInfo());
9615
9616 // Rebuild the appropriate pointer-to-function type.
9617 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009618 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009619 // Nothing to do.
9620 break;
9621
9622 case FK_FunctionPointer:
9623 DestType = S.Context.getPointerType(DestType);
9624 break;
9625
9626 case FK_BlockPointer:
9627 DestType = S.Context.getBlockPointerType(DestType);
9628 break;
9629 }
9630
9631 // Finally, we can recurse.
9632 ExprResult calleeResult = Visit(callee);
9633 if (!calleeResult.isUsable()) return ExprError();
9634 call->setCallee(calleeResult.take());
9635
9636 // Bind a temporary if necessary.
9637 return S.MaybeBindToTemporary(call);
9638}
9639
9640ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009641 // Verify that this is a legal result type of a call.
9642 if (DestType->isArrayType() || DestType->isFunctionType()) {
9643 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9644 << DestType->isFunctionType() << DestType;
9645 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009646 }
9647
John McCall3f4138c2011-07-13 17:56:40 +00009648 // Rewrite the method result type if available.
9649 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9650 assert(method->getResultType() == S.Context.UnknownAnyTy);
9651 method->setResultType(DestType);
9652 }
John McCall2979fe02011-04-12 00:42:48 +00009653
John McCall2d2e8702011-04-11 07:02:50 +00009654 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009655 msg->setType(DestType.getNonReferenceType());
9656 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009657
John McCall2979fe02011-04-12 00:42:48 +00009658 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009659}
9660
9661ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009662 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009663 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009664 assert(ice->getValueKind() == VK_RValue);
9665 assert(ice->getObjectKind() == OK_Ordinary);
9666
John McCall2979fe02011-04-12 00:42:48 +00009667 ice->setType(DestType);
9668
John McCall2d2e8702011-04-11 07:02:50 +00009669 // Rebuild the sub-expression as the pointee (function) type.
9670 DestType = DestType->castAs<PointerType>()->getPointeeType();
9671
9672 ExprResult result = Visit(ice->getSubExpr());
9673 if (!result.isUsable()) return ExprError();
9674
9675 ice->setSubExpr(result.take());
9676 return S.Owned(ice);
9677}
9678
John McCall2979fe02011-04-12 00:42:48 +00009679ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009680 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009681 QualType type = DestType;
9682
9683 // We know how to make this work for certain kinds of decls:
9684
9685 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009686 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009687 // This is true because FunctionDecls must always have function
9688 // type, so we can't be resolving the entire thing at once.
9689 assert(type->isFunctionType());
9690
John McCall4adb38c2011-04-27 00:36:17 +00009691 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9692 if (method->isInstance()) {
9693 valueKind = VK_RValue;
9694 type = S.Context.BoundMemberTy;
9695 }
9696
John McCall2d2e8702011-04-11 07:02:50 +00009697 // Function references aren't l-values in C.
9698 if (!S.getLangOptions().CPlusPlus)
9699 valueKind = VK_RValue;
9700
9701 // - variables
9702 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009703 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9704 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009705 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009706 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9707 << decl << expr->getSourceRange();
9708 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009709 }
9710
9711 // - nothing else
9712 } else {
9713 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9714 << decl << expr->getSourceRange();
9715 return ExprError();
9716 }
9717
John McCall2979fe02011-04-12 00:42:48 +00009718 decl->setType(DestType);
9719 expr->setType(type);
9720 expr->setValueKind(valueKind);
9721 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009722}
9723
John McCall31996342011-04-07 08:22:57 +00009724/// Check a cast of an unknown-any type. We intentionally only
9725/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009726ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9727 Expr *castExpr, CastKind &castKind,
9728 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009729 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009730 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9731 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009732
John McCall39439732011-04-09 22:50:59 +00009733 castExpr = result.take();
9734 VK = castExpr->getValueKind();
9735 castKind = CK_NoOp;
9736
9737 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009738}
9739
9740static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9741 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009742 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009743 while (true) {
9744 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009745 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009746 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009747 diagID = diag::err_uncasted_call_of_unknown_any;
9748 } else {
John McCall31996342011-04-07 08:22:57 +00009749 break;
John McCall2d2e8702011-04-11 07:02:50 +00009750 }
John McCall31996342011-04-07 08:22:57 +00009751 }
9752
John McCall2d2e8702011-04-11 07:02:50 +00009753 SourceLocation loc;
9754 NamedDecl *d;
9755 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9756 loc = ref->getLocation();
9757 d = ref->getDecl();
9758 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9759 loc = mem->getMemberLoc();
9760 d = mem->getMemberDecl();
9761 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9762 diagID = diag::err_uncasted_call_of_unknown_any;
9763 loc = msg->getSelectorLoc();
9764 d = msg->getMethodDecl();
9765 assert(d && "unknown method returning __unknown_any?");
9766 } else {
9767 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9768 << e->getSourceRange();
9769 return ExprError();
9770 }
9771
9772 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009773
9774 // Never recoverable.
9775 return ExprError();
9776}
9777
John McCall36e7fe32010-10-12 00:20:44 +00009778/// Check for operands with placeholder types and complain if found.
9779/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009780ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009781 // Placeholder types are always *exactly* the appropriate builtin type.
9782 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009783
John McCall31996342011-04-07 08:22:57 +00009784 // Overloaded expressions.
9785 if (type == Context.OverloadTy)
9786 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009787 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009788 QualType(),
9789 diag::err_ovl_unresolvable);
9790
John McCall0009fcc2011-04-26 20:42:42 +00009791 // Bound member functions.
9792 if (type == Context.BoundMemberTy) {
9793 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9794 << E->getSourceRange();
9795 return ExprError();
9796 }
9797
John McCall31996342011-04-07 08:22:57 +00009798 // Expressions of unknown type.
9799 if (type == Context.UnknownAnyTy)
9800 return diagnoseUnknownAnyExpr(*this, E);
9801
9802 assert(!type->isPlaceholderType());
9803 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009804}
Richard Trieu2c850c02011-04-21 21:44:26 +00009805
9806bool Sema::CheckCaseExpression(Expr *expr) {
9807 if (expr->isTypeDependent())
9808 return true;
9809 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9810 return expr->getType()->isIntegralOrEnumerationType();
9811 return false;
9812}