blob: 44a82c0aa3885febe215f792f27f5d8329812678 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000161
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000246 SourceLocation MissingNilLoc
247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
248 std::string NullValue;
249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition())
250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
253 else if (Context.getTypeSize(Context.IntTy)
254 == Context.getTypeSize(Context.getSizeType()))
255 NullValue = "0";
256 else
257 NullValue = "0L";
258
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << isMethod
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall7ddbcf42010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000263}
264
Douglas Gregor87f95b02009-02-26 21:00:50 +0000265SourceRange Sema::getExprRange(ExprTy *E) const {
266 Expr *Ex = (Expr *)E;
267 return Ex? Ex->getSourceRange() : SourceRange();
268}
269
Chris Lattner513165e2008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattner513165e2008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattner513165e2008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000282 else if (Ty->isArrayType()) {
283 // In C90 mode, arrays only promote to pointers if the array expression is
284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
285 // type 'array of type' is converted to an expression that has type 'pointer
286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
287 // that has type 'array of type' ...". The relevant change is "an lvalue"
288 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000289 //
290 // C++ 4.2p1:
291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
292 // T" can be converted to an rvalue of type "pointer to T".
293 //
John McCall086a4642010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000297 }
John Wiegley01296292011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000301static void CheckForNullPointerDereference(Sema &S, Expr *E) {
302 // Check to see if we are dereferencing a null pointer. If so,
303 // and if not volatile-qualified, this is undefined behavior that the
304 // optimizer will delete, so warn about it. People sometimes try to use this
305 // to get a deterministic trap and are surprised by clang's behavior. This
306 // only handles the pattern "*null", which is a very syntactic check.
307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
308 if (UO->getOpcode() == UO_Deref &&
309 UO->getSubExpr()->IgnoreParenCasts()->
310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
311 !UO->getType().isVolatileQualified()) {
312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
313 S.PDiag(diag::warn_indirection_through_null)
314 << UO->getSubExpr()->getSourceRange());
315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
316 S.PDiag(diag::note_indirection_through_null));
317 }
318}
319
John Wiegley01296292011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000321 // C++ [conv.lval]p1:
322 // A glvalue of a non-function, non-array type T can be
323 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000325
John McCall27584242010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000328
John McCall27584242010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000337 }
John McCall27584242010-12-06 20:48:59 +0000338
339 // We don't want to throw lvalue-to-rvalue casts on top of
340 // expressions of certain types in C++.
341 if (getLangOptions().CPlusPlus &&
342 (E->getType() == Context.OverloadTy ||
343 T->isDependentType() ||
344 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000345 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000346
347 // The C standard is actually really unclear on this point, and
348 // DR106 tells us what the result should be but not why. It's
349 // generally best to say that void types just doesn't undergo
350 // lvalue-to-rvalue at all. Note that expressions of unqualified
351 // 'void' type are never l-values, but qualified void can be.
352 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000353 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000354
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall27584242010-12-06 20:48:59 +0000357 // C++ [conv.lval]p1:
358 // [...] If T is a non-class type, the type of the prvalue is the
359 // cv-unqualified version of T. Otherwise, the type of the
360 // rvalue is T.
361 //
362 // C99 6.3.2.1p2:
363 // If the lvalue has qualified type, the value has the unqualified
364 // version of the type of the lvalue; otherwise, the value has the
365 // type of the lvalue.
366 if (T.hasQualifiers())
367 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000368
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000371}
372
John Wiegley01296292011-04-08 18:41:53 +0000373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
374 ExprResult Res = DefaultFunctionArrayConversion(E);
375 if (Res.isInvalid())
376 return ExprError();
377 Res = DefaultLvalueConversion(Res.take());
378 if (Res.isInvalid())
379 return ExprError();
380 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000381}
382
383
Chris Lattner513165e2008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000387/// apply if the array is an argument to the sizeof or address (&) operators.
388/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000398
399 // Try to perform integral promotions if the object has a theoretically
400 // promotable type.
401 if (Ty->isIntegralOrUnscopedEnumerationType()) {
402 // C99 6.3.1.1p2:
403 //
404 // The following may be used in an expression wherever an int or
405 // unsigned int may be used:
406 // - an object or expression with an integer type whose integer
407 // conversion rank is less than or equal to the rank of int
408 // and unsigned int.
409 // - A bit-field of type _Bool, int, signed int, or unsigned int.
410 //
411 // If an int can represent all values of the original type, the
412 // value is converted to an int; otherwise, it is converted to an
413 // unsigned int. These are called the integer promotions. All
414 // other types are unchanged by the integer promotions.
415
416 QualType PTy = Context.isPromotableBitField(E);
417 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000425 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000426 }
John Wiegley01296292011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000428}
429
Chris Lattner2ce500f2008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000436
John Wiegley01296292011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000441
Chris Lattner2ce500f2008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
John McCall4bb057d2011-08-27 22:06:17 +0000446 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000447 // promotion, even on class types, but note:
448 // C++11 [conv.lval]p2:
449 // When an lvalue-to-rvalue conversion occurs in an unevaluated
450 // operand or a subexpression thereof the value contained in the
451 // referenced object is not accessed. Otherwise, if the glvalue
452 // has a class type, the conversion copy-initializes a temporary
453 // of type T from the glvalue and the result of the conversion
454 // is a prvalue for the temporary.
455 // FIXME: add some way to gate this entire thing for correctness in
456 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000457 if (getLangOptions().CPlusPlus && E->isGLValue() &&
458 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000459 ExprResult Temp = PerformCopyInitialization(
460 InitializedEntity::InitializeTemporary(E->getType()),
461 E->getExprLoc(),
462 Owned(E));
463 if (Temp.isInvalid())
464 return ExprError();
465 E = Temp.get();
466 }
467
John Wiegley01296292011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000469}
470
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000471/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
472/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000473/// interfaces passed by value.
474ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000475 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000476 ExprResult ExprRes = CheckPlaceholderExpr(E);
477 if (ExprRes.isInvalid())
478 return ExprError();
479
480 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000481 if (ExprRes.isInvalid())
482 return ExprError();
483 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregor347e0f22011-05-21 19:26:31 +0000485 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000486 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000487 DiagRuntimeBehavior(E->getLocStart(), 0,
488 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
489 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000490 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000491
John McCall31168b02011-06-15 23:02:42 +0000492 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000493 // C++0x [expr.call]p7:
494 // Passing a potentially-evaluated argument of class type (Clause 9)
495 // having a non-trivial copy constructor, a non-trivial move constructor,
496 // or a non-trivial destructor, with no corresponding parameter,
497 // is conditionally-supported with implementation-defined semantics.
498 bool TrivialEnough = false;
499 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
500 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
501 if (Record->hasTrivialCopyConstructor() &&
502 Record->hasTrivialMoveConstructor() &&
503 Record->hasTrivialDestructor())
504 TrivialEnough = true;
505 }
506 }
John McCall31168b02011-06-15 23:02:42 +0000507
508 if (!TrivialEnough &&
509 getLangOptions().ObjCAutoRefCount &&
510 E->getType()->isObjCLifetimeType())
511 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000512
513 if (TrivialEnough) {
514 // Nothing to diagnose. This is okay.
515 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000516 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000517 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000518 << CT)) {
519 // Turn this into a trap.
520 CXXScopeSpec SS;
521 UnqualifiedId Name;
522 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
523 E->getLocStart());
524 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
525 if (TrapFn.isInvalid())
526 return ExprError();
527
528 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
529 MultiExprArg(), E->getLocEnd());
530 if (Call.isInvalid())
531 return ExprError();
532
533 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
534 Call.get(), E);
535 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000536 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000537 E = Comma.get();
538 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000539 }
540
John Wiegley01296292011-04-08 18:41:53 +0000541 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000542}
543
Richard Trieu7aa58f12011-09-02 20:58:51 +0000544/// \brief Converts an integer to complex float type. Helper function of
545/// UsualArithmeticConversions()
546///
547/// \return false if the integer expression is an integer type and is
548/// successfully converted to the complex type.
549static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &intExpr,
550 ExprResult &complexExpr,
551 QualType intTy,
552 QualType complexTy,
553 bool skipCast) {
554 if (intTy->isComplexType() || intTy->isRealFloatingType()) return true;
555 if (skipCast) return false;
556 if (intTy->isIntegerType()) {
557 QualType fpTy = cast<ComplexType>(complexTy)->getElementType();
558 intExpr = S.ImpCastExprToType(intExpr.take(), fpTy, CK_IntegralToFloating);
559 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
560 CK_FloatingRealToComplex);
561 } else {
562 assert(intTy->isComplexIntegerType());
563 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
564 CK_IntegralComplexToFloatingComplex);
565 }
566 return false;
567}
568
569/// \brief Takes two complex float types and converts them to the same type.
570/// Helper function of UsualArithmeticConversions()
571static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000572handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
573 ExprResult &RHS, QualType LHSType,
574 QualType RHSType,
575 bool isCompAssign) {
576 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000577
578 if (order < 0) {
579 // _Complex float -> _Complex double
580 if (!isCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000581 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
582 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000583 }
584 if (order > 0)
585 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000586 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
587 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000588}
589
590/// \brief Converts otherExpr to complex float and promotes complexExpr if
591/// necessary. Helper function of UsualArithmeticConversions()
592static QualType handleOtherComplexFloatConversion(Sema &S,
593 ExprResult &complexExpr,
594 ExprResult &otherExpr,
595 QualType complexTy,
596 QualType otherTy,
597 bool convertComplexExpr,
598 bool convertOtherExpr) {
599 int order = S.Context.getFloatingTypeOrder(complexTy, otherTy);
600
601 // If just the complexExpr is complex, the otherExpr needs to be converted,
602 // and the complexExpr might need to be promoted.
603 if (order > 0) { // complexExpr is wider
604 // float -> _Complex double
605 if (convertOtherExpr) {
606 QualType fp = cast<ComplexType>(complexTy)->getElementType();
607 otherExpr = S.ImpCastExprToType(otherExpr.take(), fp, CK_FloatingCast);
608 otherExpr = S.ImpCastExprToType(otherExpr.take(), complexTy,
609 CK_FloatingRealToComplex);
610 }
611 return complexTy;
612 }
613
614 // otherTy is at least as wide. Find its corresponding complex type.
615 QualType result = (order == 0 ? complexTy :
616 S.Context.getComplexType(otherTy));
617
618 // double -> _Complex double
619 if (convertOtherExpr)
620 otherExpr = S.ImpCastExprToType(otherExpr.take(), result,
621 CK_FloatingRealToComplex);
622
623 // _Complex float -> _Complex double
624 if (convertComplexExpr && order < 0)
625 complexExpr = S.ImpCastExprToType(complexExpr.take(), result,
626 CK_FloatingComplexCast);
627
628 return result;
629}
630
631/// \brief Handle arithmetic conversion with complex types. Helper function of
632/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000633static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
634 ExprResult &RHS, QualType LHSType,
635 QualType RHSType,
636 bool isCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000637 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000638 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000639 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000640 return LHSType;
641 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000642 /*skipCast*/isCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000643 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000644
645 // This handles complex/complex, complex/float, or float/complex.
646 // When both operands are complex, the shorter operand is converted to the
647 // type of the longer, and that is the type of the result. This corresponds
648 // to what is done when combining two real floating-point operands.
649 // The fun begins when size promotion occur across type domains.
650 // From H&S 6.3.4: When one operand is complex and the other is a real
651 // floating-point type, the less precise type is converted, within it's
652 // real or complex domain, to the precision of the other type. For example,
653 // when combining a "long double" with a "double _Complex", the
654 // "double _Complex" is promoted to "long double _Complex".
655
Richard Trieu5065cdd2011-09-06 18:25:09 +0000656 bool LHSComplexFloat = LHSType->isComplexType();
657 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000658
659 // If both are complex, just cast to the more precise type.
660 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000661 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
662 LHSType, RHSType,
663 isCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000664
665 // If only one operand is complex, promote it if necessary and convert the
666 // other operand to complex.
667 if (LHSComplexFloat)
668 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000669 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!isCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000670 /*convertOtherExpr*/ true);
671
672 assert(RHSComplexFloat);
673 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000674 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675 /*convertOtherExpr*/ !isCompAssign);
676}
677
678/// \brief Hande arithmetic conversion from integer to float. Helper function
679/// of UsualArithmeticConversions()
680static QualType handleIntToFloatConversion(Sema &S, ExprResult &floatExpr,
681 ExprResult &intExpr,
682 QualType floatTy, QualType intTy,
683 bool convertFloat, bool convertInt) {
684 if (intTy->isIntegerType()) {
685 if (convertInt)
686 // Convert intExpr to the lhs floating point type.
687 intExpr = S.ImpCastExprToType(intExpr.take(), floatTy,
688 CK_IntegralToFloating);
689 return floatTy;
690 }
691
692 // Convert both sides to the appropriate complex float.
693 assert(intTy->isComplexIntegerType());
694 QualType result = S.Context.getComplexType(floatTy);
695
696 // _Complex int -> _Complex float
697 if (convertInt)
698 intExpr = S.ImpCastExprToType(intExpr.take(), result,
699 CK_IntegralComplexToFloatingComplex);
700
701 // float -> _Complex float
702 if (convertFloat)
703 floatExpr = S.ImpCastExprToType(floatExpr.take(), result,
704 CK_FloatingRealToComplex);
705
706 return result;
707}
708
709/// \brief Handle arithmethic conversion with floating point types. Helper
710/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000711static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
712 ExprResult &RHS, QualType LHSType,
713 QualType RHSType, bool isCompAssign) {
714 bool LHSFloat = LHSType->isRealFloatingType();
715 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000716
717 // If we have two real floating types, convert the smaller operand
718 // to the bigger result.
719 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000720 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000721 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000722 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
723 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000724 }
725
726 assert(order < 0 && "illegal float comparison");
727 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000728 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
729 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000730 }
731
732 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000733 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000734 /*convertFloat=*/!isCompAssign,
735 /*convertInt=*/ true);
736 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000737 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000738 /*convertInt=*/ true,
739 /*convertFloat=*/!isCompAssign);
740}
741
742/// \brief Handle conversions with GCC complex int extension. Helper function
743/// of UsualArithmeticConverions()
744// FIXME: if the operands are (int, _Complex long), we currently
745// don't promote the complex. Also, signedness?
Richard Trieucfe3f212011-09-06 18:38:41 +0000746static QualType handleComplexIntConvsersion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
749 bool isCompAssign) {
750 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
751 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000752
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 if (LHSComplexInt && RHSComplexInt) {
754 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
755 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000756 assert(order && "inequal types with equal element ordering");
757 if (order > 0) {
758 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000759 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
760 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000761 }
762
763 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000764 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
765 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000766 }
767
Richard Trieucfe3f212011-09-06 18:38:41 +0000768 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000769 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000770 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
771 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772 }
773
Richard Trieucfe3f212011-09-06 18:38:41 +0000774 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000775 // int -> _Complex int
776 if (!isCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000777 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
778 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779}
780
781/// \brief Handle integer arithmetic conversions. Helper function of
782/// UsualArithmeticConversions()
783static QualType handleIntegerConversion(Sema &S, ExprResult &lhsExpr,
784 ExprResult &rhsExpr, QualType lhs,
785 QualType rhs, bool isCompAssign) {
786 // The rules for this case are in C99 6.3.1.8
787 int order = S.Context.getIntegerTypeOrder(lhs, rhs);
788 bool lhsSigned = lhs->hasSignedIntegerRepresentation();
789 bool rhsSigned = rhs->hasSignedIntegerRepresentation();
790 if (lhsSigned == rhsSigned) {
791 // Same signedness; use the higher-ranked type
792 if (order >= 0) {
793 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
794 return lhs;
795 } else if (!isCompAssign)
796 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
797 return rhs;
798 } else if (order != (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) {
802 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
803 return lhs;
804 } else if (!isCompAssign)
805 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
806 return rhs;
807 } else if (S.Context.getIntWidth(lhs) != S.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) {
812 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
813 return lhs;
814 } else if (!isCompAssign)
815 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
816 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 S.Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
824 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
825 if (!isCompAssign)
826 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
827 return result;
828 }
829}
830
Chris Lattner513165e2008-07-25 21:10:04 +0000831/// UsualArithmeticConversions - Performs various conversions that are common to
832/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000833/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000834/// responsible for emitting appropriate error diagnostics.
835/// FIXME: verify the conversion rules for "complex int" are consistent with
836/// GCC.
Richard Trieucfc491d2011-08-02 04:35:43 +0000837QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
838 ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000839 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000840 if (!isCompAssign) {
841 lhsExpr = UsualUnaryConversions(lhsExpr.take());
842 if (lhsExpr.isInvalid())
843 return QualType();
844 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000845
John Wiegley01296292011-04-08 18:41:53 +0000846 rhsExpr = UsualUnaryConversions(rhsExpr.take());
847 if (rhsExpr.isInvalid())
848 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000849
Mike Stump11289f42009-09-09 15:08:12 +0000850 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000851 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000852 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000853 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000854 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000855 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000856
857 // If both types are identical, no conversion is needed.
858 if (lhs == rhs)
859 return lhs;
860
861 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
862 // The caller can deal with this (e.g. pointer + int).
863 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
864 return lhs;
865
John McCalld005ac92010-11-13 08:17:45 +0000866 // Apply unary and bitfield promotions to the LHS's type.
867 QualType lhs_unpromoted = lhs;
868 if (lhs->isPromotableIntegerType())
869 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000870 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000871 if (!LHSBitfieldPromoteTy.isNull())
872 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000873 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000874 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000875
John McCalld005ac92010-11-13 08:17:45 +0000876 // If both types are identical, no conversion is needed.
877 if (lhs == rhs)
878 return lhs;
879
880 // At this point, we have two different arithmetic types.
881
882 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 if (lhs->isComplexType() || rhs->isComplexType())
884 return handleComplexFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
885 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000886
887 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu7aa58f12011-09-02 20:58:51 +0000888 if (lhs->isRealFloatingType() || rhs->isRealFloatingType())
889 return handleFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
890 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000891
892 // Handle GCC complex int extension.
Richard Trieu7aa58f12011-09-02 20:58:51 +0000893 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType())
894 return handleComplexIntConvsersion(*this, lhsExpr, rhsExpr, lhs, rhs,
895 isCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000896
897 // Finally, we have two differing integer types.
Richard Trieu7aa58f12011-09-02 20:58:51 +0000898 return handleIntegerConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
899 isCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000900}
901
Chris Lattner513165e2008-07-25 21:10:04 +0000902//===----------------------------------------------------------------------===//
903// Semantic Analysis for various Expression Types
904//===----------------------------------------------------------------------===//
905
906
Peter Collingbourne91147592011-04-15 00:35:48 +0000907ExprResult
908Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
909 SourceLocation DefaultLoc,
910 SourceLocation RParenLoc,
911 Expr *ControllingExpr,
912 MultiTypeArg types,
913 MultiExprArg exprs) {
914 unsigned NumAssocs = types.size();
915 assert(NumAssocs == exprs.size());
916
917 ParsedType *ParsedTypes = types.release();
918 Expr **Exprs = exprs.release();
919
920 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
921 for (unsigned i = 0; i < NumAssocs; ++i) {
922 if (ParsedTypes[i])
923 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
924 else
925 Types[i] = 0;
926 }
927
928 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
929 ControllingExpr, Types, Exprs,
930 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000931 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000932 return ER;
933}
934
935ExprResult
936Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
937 SourceLocation DefaultLoc,
938 SourceLocation RParenLoc,
939 Expr *ControllingExpr,
940 TypeSourceInfo **Types,
941 Expr **Exprs,
942 unsigned NumAssocs) {
943 bool TypeErrorFound = false,
944 IsResultDependent = ControllingExpr->isTypeDependent(),
945 ContainsUnexpandedParameterPack
946 = ControllingExpr->containsUnexpandedParameterPack();
947
948 for (unsigned i = 0; i < NumAssocs; ++i) {
949 if (Exprs[i]->containsUnexpandedParameterPack())
950 ContainsUnexpandedParameterPack = true;
951
952 if (Types[i]) {
953 if (Types[i]->getType()->containsUnexpandedParameterPack())
954 ContainsUnexpandedParameterPack = true;
955
956 if (Types[i]->getType()->isDependentType()) {
957 IsResultDependent = true;
958 } else {
959 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
960 // complete object type other than a variably modified type."
961 unsigned D = 0;
962 if (Types[i]->getType()->isIncompleteType())
963 D = diag::err_assoc_type_incomplete;
964 else if (!Types[i]->getType()->isObjectType())
965 D = diag::err_assoc_type_nonobject;
966 else if (Types[i]->getType()->isVariablyModifiedType())
967 D = diag::err_assoc_type_variably_modified;
968
969 if (D != 0) {
970 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
971 << Types[i]->getTypeLoc().getSourceRange()
972 << Types[i]->getType();
973 TypeErrorFound = true;
974 }
975
976 // C1X 6.5.1.1p2 "No two generic associations in the same generic
977 // selection shall specify compatible types."
978 for (unsigned j = i+1; j < NumAssocs; ++j)
979 if (Types[j] && !Types[j]->getType()->isDependentType() &&
980 Context.typesAreCompatible(Types[i]->getType(),
981 Types[j]->getType())) {
982 Diag(Types[j]->getTypeLoc().getBeginLoc(),
983 diag::err_assoc_compatible_types)
984 << Types[j]->getTypeLoc().getSourceRange()
985 << Types[j]->getType()
986 << Types[i]->getType();
987 Diag(Types[i]->getTypeLoc().getBeginLoc(),
988 diag::note_compat_assoc)
989 << Types[i]->getTypeLoc().getSourceRange()
990 << Types[i]->getType();
991 TypeErrorFound = true;
992 }
993 }
994 }
995 }
996 if (TypeErrorFound)
997 return ExprError();
998
999 // If we determined that the generic selection is result-dependent, don't
1000 // try to compute the result expression.
1001 if (IsResultDependent)
1002 return Owned(new (Context) GenericSelectionExpr(
1003 Context, KeyLoc, ControllingExpr,
1004 Types, Exprs, NumAssocs, DefaultLoc,
1005 RParenLoc, ContainsUnexpandedParameterPack));
1006
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001007 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001008 unsigned DefaultIndex = -1U;
1009 for (unsigned i = 0; i < NumAssocs; ++i) {
1010 if (!Types[i])
1011 DefaultIndex = i;
1012 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1013 Types[i]->getType()))
1014 CompatIndices.push_back(i);
1015 }
1016
1017 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1018 // type compatible with at most one of the types named in its generic
1019 // association list."
1020 if (CompatIndices.size() > 1) {
1021 // We strip parens here because the controlling expression is typically
1022 // parenthesized in macro definitions.
1023 ControllingExpr = ControllingExpr->IgnoreParens();
1024 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1025 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1026 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001027 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001028 E = CompatIndices.end(); I != E; ++I) {
1029 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1030 diag::note_compat_assoc)
1031 << Types[*I]->getTypeLoc().getSourceRange()
1032 << Types[*I]->getType();
1033 }
1034 return ExprError();
1035 }
1036
1037 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1038 // its controlling expression shall have type compatible with exactly one of
1039 // the types named in its generic association list."
1040 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1041 // We strip parens here because the controlling expression is typically
1042 // parenthesized in macro definitions.
1043 ControllingExpr = ControllingExpr->IgnoreParens();
1044 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1045 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1046 return ExprError();
1047 }
1048
1049 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1050 // type name that is compatible with the type of the controlling expression,
1051 // then the result expression of the generic selection is the expression
1052 // in that generic association. Otherwise, the result expression of the
1053 // generic selection is the expression in the default generic association."
1054 unsigned ResultIndex =
1055 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1056
1057 return Owned(new (Context) GenericSelectionExpr(
1058 Context, KeyLoc, ControllingExpr,
1059 Types, Exprs, NumAssocs, DefaultLoc,
1060 RParenLoc, ContainsUnexpandedParameterPack,
1061 ResultIndex));
1062}
1063
Steve Naroff83895f72007-09-16 03:34:24 +00001064/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001065/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1066/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1067/// multiple tokens. However, the common case is that StringToks points to one
1068/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001069///
John McCalldadc5752010-08-24 06:29:42 +00001070ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001071Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001072 assert(NumStringToks && "Must have at least one string!");
1073
Chris Lattner8a24e582009-01-16 18:51:42 +00001074 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001075 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001076 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001077
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001078 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001079 for (unsigned i = 0; i != NumStringToks; ++i)
1080 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001081
Chris Lattner36fc8792008-02-11 00:02:17 +00001082 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001083 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001084 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001085 else if (Literal.isUTF16())
1086 StrTy = Context.Char16Ty;
1087 else if (Literal.isUTF32())
1088 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001089 else if (Literal.Pascal)
1090 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001091
Douglas Gregorfb65e592011-07-27 05:40:30 +00001092 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1093 if (Literal.isWide())
1094 Kind = StringLiteral::Wide;
1095 else if (Literal.isUTF8())
1096 Kind = StringLiteral::UTF8;
1097 else if (Literal.isUTF16())
1098 Kind = StringLiteral::UTF16;
1099 else if (Literal.isUTF32())
1100 Kind = StringLiteral::UTF32;
1101
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001102 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001103 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001104 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001105
Chris Lattner36fc8792008-02-11 00:02:17 +00001106 // Get an array type for the string, according to C99 6.4.5. This includes
1107 // the nul terminator character as well as the string length for pascal
1108 // strings.
1109 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001110 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001111 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattner5b183d82006-11-10 05:03:26 +00001113 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001114 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001115 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001116 &StringTokLocs[0],
1117 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001118}
1119
John McCallc63de662011-02-02 13:00:07 +00001120enum CaptureResult {
1121 /// No capture is required.
1122 CR_NoCapture,
1123
1124 /// A capture is required.
1125 CR_Capture,
1126
John McCall351762c2011-02-07 10:33:21 +00001127 /// A by-ref capture is required.
1128 CR_CaptureByRef,
1129
John McCallc63de662011-02-02 13:00:07 +00001130 /// An error occurred when trying to capture the given variable.
1131 CR_Error
1132};
1133
1134/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001135///
John McCallc63de662011-02-02 13:00:07 +00001136/// \param var - the variable referenced
1137/// \param DC - the context which we couldn't capture through
1138static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001139diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001140 VarDecl *var, DeclContext *DC) {
1141 switch (S.ExprEvalContexts.back().Context) {
1142 case Sema::Unevaluated:
1143 // The argument will never be evaluated, so don't complain.
1144 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001145
John McCallc63de662011-02-02 13:00:07 +00001146 case Sema::PotentiallyEvaluated:
1147 case Sema::PotentiallyEvaluatedIfUsed:
1148 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001149
John McCallc63de662011-02-02 13:00:07 +00001150 case Sema::PotentiallyPotentiallyEvaluated:
1151 // FIXME: delay these!
1152 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
John McCallc63de662011-02-02 13:00:07 +00001155 // Don't diagnose about capture if we're not actually in code right
1156 // now; in general, there are more appropriate places that will
1157 // diagnose this.
1158 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1159
John McCall92d627e2011-03-22 23:15:50 +00001160 // Certain madnesses can happen with parameter declarations, which
1161 // we want to ignore.
1162 if (isa<ParmVarDecl>(var)) {
1163 // - If the parameter still belongs to the translation unit, then
1164 // we're actually just using one parameter in the declaration of
1165 // the next. This is useful in e.g. VLAs.
1166 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1167 return CR_NoCapture;
1168
1169 // - This particular madness can happen in ill-formed default
1170 // arguments; claim it's okay and let downstream code handle it.
1171 if (S.CurContext == var->getDeclContext()->getParent())
1172 return CR_NoCapture;
1173 }
John McCallc63de662011-02-02 13:00:07 +00001174
1175 DeclarationName functionName;
1176 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1177 functionName = fn->getDeclName();
1178 // FIXME: variable from enclosing block that we couldn't capture from!
1179
1180 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1181 << var->getIdentifier() << functionName;
1182 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1183 << var->getIdentifier();
1184
1185 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001186}
1187
John McCall351762c2011-02-07 10:33:21 +00001188/// There is a well-formed capture at a particular scope level;
1189/// propagate it through all the nested blocks.
1190static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1191 const BlockDecl::Capture &capture) {
1192 VarDecl *var = capture.getVariable();
1193
1194 // Update all the inner blocks with the capture information.
1195 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1196 i != e; ++i) {
1197 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1198 innerBlock->Captures.push_back(
1199 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1200 /*nested*/ true, capture.getCopyExpr()));
1201 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1202 }
1203
1204 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1205}
1206
1207/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001208/// given value in the current context requires a variable capture.
1209///
1210/// This also keeps the captures set in the BlockScopeInfo records
1211/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001212static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001213 ValueDecl *value) {
1214 // Only variables ever require capture.
1215 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001216 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001217
1218 // Fast path: variables from the current context never require capture.
1219 DeclContext *DC = S.CurContext;
1220 if (var->getDeclContext() == DC) return CR_NoCapture;
1221
1222 // Only variables with local storage require capture.
1223 // FIXME: What about 'const' variables in C++?
1224 if (!var->hasLocalStorage()) return CR_NoCapture;
1225
1226 // Otherwise, we need to capture.
1227
1228 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001229 do {
1230 // Only blocks (and eventually C++0x closures) can capture; other
1231 // scopes don't work.
1232 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001233 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001234
1235 BlockScopeInfo *blockScope =
1236 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1237 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1238
John McCall351762c2011-02-07 10:33:21 +00001239 // Check whether we've already captured it in this block. If so,
1240 // we're done.
1241 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1242 return propagateCapture(S, functionScopesIndex,
1243 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001244
1245 functionScopesIndex--;
1246 DC = cast<BlockDecl>(DC)->getDeclContext();
1247 } while (var->getDeclContext() != DC);
1248
John McCall351762c2011-02-07 10:33:21 +00001249 // Okay, we descended all the way to the block that defines the variable.
1250 // Actually try to capture it.
1251 QualType type = var->getType();
1252
1253 // Prohibit variably-modified types.
1254 if (type->isVariablyModifiedType()) {
1255 S.Diag(loc, diag::err_ref_vm_type);
1256 S.Diag(var->getLocation(), diag::note_declared_at);
1257 return CR_Error;
1258 }
1259
1260 // Prohibit arrays, even in __block variables, but not references to
1261 // them.
1262 if (type->isArrayType()) {
1263 S.Diag(loc, diag::err_ref_array_type);
1264 S.Diag(var->getLocation(), diag::note_declared_at);
1265 return CR_Error;
1266 }
1267
1268 S.MarkDeclarationReferenced(loc, var);
1269
1270 // The BlocksAttr indicates the variable is bound by-reference.
1271 bool byRef = var->hasAttr<BlocksAttr>();
1272
1273 // Build a copy expression.
1274 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001275 const RecordType *rtype;
1276 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1277 (rtype = type->getAs<RecordType>())) {
1278
1279 // The capture logic needs the destructor, so make sure we mark it.
1280 // Usually this is unnecessary because most local variables have
1281 // their destructors marked at declaration time, but parameters are
1282 // an exception because it's technically only the call site that
1283 // actually requires the destructor.
1284 if (isa<ParmVarDecl>(var))
1285 S.FinalizeVarWithDestructor(var, rtype);
1286
John McCall351762c2011-02-07 10:33:21 +00001287 // According to the blocks spec, the capture of a variable from
1288 // the stack requires a const copy constructor. This is not true
1289 // of the copy/move done to move a __block variable to the heap.
1290 type.addConst();
1291
1292 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1293 ExprResult result =
1294 S.PerformCopyInitialization(
1295 InitializedEntity::InitializeBlock(var->getLocation(),
1296 type, false),
1297 loc, S.Owned(declRef));
1298
1299 // Build a full-expression copy expression if initialization
1300 // succeeded and used a non-trivial constructor. Recover from
1301 // errors by pretending that the copy isn't necessary.
1302 if (!result.isInvalid() &&
1303 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1304 result = S.MaybeCreateExprWithCleanups(result);
1305 copyExpr = result.take();
1306 }
1307 }
1308
1309 // We're currently at the declarer; go back to the closure.
1310 functionScopesIndex++;
1311 BlockScopeInfo *blockScope =
1312 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1313
1314 // Build a valid capture in this scope.
1315 blockScope->Captures.push_back(
1316 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1317 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1318
1319 // Propagate that to inner captures if necessary.
1320 return propagateCapture(S, functionScopesIndex,
1321 blockScope->Captures.back());
1322}
1323
1324static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1325 const DeclarationNameInfo &NameInfo,
1326 bool byRef) {
1327 assert(isa<VarDecl>(vd) && "capturing non-variable");
1328
1329 VarDecl *var = cast<VarDecl>(vd);
1330 assert(var->hasLocalStorage() && "capturing non-local");
1331 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1332
1333 QualType exprType = var->getType().getNonReferenceType();
1334
1335 BlockDeclRefExpr *BDRE;
1336 if (!byRef) {
1337 // The variable will be bound by copy; make it const within the
1338 // closure, but record that this was done in the expression.
1339 bool constAdded = !exprType.isConstQualified();
1340 exprType.addConst();
1341
1342 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1343 NameInfo.getLoc(), false,
1344 constAdded);
1345 } else {
1346 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1347 NameInfo.getLoc(), true);
1348 }
1349
1350 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001351}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001352
John McCalldadc5752010-08-24 06:29:42 +00001353ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001354Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001355 SourceLocation Loc,
1356 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001357 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001358 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001359}
1360
John McCallf4cd4f92011-02-09 01:13:10 +00001361/// BuildDeclRefExpr - Build an expression that references a
1362/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001363ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001364Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001365 const DeclarationNameInfo &NameInfo,
1366 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001367 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCall086a4642010-11-24 05:12:34 +00001369 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001370 SS? SS->getWithLocInContext(Context)
1371 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001372 D, NameInfo, Ty, VK);
1373
1374 // Just in case we're building an illegal pointer-to-member.
1375 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1376 E->setObjectKind(OK_BitField);
1377
1378 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001379}
1380
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001381/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001382/// possibly a list of template arguments.
1383///
1384/// If this produces template arguments, it is permitted to call
1385/// DecomposeTemplateName.
1386///
1387/// This actually loses a lot of source location information for
1388/// non-standard name kinds; we should consider preserving that in
1389/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001390void
1391Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1392 TemplateArgumentListInfo &Buffer,
1393 DeclarationNameInfo &NameInfo,
1394 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001395 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1396 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1397 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1398
Douglas Gregor5476205b2011-06-23 00:49:38 +00001399 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001400 Id.TemplateId->getTemplateArgs(),
1401 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001402 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001403 TemplateArgsPtr.release();
1404
John McCall3e56fd42010-08-23 07:28:44 +00001405 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001406 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001407 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001408 TemplateArgs = &Buffer;
1409 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001410 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001411 TemplateArgs = 0;
1412 }
1413}
1414
John McCalld681c392009-12-16 08:11:27 +00001415/// Diagnose an empty lookup.
1416///
1417/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001418bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001419 CorrectTypoContext CTC,
1420 TemplateArgumentListInfo *ExplicitTemplateArgs,
1421 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001422 DeclarationName Name = R.getLookupName();
1423
John McCalld681c392009-12-16 08:11:27 +00001424 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001425 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001426 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1427 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001428 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001429 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001430 diagnostic_suggest = diag::err_undeclared_use_suggest;
1431 }
John McCalld681c392009-12-16 08:11:27 +00001432
Douglas Gregor598b08f2009-12-31 05:20:13 +00001433 // If the original lookup was an unqualified lookup, fake an
1434 // unqualified lookup. This is useful when (for example) the
1435 // original lookup would not have found something because it was a
1436 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001437 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001438 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001439 if (isa<CXXRecordDecl>(DC)) {
1440 LookupQualifiedName(R, DC);
1441
1442 if (!R.empty()) {
1443 // Don't give errors about ambiguities in this lookup.
1444 R.suppressDiagnostics();
1445
1446 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1447 bool isInstance = CurMethod &&
1448 CurMethod->isInstance() &&
1449 DC == CurMethod->getParent();
1450
1451 // Give a code modification hint to insert 'this->'.
1452 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1453 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001454 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001455 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1456 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001457 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001458 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001459 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001460 Diag(R.getNameLoc(), diagnostic) << Name
1461 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1462 QualType DepThisType = DepMethod->getThisType(Context);
1463 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1464 R.getNameLoc(), DepThisType, false);
1465 TemplateArgumentListInfo TList;
1466 if (ULE->hasExplicitTemplateArgs())
1467 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001468
Douglas Gregore16af532011-02-28 18:50:33 +00001469 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001470 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001471 CXXDependentScopeMemberExpr *DepExpr =
1472 CXXDependentScopeMemberExpr::Create(
1473 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001474 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001475 R.getLookupNameInfo(),
1476 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001477 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001478 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001479 // FIXME: we should be able to handle this case too. It is correct
1480 // to add this-> here. This is a workaround for PR7947.
1481 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001482 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001483 } else {
John McCalld681c392009-12-16 08:11:27 +00001484 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001485 }
John McCalld681c392009-12-16 08:11:27 +00001486
1487 // Do we really want to note all of these?
1488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1489 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1490
1491 // Tell the callee to try to recover.
1492 return false;
1493 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001494
1495 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001496 }
1497 }
1498
Douglas Gregor598b08f2009-12-31 05:20:13 +00001499 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001500 TypoCorrection Corrected;
1501 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1502 S, &SS, NULL, false, CTC))) {
1503 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1504 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1505 R.setLookupName(Corrected.getCorrection());
1506
Hans Wennborg38198de2011-07-12 08:45:31 +00001507 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001508 if (Corrected.isOverloaded()) {
1509 OverloadCandidateSet OCS(R.getNameLoc());
1510 OverloadCandidateSet::iterator Best;
1511 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1512 CDEnd = Corrected.end();
1513 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001514 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001515 dyn_cast<FunctionTemplateDecl>(*CD))
1516 AddTemplateOverloadCandidate(
1517 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1518 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001519 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1520 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1521 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1522 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001523 }
1524 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1525 case OR_Success:
1526 ND = Best->Function;
1527 break;
1528 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001529 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001530 }
1531 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001532 R.addDecl(ND);
1533 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001534 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001535 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1536 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001537 else
1538 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001539 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001540 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001541 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1542 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001543 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001544 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001545
1546 // Tell the callee to try to recover.
1547 return false;
1548 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001549
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001550 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001551 // FIXME: If we ended up with a typo for a type name or
1552 // Objective-C class name, we're in trouble because the parser
1553 // is in the wrong place to recover. Suggest the typo
1554 // correction, but don't make it a fix-it since we're not going
1555 // to recover well anyway.
1556 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001557 Diag(R.getNameLoc(), diagnostic_suggest)
1558 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001559 else
1560 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001561 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001562 << SS.getRange();
1563
1564 // Don't try to recover; it won't work.
1565 return true;
1566 }
1567 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001568 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001569 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001570 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001571 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001572 else
Douglas Gregor25363982010-01-01 00:15:04 +00001573 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001574 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001575 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001576 return true;
1577 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001578 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001579 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001580
1581 // Emit a special diagnostic for failed member lookups.
1582 // FIXME: computing the declaration context might fail here (?)
1583 if (!SS.isEmpty()) {
1584 Diag(R.getNameLoc(), diag::err_no_member)
1585 << Name << computeDeclContext(SS, false)
1586 << SS.getRange();
1587 return true;
1588 }
1589
John McCalld681c392009-12-16 08:11:27 +00001590 // Give up, we can't recover.
1591 Diag(R.getNameLoc(), diagnostic) << Name;
1592 return true;
1593}
1594
John McCalldadc5752010-08-24 06:29:42 +00001595ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001596 CXXScopeSpec &SS,
1597 UnqualifiedId &Id,
1598 bool HasTrailingLParen,
1599 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001600 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1601 "cannot be direct & operand and have a trailing lparen");
1602
1603 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001604 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001605
John McCall10eae182009-11-30 22:42:35 +00001606 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001607
1608 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001609 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001610 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001611 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001612
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001613 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001614 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001615 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001616
John McCalle66edc12009-11-24 19:00:30 +00001617 // C++ [temp.dep.expr]p3:
1618 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001619 // -- an identifier that was declared with a dependent type,
1620 // (note: handled after lookup)
1621 // -- a template-id that is dependent,
1622 // (note: handled in BuildTemplateIdExpr)
1623 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001624 // -- a nested-name-specifier that contains a class-name that
1625 // names a dependent type.
1626 // Determine whether this is a member of an unknown specialization;
1627 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001628 bool DependentID = false;
1629 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1630 Name.getCXXNameType()->isDependentType()) {
1631 DependentID = true;
1632 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001633 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001634 if (RequireCompleteDeclContext(SS, DC))
1635 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001636 } else {
1637 DependentID = true;
1638 }
1639 }
1640
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001641 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001642 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001643 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001644
Fariborz Jahanian86151342010-07-22 23:33:21 +00001645 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001646 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001647 LookupResult R(*this, NameInfo,
1648 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1649 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001650 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001651 // Lookup the template name again to correctly establish the context in
1652 // which it was found. This is really unfortunate as we already did the
1653 // lookup to determine that it was a template name in the first place. If
1654 // this becomes a performance hit, we can work harder to preserve those
1655 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001656 bool MemberOfUnknownSpecialization;
1657 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1658 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001659
1660 if (MemberOfUnknownSpecialization ||
1661 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1662 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1663 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001664 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001665 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001666 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Douglas Gregora5226932011-02-04 13:35:07 +00001668 // If the result might be in a dependent base class, this is a dependent
1669 // id-expression.
1670 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1671 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1672 TemplateArgs);
1673
John McCalle66edc12009-11-24 19:00:30 +00001674 // If this reference is in an Objective-C method, then we need to do
1675 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001676 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001677 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001678 if (E.isInvalid())
1679 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001681 if (Expr *Ex = E.takeAs<Expr>())
1682 return Owned(Ex);
1683
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001684 // for further use, this must be set to false if in class method.
1685 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001686 }
Chris Lattner59a25942008-03-31 00:36:02 +00001687 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001688
John McCalle66edc12009-11-24 19:00:30 +00001689 if (R.isAmbiguous())
1690 return ExprError();
1691
Douglas Gregor171c45a2009-02-18 21:56:37 +00001692 // Determine whether this name might be a candidate for
1693 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001694 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001695
John McCalle66edc12009-11-24 19:00:30 +00001696 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001697 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001698 // in C90, extension in C99, forbidden in C++).
1699 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1700 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1701 if (D) R.addDecl(D);
1702 }
1703
1704 // If this name wasn't predeclared and if this is not a function
1705 // call, diagnose the problem.
1706 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001707 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001708 return ExprError();
1709
1710 assert(!R.empty() &&
1711 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001712
1713 // If we found an Objective-C instance variable, let
1714 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001715 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001716 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1717 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001718 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001719 assert(E.isInvalid() || E.get());
1720 return move(E);
1721 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001722 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
John McCalle66edc12009-11-24 19:00:30 +00001725 // This is guaranteed from this point on.
1726 assert(!R.empty() || ADL);
1727
John McCall2d74de92009-12-01 22:10:20 +00001728 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001729 // C++ [class.mfct.non-static]p3:
1730 // When an id-expression that is not part of a class member access
1731 // syntax and not used to form a pointer to member is used in the
1732 // body of a non-static member function of class X, if name lookup
1733 // resolves the name in the id-expression to a non-static non-type
1734 // member of some class C, the id-expression is transformed into a
1735 // class member access expression using (*this) as the
1736 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001737 //
1738 // But we don't actually need to do this for '&' operands if R
1739 // resolved to a function or overloaded function set, because the
1740 // expression is ill-formed if it actually works out to be a
1741 // non-static member function:
1742 //
1743 // C++ [expr.ref]p4:
1744 // Otherwise, if E1.E2 refers to a non-static member function. . .
1745 // [t]he expression can be used only as the left-hand operand of a
1746 // member function call.
1747 //
1748 // There are other safeguards against such uses, but it's important
1749 // to get this right here so that we don't end up making a
1750 // spuriously dependent expression if we're inside a dependent
1751 // instance method.
John McCall57500772009-12-16 12:17:52 +00001752 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001753 bool MightBeImplicitMember;
1754 if (!isAddressOfOperand)
1755 MightBeImplicitMember = true;
1756 else if (!SS.isEmpty())
1757 MightBeImplicitMember = false;
1758 else if (R.isOverloadedResult())
1759 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001760 else if (R.isUnresolvableResult())
1761 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001762 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001763 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1764 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001765
1766 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001767 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001768 }
1769
John McCalle66edc12009-11-24 19:00:30 +00001770 if (TemplateArgs)
1771 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001772
John McCalle66edc12009-11-24 19:00:30 +00001773 return BuildDeclarationNameExpr(SS, R, ADL);
1774}
1775
John McCall10eae182009-11-30 22:42:35 +00001776/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1777/// declaration name, generally during template instantiation.
1778/// There's a large number of things which don't need to be done along
1779/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001780ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001781Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001782 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001783 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001784 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001785 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001786
John McCall0b66eb32010-05-01 00:40:08 +00001787 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001788 return ExprError();
1789
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001790 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001791 LookupQualifiedName(R, DC);
1792
1793 if (R.isAmbiguous())
1794 return ExprError();
1795
1796 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001797 Diag(NameInfo.getLoc(), diag::err_no_member)
1798 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001799 return ExprError();
1800 }
1801
1802 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1803}
1804
1805/// LookupInObjCMethod - The parser has read a name in, and Sema has
1806/// detected that we're currently inside an ObjC method. Perform some
1807/// additional lookup.
1808///
1809/// Ideally, most of this would be done by lookup, but there's
1810/// actually quite a lot of extra work involved.
1811///
1812/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001813ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001814Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001815 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001816 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001817 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001818
John McCalle66edc12009-11-24 19:00:30 +00001819 // There are two cases to handle here. 1) scoped lookup could have failed,
1820 // in which case we should look for an ivar. 2) scoped lookup could have
1821 // found a decl, but that decl is outside the current instance method (i.e.
1822 // a global variable). In these two cases, we do a lookup for an ivar with
1823 // this name, if the lookup sucedes, we replace it our current decl.
1824
1825 // If we're in a class method, we don't normally want to look for
1826 // ivars. But if we don't find anything else, and there's an
1827 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001828 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001829
1830 bool LookForIvars;
1831 if (Lookup.empty())
1832 LookForIvars = true;
1833 else if (IsClassMethod)
1834 LookForIvars = false;
1835 else
1836 LookForIvars = (Lookup.isSingleResult() &&
1837 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001838 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001839 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001840 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001841 ObjCInterfaceDecl *ClassDeclared;
1842 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1843 // Diagnose using an ivar in a class method.
1844 if (IsClassMethod)
1845 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1846 << IV->getDeclName());
1847
1848 // If we're referencing an invalid decl, just return this as a silent
1849 // error node. The error diagnostic was already emitted on the decl.
1850 if (IV->isInvalidDecl())
1851 return ExprError();
1852
1853 // Check if referencing a field with __attribute__((deprecated)).
1854 if (DiagnoseUseOfDecl(IV, Loc))
1855 return ExprError();
1856
1857 // Diagnose the use of an ivar outside of the declaring class.
1858 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1859 ClassDeclared != IFace)
1860 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1861
1862 // FIXME: This should use a new expr for a direct reference, don't
1863 // turn this into Self->ivar, just return a BareIVarExpr or something.
1864 IdentifierInfo &II = Context.Idents.get("self");
1865 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001866 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001867 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001868 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001869 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001870 SelfName, false, false);
1871 if (SelfExpr.isInvalid())
1872 return ExprError();
1873
John Wiegley01296292011-04-08 18:41:53 +00001874 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1875 if (SelfExpr.isInvalid())
1876 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001877
John McCalle66edc12009-11-24 19:00:30 +00001878 MarkDeclarationReferenced(Loc, IV);
1879 return Owned(new (Context)
1880 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001881 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001882 }
Chris Lattner87313662010-04-12 05:10:17 +00001883 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001884 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001885 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001886 ObjCInterfaceDecl *ClassDeclared;
1887 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1888 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1889 IFace == ClassDeclared)
1890 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1891 }
1892 }
1893
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001894 if (Lookup.empty() && II && AllowBuiltinCreation) {
1895 // FIXME. Consolidate this with similar code in LookupName.
1896 if (unsigned BuiltinID = II->getBuiltinID()) {
1897 if (!(getLangOptions().CPlusPlus &&
1898 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1899 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1900 S, Lookup.isForRedeclaration(),
1901 Lookup.getNameLoc());
1902 if (D) Lookup.addDecl(D);
1903 }
1904 }
1905 }
John McCalle66edc12009-11-24 19:00:30 +00001906 // Sentinel value saying that we didn't do anything special.
1907 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001908}
John McCalld14a8642009-11-21 08:51:07 +00001909
John McCall16df1e52010-03-30 21:47:33 +00001910/// \brief Cast a base object to a member's actual type.
1911///
1912/// Logically this happens in three phases:
1913///
1914/// * First we cast from the base type to the naming class.
1915/// The naming class is the class into which we were looking
1916/// when we found the member; it's the qualifier type if a
1917/// qualifier was provided, and otherwise it's the base type.
1918///
1919/// * Next we cast from the naming class to the declaring class.
1920/// If the member we found was brought into a class's scope by
1921/// a using declaration, this is that class; otherwise it's
1922/// the class declaring the member.
1923///
1924/// * Finally we cast from the declaring class to the "true"
1925/// declaring class of the member. This conversion does not
1926/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001927ExprResult
1928Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001929 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001930 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001931 NamedDecl *Member) {
1932 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1933 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001934 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001935
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001936 QualType DestRecordType;
1937 QualType DestType;
1938 QualType FromRecordType;
1939 QualType FromType = From->getType();
1940 bool PointerConversions = false;
1941 if (isa<FieldDecl>(Member)) {
1942 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 if (FromType->getAs<PointerType>()) {
1945 DestType = Context.getPointerType(DestRecordType);
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 DestType = DestRecordType;
1950 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001951 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001952 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1953 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001954 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 DestType = Method->getThisType(Context);
1957 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 if (FromType->getAs<PointerType>()) {
1960 FromRecordType = FromType->getPointeeType();
1961 PointerConversions = true;
1962 } else {
1963 FromRecordType = FromType;
1964 DestType = DestRecordType;
1965 }
1966 } else {
1967 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001968 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001969 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001970
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001971 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001972 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 // If the unqualified types are the same, no conversion is necessary.
1975 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001976 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001977
John McCall16df1e52010-03-30 21:47:33 +00001978 SourceRange FromRange = From->getSourceRange();
1979 SourceLocation FromLoc = FromRange.getBegin();
1980
John McCall2536c6d2010-08-25 10:28:54 +00001981 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001982
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001984 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001985 // class name.
1986 //
1987 // If the member was a qualified name and the qualified referred to a
1988 // specific base subobject type, we'll cast to that intermediate type
1989 // first and then to the object in which the member is declared. That allows
1990 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1991 //
1992 // class Base { public: int x; };
1993 // class Derived1 : public Base { };
1994 // class Derived2 : public Base { };
1995 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1996 //
1997 // void VeryDerived::f() {
1998 // x = 17; // error: ambiguous base subobjects
1999 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2000 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002001 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002002 QualType QType = QualType(Qualifier->getAsType(), 0);
2003 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2004 assert(QType->isRecordType() && "lookup done with non-record type");
2005
2006 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2007
2008 // In C++98, the qualifier type doesn't actually have to be a base
2009 // type of the object type, in which case we just ignore it.
2010 // Otherwise build the appropriate casts.
2011 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002012 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002013 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002014 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002015 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002016
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002017 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002018 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002019 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2020 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002021
2022 FromType = QType;
2023 FromRecordType = QRecordType;
2024
2025 // If the qualifier type was the same as the destination type,
2026 // we're done.
2027 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002028 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002029 }
2030 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002031
John McCall16df1e52010-03-30 21:47:33 +00002032 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002033
John McCall16df1e52010-03-30 21:47:33 +00002034 // If we actually found the member through a using declaration, cast
2035 // down to the using declaration's type.
2036 //
2037 // Pointer equality is fine here because only one declaration of a
2038 // class ever has member declarations.
2039 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2040 assert(isa<UsingShadowDecl>(FoundDecl));
2041 QualType URecordType = Context.getTypeDeclType(
2042 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2043
2044 // We only need to do this if the naming-class to declaring-class
2045 // conversion is non-trivial.
2046 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2047 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002048 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002049 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002050 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002051 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002052
John McCall16df1e52010-03-30 21:47:33 +00002053 QualType UType = URecordType;
2054 if (PointerConversions)
2055 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002056 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2057 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002058 FromType = UType;
2059 FromRecordType = URecordType;
2060 }
2061
2062 // We don't do access control for the conversion from the
2063 // declaring class to the true declaring class.
2064 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002065 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002066
John McCallcf142162010-08-07 06:22:56 +00002067 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002068 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2069 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002070 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002071 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002072
John Wiegley01296292011-04-08 18:41:53 +00002073 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2074 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002075}
Douglas Gregor3256d042009-06-30 15:47:41 +00002076
John McCalle66edc12009-11-24 19:00:30 +00002077bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002078 const LookupResult &R,
2079 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002080 // Only when used directly as the postfix-expression of a call.
2081 if (!HasTrailingLParen)
2082 return false;
2083
2084 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002085 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002086 return false;
2087
2088 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002089 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002090 return false;
2091
2092 // Turn off ADL when we find certain kinds of declarations during
2093 // normal lookup:
2094 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2095 NamedDecl *D = *I;
2096
2097 // C++0x [basic.lookup.argdep]p3:
2098 // -- a declaration of a class member
2099 // Since using decls preserve this property, we check this on the
2100 // original decl.
John McCall57500772009-12-16 12:17:52 +00002101 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002102 return false;
2103
2104 // C++0x [basic.lookup.argdep]p3:
2105 // -- a block-scope function declaration that is not a
2106 // using-declaration
2107 // NOTE: we also trigger this for function templates (in fact, we
2108 // don't check the decl type at all, since all other decl types
2109 // turn off ADL anyway).
2110 if (isa<UsingShadowDecl>(D))
2111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2112 else if (D->getDeclContext()->isFunctionOrMethod())
2113 return false;
2114
2115 // C++0x [basic.lookup.argdep]p3:
2116 // -- a declaration that is neither a function or a function
2117 // template
2118 // And also for builtin functions.
2119 if (isa<FunctionDecl>(D)) {
2120 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2121
2122 // But also builtin functions.
2123 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2124 return false;
2125 } else if (!isa<FunctionTemplateDecl>(D))
2126 return false;
2127 }
2128
2129 return true;
2130}
2131
2132
John McCalld14a8642009-11-21 08:51:07 +00002133/// Diagnoses obvious problems with the use of the given declaration
2134/// as an expression. This is only actually called for lookups that
2135/// were not overloaded, and it doesn't promise that the declaration
2136/// will in fact be used.
2137static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002138 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002139 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2140 return true;
2141 }
2142
2143 if (isa<ObjCInterfaceDecl>(D)) {
2144 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2145 return true;
2146 }
2147
2148 if (isa<NamespaceDecl>(D)) {
2149 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2150 return true;
2151 }
2152
2153 return false;
2154}
2155
John McCalldadc5752010-08-24 06:29:42 +00002156ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002157Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002158 LookupResult &R,
2159 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002160 // If this is a single, fully-resolved result and we don't need ADL,
2161 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002162 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002163 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2164 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002165
2166 // We only need to check the declaration if there's exactly one
2167 // result, because in the overloaded case the results can only be
2168 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002169 if (R.isSingleResult() &&
2170 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002171 return ExprError();
2172
John McCall58cc69d2010-01-27 01:50:18 +00002173 // Otherwise, just build an unresolved lookup expression. Suppress
2174 // any lookup-related diagnostics; we'll hash these out later, when
2175 // we've picked a target.
2176 R.suppressDiagnostics();
2177
John McCalld14a8642009-11-21 08:51:07 +00002178 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002179 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002180 SS.getWithLocInContext(Context),
2181 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002182 NeedsADL, R.isOverloadedResult(),
2183 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002184
2185 return Owned(ULE);
2186}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002187
John McCalld14a8642009-11-21 08:51:07 +00002188/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002189ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002190Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002191 const DeclarationNameInfo &NameInfo,
2192 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002193 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002194 assert(!isa<FunctionTemplateDecl>(D) &&
2195 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002196
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002197 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002198 if (CheckDeclInExpr(*this, Loc, D))
2199 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002200
Douglas Gregore7488b92009-12-01 16:58:18 +00002201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2202 // Specifically diagnose references to class templates that are missing
2203 // a template argument list.
2204 Diag(Loc, diag::err_template_decl_ref)
2205 << Template << SS.getRange();
2206 Diag(Template->getLocation(), diag::note_template_decl_here);
2207 return ExprError();
2208 }
2209
2210 // Make sure that we're referring to a value.
2211 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2212 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002213 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002214 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002215 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002216 return ExprError();
2217 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002218
Douglas Gregor171c45a2009-02-18 21:56:37 +00002219 // Check whether this declaration can be used. Note that we suppress
2220 // this check when we're going to perform argument-dependent lookup
2221 // on this function name, because this might not be the function
2222 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002223 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002224 return ExprError();
2225
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002226 // Only create DeclRefExpr's for valid Decl's.
2227 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002228 return ExprError();
2229
John McCallf3a88602011-02-03 08:15:49 +00002230 // Handle members of anonymous structs and unions. If we got here,
2231 // and the reference is to a class member indirect field, then this
2232 // must be the subject of a pointer-to-member expression.
2233 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2234 if (!indirectField->isCXXClassMember())
2235 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2236 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002237
Chris Lattner2a9d9892008-10-20 05:16:36 +00002238 // If the identifier reference is inside a block, and it refers to a value
2239 // that is outside the block, create a BlockDeclRefExpr instead of a
2240 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2241 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002242 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002243 // We do not do this for things like enum constants, global variables, etc,
2244 // as they do not get snapshotted.
2245 //
John McCall351762c2011-02-07 10:33:21 +00002246 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002247 case CR_Error:
2248 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002249
John McCallc63de662011-02-02 13:00:07 +00002250 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002251 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2252 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2253
2254 case CR_CaptureByRef:
2255 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2256 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002257
2258 case CR_NoCapture: {
2259 // If this reference is not in a block or if the referenced
2260 // variable is within the block, create a normal DeclRefExpr.
2261
2262 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002263 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002264
2265 switch (D->getKind()) {
2266 // Ignore all the non-ValueDecl kinds.
2267#define ABSTRACT_DECL(kind)
2268#define VALUE(type, base)
2269#define DECL(type, base) \
2270 case Decl::type:
2271#include "clang/AST/DeclNodes.inc"
2272 llvm_unreachable("invalid value decl kind");
2273 return ExprError();
2274
2275 // These shouldn't make it here.
2276 case Decl::ObjCAtDefsField:
2277 case Decl::ObjCIvar:
2278 llvm_unreachable("forming non-member reference to ivar?");
2279 return ExprError();
2280
2281 // Enum constants are always r-values and never references.
2282 // Unresolved using declarations are dependent.
2283 case Decl::EnumConstant:
2284 case Decl::UnresolvedUsingValue:
2285 valueKind = VK_RValue;
2286 break;
2287
2288 // Fields and indirect fields that got here must be for
2289 // pointer-to-member expressions; we just call them l-values for
2290 // internal consistency, because this subexpression doesn't really
2291 // exist in the high-level semantics.
2292 case Decl::Field:
2293 case Decl::IndirectField:
2294 assert(getLangOptions().CPlusPlus &&
2295 "building reference to field in C?");
2296
2297 // These can't have reference type in well-formed programs, but
2298 // for internal consistency we do this anyway.
2299 type = type.getNonReferenceType();
2300 valueKind = VK_LValue;
2301 break;
2302
2303 // Non-type template parameters are either l-values or r-values
2304 // depending on the type.
2305 case Decl::NonTypeTemplateParm: {
2306 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2307 type = reftype->getPointeeType();
2308 valueKind = VK_LValue; // even if the parameter is an r-value reference
2309 break;
2310 }
2311
2312 // For non-references, we need to strip qualifiers just in case
2313 // the template parameter was declared as 'const int' or whatever.
2314 valueKind = VK_RValue;
2315 type = type.getUnqualifiedType();
2316 break;
2317 }
2318
2319 case Decl::Var:
2320 // In C, "extern void blah;" is valid and is an r-value.
2321 if (!getLangOptions().CPlusPlus &&
2322 !type.hasQualifiers() &&
2323 type->isVoidType()) {
2324 valueKind = VK_RValue;
2325 break;
2326 }
2327 // fallthrough
2328
2329 case Decl::ImplicitParam:
2330 case Decl::ParmVar:
2331 // These are always l-values.
2332 valueKind = VK_LValue;
2333 type = type.getNonReferenceType();
2334 break;
2335
2336 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002337 const FunctionType *fty = type->castAs<FunctionType>();
2338
2339 // If we're referring to a function with an __unknown_anytype
2340 // result type, make the entire expression __unknown_anytype.
2341 if (fty->getResultType() == Context.UnknownAnyTy) {
2342 type = Context.UnknownAnyTy;
2343 valueKind = VK_RValue;
2344 break;
2345 }
2346
John McCallf4cd4f92011-02-09 01:13:10 +00002347 // Functions are l-values in C++.
2348 if (getLangOptions().CPlusPlus) {
2349 valueKind = VK_LValue;
2350 break;
2351 }
2352
2353 // C99 DR 316 says that, if a function type comes from a
2354 // function definition (without a prototype), that type is only
2355 // used for checking compatibility. Therefore, when referencing
2356 // the function, we pretend that we don't have the full function
2357 // type.
John McCall2979fe02011-04-12 00:42:48 +00002358 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2359 isa<FunctionProtoType>(fty))
2360 type = Context.getFunctionNoProtoType(fty->getResultType(),
2361 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002362
2363 // Functions are r-values in C.
2364 valueKind = VK_RValue;
2365 break;
2366 }
2367
2368 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002369 // If we're referring to a method with an __unknown_anytype
2370 // result type, make the entire expression __unknown_anytype.
2371 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002372 if (const FunctionProtoType *proto
2373 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002374 if (proto->getResultType() == Context.UnknownAnyTy) {
2375 type = Context.UnknownAnyTy;
2376 valueKind = VK_RValue;
2377 break;
2378 }
2379
John McCallf4cd4f92011-02-09 01:13:10 +00002380 // C++ methods are l-values if static, r-values if non-static.
2381 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2382 valueKind = VK_LValue;
2383 break;
2384 }
2385 // fallthrough
2386
2387 case Decl::CXXConversion:
2388 case Decl::CXXDestructor:
2389 case Decl::CXXConstructor:
2390 valueKind = VK_RValue;
2391 break;
2392 }
2393
2394 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2395 }
2396
John McCallc63de662011-02-02 13:00:07 +00002397 }
John McCall7decc9e2010-11-18 06:31:45 +00002398
John McCall351762c2011-02-07 10:33:21 +00002399 llvm_unreachable("unknown capture result");
2400 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002401}
Chris Lattnere168f762006-11-10 05:29:30 +00002402
John McCall2979fe02011-04-12 00:42:48 +00002403ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002404 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002405
Chris Lattnere168f762006-11-10 05:29:30 +00002406 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002407 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002408 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2409 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2410 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002411 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002412
Chris Lattnera81a0272008-01-12 08:14:25 +00002413 // Pre-defined identifiers are of type char[x], where x is the length of the
2414 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002415
Anders Carlsson2fb08242009-09-08 18:24:21 +00002416 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002417 if (!currentDecl && getCurBlock())
2418 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002419 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002420 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002421 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002422 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002423
Anders Carlsson0b209a82009-09-11 01:22:35 +00002424 QualType ResTy;
2425 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2426 ResTy = Context.DependentTy;
2427 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002428 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002429
Anders Carlsson0b209a82009-09-11 01:22:35 +00002430 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002431 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002432 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2433 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002434 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002435}
2436
John McCalldadc5752010-08-24 06:29:42 +00002437ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002438 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002439 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002440 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002441 if (Invalid)
2442 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002443
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002444 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002445 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002446 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002447 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002448
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002449 QualType Ty;
2450 if (!getLangOptions().CPlusPlus)
2451 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2452 else if (Literal.isWide())
2453 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002454 else if (Literal.isUTF16())
2455 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2456 else if (Literal.isUTF32())
2457 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002458 else if (Literal.isMultiChar())
2459 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002460 else
2461 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002462
Douglas Gregorfb65e592011-07-27 05:40:30 +00002463 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2464 if (Literal.isWide())
2465 Kind = CharacterLiteral::Wide;
2466 else if (Literal.isUTF16())
2467 Kind = CharacterLiteral::UTF16;
2468 else if (Literal.isUTF32())
2469 Kind = CharacterLiteral::UTF32;
2470
2471 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2472 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002473}
2474
John McCalldadc5752010-08-24 06:29:42 +00002475ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002476 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002477 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2478 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002479 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002480 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002481 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002482 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002483 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002484
Chris Lattner23b7eb62007-06-15 23:05:46 +00002485 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002486 // Add padding so that NumericLiteralParser can overread by one character.
2487 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002488 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002489
Chris Lattner67ca9252007-05-21 01:08:44 +00002490 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002491 bool Invalid = false;
2492 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2493 if (Invalid)
2494 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002495
Mike Stump11289f42009-09-09 15:08:12 +00002496 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002497 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002498 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002499 return ExprError();
2500
Chris Lattner1c20a172007-08-26 03:42:43 +00002501 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002502
Chris Lattner1c20a172007-08-26 03:42:43 +00002503 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002504 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002505 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002506 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002507 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002508 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002509 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002510 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002511
2512 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2513
John McCall53b93a02009-12-24 09:08:04 +00002514 using llvm::APFloat;
2515 APFloat Val(Format);
2516
2517 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002518
2519 // Overflow is always an error, but underflow is only an error if
2520 // we underflowed to zero (APFloat reports denormals as underflow).
2521 if ((result & APFloat::opOverflow) ||
2522 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002523 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002524 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002525 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002526 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002527 APFloat::getLargest(Format).toString(buffer);
2528 } else {
John McCall62abc942010-02-26 23:35:57 +00002529 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002530 APFloat::getSmallest(Format).toString(buffer);
2531 }
2532
2533 Diag(Tok.getLocation(), diagnostic)
2534 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002536 }
2537
2538 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002539 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002540
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002541 if (Ty == Context.DoubleTy) {
2542 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002543 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002544 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2545 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002546 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002547 }
2548 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002549 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002551 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002552 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002553
Neil Boothac582c52007-08-29 22:00:19 +00002554 // long long is a C99 feature.
2555 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002556 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002557 Diag(Tok.getLocation(), diag::ext_longlong);
2558
Chris Lattner67ca9252007-05-21 01:08:44 +00002559 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002560 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002561
Chris Lattner67ca9252007-05-21 01:08:44 +00002562 if (Literal.GetIntegerValue(ResultVal)) {
2563 // If this value didn't fit into uintmax_t, warn and force to ull.
2564 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002565 Ty = Context.UnsignedLongLongTy;
2566 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002567 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002568 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002569 // If this value fits into a ULL, try to figure out what else it fits into
2570 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2573 // be an unsigned int.
2574 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2575
2576 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002577 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002578 if (!Literal.isLong && !Literal.isLongLong) {
2579 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002580 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 // Does it fit in a unsigned int?
2583 if (ResultVal.isIntN(IntSize)) {
2584 // Does it fit in a signed int?
2585 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002586 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002587 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002588 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002589 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002590 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002592
Chris Lattner67ca9252007-05-21 01:08:44 +00002593 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002594 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002595 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002596
Chris Lattner67ca9252007-05-21 01:08:44 +00002597 // Does it fit in a unsigned long?
2598 if (ResultVal.isIntN(LongSize)) {
2599 // Does it fit in a signed long?
2600 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002601 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002603 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002604 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002605 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002606 }
2607
Chris Lattner67ca9252007-05-21 01:08:44 +00002608 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002609 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002610 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002611
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 // Does it fit in a unsigned long long?
2613 if (ResultVal.isIntN(LongLongSize)) {
2614 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002615 // To be compatible with MSVC, hex integer literals ending with the
2616 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002617 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2618 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002619 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002620 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002621 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002622 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 }
2624 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002625
Chris Lattner67ca9252007-05-21 01:08:44 +00002626 // If we still couldn't decide a type, we probably have something that
2627 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002628 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002629 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002630 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002631 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002633
Chris Lattner55258cf2008-05-09 05:59:00 +00002634 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002635 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002636 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002637 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002638 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002639
Chris Lattner1c20a172007-08-26 03:42:43 +00002640 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2641 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002642 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002643 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002644
2645 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002646}
2647
John McCalldadc5752010-08-24 06:29:42 +00002648ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002649 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002650 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002651 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002652}
2653
Chandler Carruth62da79c2011-05-26 08:53:12 +00002654static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2655 SourceLocation Loc,
2656 SourceRange ArgRange) {
2657 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2658 // scalar or vector data type argument..."
2659 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2660 // type (C99 6.2.5p18) or void.
2661 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2662 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2663 << T << ArgRange;
2664 return true;
2665 }
2666
2667 assert((T->isVoidType() || !T->isIncompleteType()) &&
2668 "Scalar types should always be complete");
2669 return false;
2670}
2671
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002672static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2673 SourceLocation Loc,
2674 SourceRange ArgRange,
2675 UnaryExprOrTypeTrait TraitKind) {
2676 // C99 6.5.3.4p1:
2677 if (T->isFunctionType()) {
2678 // alignof(function) is allowed as an extension.
2679 if (TraitKind == UETT_SizeOf)
2680 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2681 return false;
2682 }
2683
2684 // Allow sizeof(void)/alignof(void) as an extension.
2685 if (T->isVoidType()) {
2686 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2687 return false;
2688 }
2689
2690 return true;
2691}
2692
2693static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2694 SourceLocation Loc,
2695 SourceRange ArgRange,
2696 UnaryExprOrTypeTrait TraitKind) {
2697 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2698 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2699 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2700 << T << (TraitKind == UETT_SizeOf)
2701 << ArgRange;
2702 return true;
2703 }
2704
2705 return false;
2706}
2707
Chandler Carruth14502c22011-05-26 08:53:10 +00002708/// \brief Check the constrains on expression operands to unary type expression
2709/// and type traits.
2710///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002711/// Completes any types necessary and validates the constraints on the operand
2712/// expression. The logic mostly mirrors the type-based overload, but may modify
2713/// the expression as it completes the type for that expression through template
2714/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002715bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2716 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002717 QualType ExprTy = Op->getType();
2718
2719 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2720 // the result is the size of the referenced type."
2721 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2722 // result shall be the alignment of the referenced type."
2723 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2724 ExprTy = Ref->getPointeeType();
2725
2726 if (ExprKind == UETT_VecStep)
2727 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2728 Op->getSourceRange());
2729
2730 // Whitelist some types as extensions
2731 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2732 Op->getSourceRange(), ExprKind))
2733 return false;
2734
2735 if (RequireCompleteExprType(Op,
2736 PDiag(diag::err_sizeof_alignof_incomplete_type)
2737 << ExprKind << Op->getSourceRange(),
2738 std::make_pair(SourceLocation(), PDiag(0))))
2739 return true;
2740
2741 // Completeing the expression's type may have changed it.
2742 ExprTy = Op->getType();
2743 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2744 ExprTy = Ref->getPointeeType();
2745
2746 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2747 Op->getSourceRange(), ExprKind))
2748 return true;
2749
Nico Weber0870deb2011-06-15 02:47:03 +00002750 if (ExprKind == UETT_SizeOf) {
2751 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2752 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2753 QualType OType = PVD->getOriginalType();
2754 QualType Type = PVD->getType();
2755 if (Type->isPointerType() && OType->isArrayType()) {
2756 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2757 << Type << OType;
2758 Diag(PVD->getLocation(), diag::note_declared_at);
2759 }
2760 }
2761 }
2762 }
2763
Chandler Carruth7c430c02011-05-27 01:33:31 +00002764 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002765}
2766
2767/// \brief Check the constraints on operands to unary expression and type
2768/// traits.
2769///
2770/// This will complete any types necessary, and validate the various constraints
2771/// on those operands.
2772///
Steve Naroff71b59a92007-06-04 22:22:31 +00002773/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002774/// C99 6.3.2.1p[2-4] all state:
2775/// Except when it is the operand of the sizeof operator ...
2776///
2777/// C++ [expr.sizeof]p4
2778/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2779/// standard conversions are not applied to the operand of sizeof.
2780///
2781/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002782bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2783 SourceLocation OpLoc,
2784 SourceRange ExprRange,
2785 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002786 if (exprType->isDependentType())
2787 return false;
2788
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002789 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2790 // the result is the size of the referenced type."
2791 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2792 // result shall be the alignment of the referenced type."
2793 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2794 exprType = Ref->getPointeeType();
2795
Chandler Carruth62da79c2011-05-26 08:53:12 +00002796 if (ExprKind == UETT_VecStep)
2797 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002798
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002799 // Whitelist some types as extensions
2800 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2801 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002802 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002803
Chris Lattner62975a72009-04-24 00:30:45 +00002804 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002805 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002806 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002807 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002808
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002809 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2810 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002811 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002812
Chris Lattner62975a72009-04-24 00:30:45 +00002813 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002814}
2815
Chandler Carruth14502c22011-05-26 08:53:10 +00002816static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002817 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002818
Mike Stump11289f42009-09-09 15:08:12 +00002819 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002820 if (isa<DeclRefExpr>(E))
2821 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002822
2823 // Cannot know anything else if the expression is dependent.
2824 if (E->isTypeDependent())
2825 return false;
2826
Douglas Gregor71235ec2009-05-02 02:18:30 +00002827 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002828 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2829 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002830 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002831 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002832
2833 // Alignment of a field access is always okay, so long as it isn't a
2834 // bit-field.
2835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002836 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002837 return false;
2838
Chandler Carruth14502c22011-05-26 08:53:10 +00002839 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002840}
2841
Chandler Carruth14502c22011-05-26 08:53:10 +00002842bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002843 E = E->IgnoreParens();
2844
2845 // Cannot know anything else if the expression is dependent.
2846 if (E->isTypeDependent())
2847 return false;
2848
Chandler Carruth14502c22011-05-26 08:53:10 +00002849 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002850}
2851
Douglas Gregor0950e412009-03-13 21:01:28 +00002852/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002853ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002854Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2855 SourceLocation OpLoc,
2856 UnaryExprOrTypeTrait ExprKind,
2857 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002858 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002859 return ExprError();
2860
John McCallbcd03502009-12-07 02:54:59 +00002861 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002862
Douglas Gregor0950e412009-03-13 21:01:28 +00002863 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002864 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002865 return ExprError();
2866
2867 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002868 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2869 Context.getSizeType(),
2870 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002871}
2872
2873/// \brief Build a sizeof or alignof expression given an expression
2874/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002875ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002876Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2877 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002878 ExprResult PE = CheckPlaceholderExpr(E);
2879 if (PE.isInvalid())
2880 return ExprError();
2881
2882 E = PE.get();
2883
Douglas Gregor0950e412009-03-13 21:01:28 +00002884 // Verify that the operand is valid.
2885 bool isInvalid = false;
2886 if (E->isTypeDependent()) {
2887 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002888 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002889 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002890 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002891 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002892 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002893 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002894 isInvalid = true;
2895 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002896 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002897 }
2898
2899 if (isInvalid)
2900 return ExprError();
2901
2902 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002903 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002904 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002905 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002906}
2907
Peter Collingbournee190dee2011-03-11 19:24:49 +00002908/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2909/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002910/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002911ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002912Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2913 UnaryExprOrTypeTrait ExprKind, bool isType,
2914 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002915 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002916 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002917
Sebastian Redl6f282892008-11-11 17:56:53 +00002918 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002919 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002920 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002921 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002922 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002923
Douglas Gregor0950e412009-03-13 21:01:28 +00002924 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002925 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002926 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002927}
2928
John Wiegley01296292011-04-08 18:41:53 +00002929static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002930 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002931 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002932 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002933
John McCall34376a62010-12-04 03:47:34 +00002934 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002935 if (V.get()->getObjectKind() != OK_Ordinary) {
2936 V = S.DefaultLvalueConversion(V.take());
2937 if (V.isInvalid())
2938 return QualType();
2939 }
John McCall34376a62010-12-04 03:47:34 +00002940
Chris Lattnere267f5d2007-08-26 05:39:26 +00002941 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002942 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002943 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002944
Chris Lattnere267f5d2007-08-26 05:39:26 +00002945 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002946 if (V.get()->getType()->isArithmeticType())
2947 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002948
John McCall36226622010-10-12 02:09:17 +00002949 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002950 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002951 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002952 if (PR.get() != V.get()) {
2953 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002954 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002955 }
2956
Chris Lattnere267f5d2007-08-26 05:39:26 +00002957 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002958 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002959 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002960 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002961}
2962
2963
Chris Lattnere168f762006-11-10 05:29:30 +00002964
John McCalldadc5752010-08-24 06:29:42 +00002965ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002966Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002967 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002968 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002969 switch (Kind) {
2970 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002971 case tok::plusplus: Opc = UO_PostInc; break;
2972 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002973 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002974
John McCallb268a282010-08-23 23:25:46 +00002975 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002976}
2977
John McCalldadc5752010-08-24 06:29:42 +00002978ExprResult
John McCallb268a282010-08-23 23:25:46 +00002979Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2980 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002981 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002982 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002983 if (Result.isInvalid()) return ExprError();
2984 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002985
John McCallb268a282010-08-23 23:25:46 +00002986 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002987
Douglas Gregor40412ac2008-11-19 17:17:41 +00002988 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002989 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002990 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002991 Context.DependentTy,
2992 VK_LValue, OK_Ordinary,
2993 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002994 }
2995
Mike Stump11289f42009-09-09 15:08:12 +00002996 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002997 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002998 LHSExp->getType()->isEnumeralType() ||
2999 RHSExp->getType()->isRecordType() ||
3000 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003001 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003002 }
3003
John McCallb268a282010-08-23 23:25:46 +00003004 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003005}
3006
3007
John McCalldadc5752010-08-24 06:29:42 +00003008ExprResult
John McCallb268a282010-08-23 23:25:46 +00003009Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3010 Expr *Idx, SourceLocation RLoc) {
3011 Expr *LHSExp = Base;
3012 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003013
Chris Lattner36d572b2007-07-16 00:14:47 +00003014 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003015 if (!LHSExp->getType()->getAs<VectorType>()) {
3016 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3017 if (Result.isInvalid())
3018 return ExprError();
3019 LHSExp = Result.take();
3020 }
3021 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3022 if (Result.isInvalid())
3023 return ExprError();
3024 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003025
Chris Lattner36d572b2007-07-16 00:14:47 +00003026 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003027 ExprValueKind VK = VK_LValue;
3028 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003029
Steve Naroffc1aadb12007-03-28 21:49:40 +00003030 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003031 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003032 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003033 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003034 Expr *BaseExpr, *IndexExpr;
3035 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003036 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3037 BaseExpr = LHSExp;
3038 IndexExpr = RHSExp;
3039 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003040 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003041 BaseExpr = LHSExp;
3042 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003043 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003044 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003045 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003046 BaseExpr = RHSExp;
3047 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003048 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003049 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003050 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003051 BaseExpr = LHSExp;
3052 IndexExpr = RHSExp;
3053 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003054 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003055 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003056 // Handle the uncommon case of "123[Ptr]".
3057 BaseExpr = RHSExp;
3058 IndexExpr = LHSExp;
3059 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003060 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003061 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003062 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003063 VK = LHSExp->getValueKind();
3064 if (VK != VK_RValue)
3065 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003066
Chris Lattner36d572b2007-07-16 00:14:47 +00003067 // FIXME: need to deal with const...
3068 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003069 } else if (LHSTy->isArrayType()) {
3070 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003071 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003072 // wasn't promoted because of the C90 rule that doesn't
3073 // allow promoting non-lvalue arrays. Warn, then
3074 // force the promotion here.
3075 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3076 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003077 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3078 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003079 LHSTy = LHSExp->getType();
3080
3081 BaseExpr = LHSExp;
3082 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003083 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003084 } else if (RHSTy->isArrayType()) {
3085 // Same as previous, except for 123[f().a] case
3086 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3087 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003088 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3089 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003090 RHSTy = RHSExp->getType();
3091
3092 BaseExpr = RHSExp;
3093 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003094 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003095 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003096 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3097 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003098 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003099 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003100 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003101 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3102 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003103
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003104 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003105 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3106 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003107 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3108
Douglas Gregorac1fb652009-03-24 19:52:54 +00003109 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003110 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3111 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003112 // incomplete types are not object types.
3113 if (ResultType->isFunctionType()) {
3114 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3115 << ResultType << BaseExpr->getSourceRange();
3116 return ExprError();
3117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003119 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3120 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003121 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3122 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003123
3124 // C forbids expressions of unqualified void type from being l-values.
3125 // See IsCForbiddenLValueType.
3126 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003127 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003128 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003129 PDiag(diag::err_subscript_incomplete_type)
3130 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003131 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003132
Chris Lattner62975a72009-04-24 00:30:45 +00003133 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003134 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003135 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3136 << ResultType << BaseExpr->getSourceRange();
3137 return ExprError();
3138 }
Mike Stump11289f42009-09-09 15:08:12 +00003139
John McCall4bc41ae2010-11-18 19:01:18 +00003140 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003141 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003142
Mike Stump4e1f26a2009-02-19 03:04:26 +00003143 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003144 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003145}
3146
John McCalldadc5752010-08-24 06:29:42 +00003147ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003148 FunctionDecl *FD,
3149 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003150 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003151 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003152 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003153 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003154 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003155 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003156 return ExprError();
3157 }
3158
3159 if (Param->hasUninstantiatedDefaultArg()) {
3160 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003161
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003162 // Instantiate the expression.
3163 MultiLevelTemplateArgumentList ArgList
3164 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003165
Nico Weber44887f62010-11-29 18:19:25 +00003166 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003167 = ArgList.getInnermost();
3168 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3169 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003170
Nico Weber44887f62010-11-29 18:19:25 +00003171 ExprResult Result;
3172 {
3173 // C++ [dcl.fct.default]p5:
3174 // The names in the [default argument] expression are bound, and
3175 // the semantic constraints are checked, at the point where the
3176 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003177 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003178 Result = SubstExpr(UninstExpr, ArgList);
3179 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003180 if (Result.isInvalid())
3181 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003182
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003183 // Check the expression as an initializer for the parameter.
3184 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003185 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003186 InitializationKind Kind
3187 = InitializationKind::CreateCopy(Param->getLocation(),
3188 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3189 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003190
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003191 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3192 Result = InitSeq.Perform(*this, Entity, Kind,
3193 MultiExprArg(*this, &ResultE, 1));
3194 if (Result.isInvalid())
3195 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003196
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003197 // Build the default argument expression.
3198 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3199 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003200 }
3201
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003202 // If the default expression creates temporaries, we need to
3203 // push them to the current stack of expression temporaries so they'll
3204 // be properly destroyed.
3205 // FIXME: We should really be rebuilding the default argument with new
3206 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003207 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3208 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3209 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3210 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3211 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003212 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003213 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003214
3215 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003216 // Just mark all of the declarations in this potentially-evaluated expression
3217 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003218 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003219 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003220}
3221
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003222/// ConvertArgumentsForCall - Converts the arguments specified in
3223/// Args/NumArgs to the parameter types of the function FDecl with
3224/// function prototype Proto. Call is the call expression itself, and
3225/// Fn is the function expression. For a C++ member function, this
3226/// routine does not attempt to convert the object argument. Returns
3227/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003228bool
3229Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003230 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003231 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003232 Expr **Args, unsigned NumArgs,
3233 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003234 // Bail out early if calling a builtin with custom typechecking.
3235 // We don't need to do this in the
3236 if (FDecl)
3237 if (unsigned ID = FDecl->getBuiltinID())
3238 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3239 return false;
3240
Mike Stump4e1f26a2009-02-19 03:04:26 +00003241 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003242 // assignment, to the types of the corresponding parameter, ...
3243 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003244 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003245
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003246 // If too few arguments are available (and we don't have default
3247 // arguments for the remaining parameters), don't make the call.
3248 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003249 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3250 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003251 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003252 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003253
3254 // Emit the location of the prototype.
3255 if (FDecl && !FDecl->getBuiltinID())
3256 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3257 << FDecl;
3258
3259 return true;
3260 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003261 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003262 }
3263
3264 // If too many are passed and not variadic, error on the extras and drop
3265 // them.
3266 if (NumArgs > NumArgsInProto) {
3267 if (!Proto->isVariadic()) {
3268 Diag(Args[NumArgsInProto]->getLocStart(),
3269 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003270 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003271 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003272 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3273 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003274
3275 // Emit the location of the prototype.
3276 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003277 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3278 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003279
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003280 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003281 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003282 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003283 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003284 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003285 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003286 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003287 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3288 if (Fn->getType()->isBlockPointerType())
3289 CallType = VariadicBlock; // Block
3290 else if (isa<MemberExpr>(Fn))
3291 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003292 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003293 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003294 if (Invalid)
3295 return true;
3296 unsigned TotalNumArgs = AllArgs.size();
3297 for (unsigned i = 0; i < TotalNumArgs; ++i)
3298 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003299
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003300 return false;
3301}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003302
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003303bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3304 FunctionDecl *FDecl,
3305 const FunctionProtoType *Proto,
3306 unsigned FirstProtoArg,
3307 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003308 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003309 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003310 unsigned NumArgsInProto = Proto->getNumArgs();
3311 unsigned NumArgsToCheck = NumArgs;
3312 bool Invalid = false;
3313 if (NumArgs != NumArgsInProto)
3314 // Use default arguments for missing arguments
3315 NumArgsToCheck = NumArgsInProto;
3316 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003318 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003319 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003320
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003321 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003322 if (ArgIx < NumArgs) {
3323 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003324
Eli Friedman3164fb12009-03-22 22:00:50 +00003325 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3326 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003327 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003328 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003329 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003330
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003331 // Pass the argument
3332 ParmVarDecl *Param = 0;
3333 if (FDecl && i < FDecl->getNumParams())
3334 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003335
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003336 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003337 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003338 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3339 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003340 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003341 SourceLocation(),
3342 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003343 if (ArgE.isInvalid())
3344 return true;
3345
3346 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003347 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003348 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003349
John McCalldadc5752010-08-24 06:29:42 +00003350 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003351 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003352 if (ArgExpr.isInvalid())
3353 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003354
Anders Carlsson355933d2009-08-25 03:49:14 +00003355 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003356 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003357
3358 // Check for array bounds violations for each argument to the call. This
3359 // check only triggers warnings when the argument isn't a more complex Expr
3360 // with its own checking, such as a BinaryOperator.
3361 CheckArrayAccess(Arg);
3362
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003363 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003364 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003365
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003366 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003367 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003368
3369 // Assume that extern "C" functions with variadic arguments that
3370 // return __unknown_anytype aren't *really* variadic.
3371 if (Proto->getResultType() == Context.UnknownAnyTy &&
3372 FDecl && FDecl->isExternC()) {
3373 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3374 ExprResult arg;
3375 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3376 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3377 else
3378 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3379 Invalid |= arg.isInvalid();
3380 AllArgs.push_back(arg.take());
3381 }
3382
3383 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3384 } else {
3385 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003386 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3387 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003388 Invalid |= Arg.isInvalid();
3389 AllArgs.push_back(Arg.take());
3390 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003391 }
3392 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003393 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003394}
3395
John McCall2979fe02011-04-12 00:42:48 +00003396/// Given a function expression of unknown-any type, try to rebuild it
3397/// to have a function type.
3398static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3399
Steve Naroff83895f72007-09-16 03:34:24 +00003400/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003401/// This provides the location of the left/right parens and a list of comma
3402/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003403ExprResult
John McCallb268a282010-08-23 23:25:46 +00003404Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003405 MultiExprArg args, SourceLocation RParenLoc,
3406 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003407 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003408
3409 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003410 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003411 if (Result.isInvalid()) return ExprError();
3412 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003413
John McCallb268a282010-08-23 23:25:46 +00003414 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003415
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003416 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003417 // If this is a pseudo-destructor expression, build the call immediately.
3418 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3419 if (NumArgs > 0) {
3420 // Pseudo-destructor calls should not have any arguments.
3421 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003422 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003423 SourceRange(Args[0]->getLocStart(),
3424 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003425
Douglas Gregorad8a3362009-09-04 17:36:40 +00003426 NumArgs = 0;
3427 }
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregorad8a3362009-09-04 17:36:40 +00003429 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003430 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003433 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003434 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003435 // FIXME: Will need to cache the results of name lookup (including ADL) in
3436 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003437 bool Dependent = false;
3438 if (Fn->isTypeDependent())
3439 Dependent = true;
3440 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3441 Dependent = true;
3442
Peter Collingbourne41f85462011-02-09 21:07:24 +00003443 if (Dependent) {
3444 if (ExecConfig) {
3445 return Owned(new (Context) CUDAKernelCallExpr(
3446 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3447 Context.DependentTy, VK_RValue, RParenLoc));
3448 } else {
3449 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3450 Context.DependentTy, VK_RValue,
3451 RParenLoc));
3452 }
3453 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003454
3455 // Determine whether this is a call to an object (C++ [over.call.object]).
3456 if (Fn->getType()->isRecordType())
3457 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003458 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003459
John McCall2979fe02011-04-12 00:42:48 +00003460 if (Fn->getType() == Context.UnknownAnyTy) {
3461 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3462 if (result.isInvalid()) return ExprError();
3463 Fn = result.take();
3464 }
3465
John McCall0009fcc2011-04-26 20:42:42 +00003466 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003467 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003468 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003469 }
John McCall0009fcc2011-04-26 20:42:42 +00003470 }
John McCall10eae182009-11-30 22:42:35 +00003471
John McCall0009fcc2011-04-26 20:42:42 +00003472 // Check for overloaded calls. This can happen even in C due to extensions.
3473 if (Fn->getType() == Context.OverloadTy) {
3474 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3475
3476 // We aren't supposed to apply this logic if there's an '&' involved.
3477 if (!find.IsAddressOfOperand) {
3478 OverloadExpr *ovl = find.Expression;
3479 if (isa<UnresolvedLookupExpr>(ovl)) {
3480 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3481 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3482 RParenLoc, ExecConfig);
3483 } else {
John McCall2d74de92009-12-01 22:10:20 +00003484 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003485 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003486 }
3487 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003488 }
3489
Douglas Gregore254f902009-02-04 00:32:51 +00003490 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003491
Eli Friedmane14b1992009-12-26 03:35:45 +00003492 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003493
John McCall57500772009-12-16 12:17:52 +00003494 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003495 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3496 if (UnOp->getOpcode() == UO_AddrOf)
3497 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3498
John McCall57500772009-12-16 12:17:52 +00003499 if (isa<DeclRefExpr>(NakedFn))
3500 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003501 else if (isa<MemberExpr>(NakedFn))
3502 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003503
Peter Collingbourne41f85462011-02-09 21:07:24 +00003504 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3505 ExecConfig);
3506}
3507
3508ExprResult
3509Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3510 MultiExprArg execConfig, SourceLocation GGGLoc) {
3511 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3512 if (!ConfigDecl)
3513 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3514 << "cudaConfigureCall");
3515 QualType ConfigQTy = ConfigDecl->getType();
3516
3517 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3518 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3519
3520 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003521}
3522
Tanya Lattner55808c12011-06-04 00:47:47 +00003523/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3524///
3525/// __builtin_astype( value, dst type )
3526///
3527ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3528 SourceLocation BuiltinLoc,
3529 SourceLocation RParenLoc) {
3530 ExprValueKind VK = VK_RValue;
3531 ExprObjectKind OK = OK_Ordinary;
3532 QualType DstTy = GetTypeFromParser(destty);
3533 QualType SrcTy = expr->getType();
3534 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3535 return ExprError(Diag(BuiltinLoc,
3536 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003537 << DstTy
3538 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003539 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003540 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3541 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003542}
3543
John McCall57500772009-12-16 12:17:52 +00003544/// BuildResolvedCallExpr - Build a call to a resolved expression,
3545/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003546/// unary-convert to an expression of function-pointer or
3547/// block-pointer type.
3548///
3549/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003550ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003551Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3552 SourceLocation LParenLoc,
3553 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003554 SourceLocation RParenLoc,
3555 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003556 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3557
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003558 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003559 ExprResult Result = UsualUnaryConversions(Fn);
3560 if (Result.isInvalid())
3561 return ExprError();
3562 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003563
Chris Lattner08464942007-12-28 05:29:59 +00003564 // Make the call expr early, before semantic checks. This guarantees cleanup
3565 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003566 CallExpr *TheCall;
3567 if (Config) {
3568 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3569 cast<CallExpr>(Config),
3570 Args, NumArgs,
3571 Context.BoolTy,
3572 VK_RValue,
3573 RParenLoc);
3574 } else {
3575 TheCall = new (Context) CallExpr(Context, Fn,
3576 Args, NumArgs,
3577 Context.BoolTy,
3578 VK_RValue,
3579 RParenLoc);
3580 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003581
John McCallbebede42011-02-26 05:39:39 +00003582 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3583
3584 // Bail out early if calling a builtin with custom typechecking.
3585 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3586 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3587
John McCall31996342011-04-07 08:22:57 +00003588 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003589 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003590 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003591 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3592 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003593 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003594 if (FuncT == 0)
3595 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3596 << Fn->getType() << Fn->getSourceRange());
3597 } else if (const BlockPointerType *BPT =
3598 Fn->getType()->getAs<BlockPointerType>()) {
3599 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3600 } else {
John McCall31996342011-04-07 08:22:57 +00003601 // Handle calls to expressions of unknown-any type.
3602 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003603 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003604 if (rewrite.isInvalid()) return ExprError();
3605 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003606 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003607 goto retry;
3608 }
3609
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003610 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3611 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003612 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003613
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003614 if (getLangOptions().CUDA) {
3615 if (Config) {
3616 // CUDA: Kernel calls must be to global functions
3617 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3618 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3619 << FDecl->getName() << Fn->getSourceRange());
3620
3621 // CUDA: Kernel function must have 'void' return type
3622 if (!FuncT->getResultType()->isVoidType())
3623 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3624 << Fn->getType() << Fn->getSourceRange());
3625 }
3626 }
3627
Eli Friedman3164fb12009-03-22 22:00:50 +00003628 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003629 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003630 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003631 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003632 return ExprError();
3633
Chris Lattner08464942007-12-28 05:29:59 +00003634 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003635 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003636 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003637
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003638 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003639 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003640 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003641 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003642 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003643 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003644
Douglas Gregord8e97de2009-04-02 15:37:10 +00003645 if (FDecl) {
3646 // Check if we have too few/too many template arguments, based
3647 // on our knowledge of the function definition.
3648 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003649 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003650 const FunctionProtoType *Proto
3651 = Def->getType()->getAs<FunctionProtoType>();
3652 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003653 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3654 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003655 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003656
3657 // If the function we're calling isn't a function prototype, but we have
3658 // a function prototype from a prior declaratiom, use that prototype.
3659 if (!FDecl->hasPrototype())
3660 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003661 }
3662
Steve Naroff0b661582007-08-28 23:30:39 +00003663 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003664 for (unsigned i = 0; i != NumArgs; i++) {
3665 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003666
3667 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003668 InitializedEntity Entity
3669 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003670 Proto->getArgType(i),
3671 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003672 ExprResult ArgE = PerformCopyInitialization(Entity,
3673 SourceLocation(),
3674 Owned(Arg));
3675 if (ArgE.isInvalid())
3676 return true;
3677
3678 Arg = ArgE.takeAs<Expr>();
3679
3680 } else {
John Wiegley01296292011-04-08 18:41:53 +00003681 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3682
3683 if (ArgE.isInvalid())
3684 return true;
3685
3686 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003687 }
3688
Douglas Gregor83025412010-10-26 05:45:40 +00003689 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3690 Arg->getType(),
3691 PDiag(diag::err_call_incomplete_argument)
3692 << Arg->getSourceRange()))
3693 return ExprError();
3694
Chris Lattner08464942007-12-28 05:29:59 +00003695 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003696 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003697 }
Chris Lattner08464942007-12-28 05:29:59 +00003698
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003699 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3700 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003701 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3702 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003703
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003704 // Check for sentinels
3705 if (NDecl)
3706 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003707
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003708 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003709 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003710 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003711 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003712
John McCallbebede42011-02-26 05:39:39 +00003713 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003714 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003715 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003716 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003717 return ExprError();
3718 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003719
John McCallb268a282010-08-23 23:25:46 +00003720 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003721}
3722
John McCalldadc5752010-08-24 06:29:42 +00003723ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003724Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003725 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003726 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003727 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003728 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003729
3730 TypeSourceInfo *TInfo;
3731 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3732 if (!TInfo)
3733 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3734
John McCallb268a282010-08-23 23:25:46 +00003735 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003736}
3737
John McCalldadc5752010-08-24 06:29:42 +00003738ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003739Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003740 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003741 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003742
Eli Friedman37a186d2008-05-20 05:22:08 +00003743 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003744 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3745 PDiag(diag::err_illegal_decl_array_incomplete_type)
3746 << SourceRange(LParenLoc,
3747 literalExpr->getSourceRange().getEnd())))
3748 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003749 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003750 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3751 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003752 } else if (!literalType->isDependentType() &&
3753 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003754 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003755 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003756 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003757 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003758
Douglas Gregor85dabae2009-12-16 01:38:02 +00003759 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003760 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003761 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003762 = InitializationKind::CreateCStyleCast(LParenLoc,
3763 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003764 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003765 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003766 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003767 &literalType);
3768 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003769 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003770 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003771
Chris Lattner79413952008-12-04 23:50:19 +00003772 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003773 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003774 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003775 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003776 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003777
John McCall7decc9e2010-11-18 06:31:45 +00003778 // In C, compound literals are l-values for some reason.
3779 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3780
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003781 return MaybeBindToTemporary(
3782 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3783 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003784}
3785
John McCalldadc5752010-08-24 06:29:42 +00003786ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003787Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003788 SourceLocation RBraceLoc) {
3789 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003790 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003791
Steve Naroff30d242c2007-09-15 18:49:24 +00003792 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003793 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003794
Ted Kremenekac034612010-04-13 23:39:13 +00003795 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3796 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003797 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003798 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003799}
3800
John McCalld7646252010-11-14 08:17:51 +00003801/// Prepares for a scalar cast, performing all the necessary stages
3802/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003803static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003804 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3805 // Also, callers should have filtered out the invalid cases with
3806 // pointers. Everything else should be possible.
3807
John Wiegley01296292011-04-08 18:41:53 +00003808 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003809 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003810 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003811
John McCall8cb679e2010-11-15 09:13:47 +00003812 switch (SrcTy->getScalarTypeKind()) {
3813 case Type::STK_MemberPointer:
3814 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003815
John McCall8cb679e2010-11-15 09:13:47 +00003816 case Type::STK_Pointer:
3817 switch (DestTy->getScalarTypeKind()) {
3818 case Type::STK_Pointer:
3819 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003820 CK_AnyPointerToObjCPointerCast :
3821 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003822 case Type::STK_Bool:
3823 return CK_PointerToBoolean;
3824 case Type::STK_Integral:
3825 return CK_PointerToIntegral;
3826 case Type::STK_Floating:
3827 case Type::STK_FloatingComplex:
3828 case Type::STK_IntegralComplex:
3829 case Type::STK_MemberPointer:
3830 llvm_unreachable("illegal cast from pointer");
3831 }
3832 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003833
John McCall8cb679e2010-11-15 09:13:47 +00003834 case Type::STK_Bool: // casting from bool is like casting from an integer
3835 case Type::STK_Integral:
3836 switch (DestTy->getScalarTypeKind()) {
3837 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003838 if (Src.get()->isNullPointerConstant(S.Context,
3839 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003840 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003841 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003842 case Type::STK_Bool:
3843 return CK_IntegralToBoolean;
3844 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003845 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003846 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003847 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003848 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003849 Src = S.ImpCastExprToType(Src.take(),
3850 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003851 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003852 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003853 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003854 Src = S.ImpCastExprToType(Src.take(),
3855 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003856 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003857 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003858 case Type::STK_MemberPointer:
3859 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003860 }
3861 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003862
John McCall8cb679e2010-11-15 09:13:47 +00003863 case Type::STK_Floating:
3864 switch (DestTy->getScalarTypeKind()) {
3865 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003866 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003867 case Type::STK_Bool:
3868 return CK_FloatingToBoolean;
3869 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003870 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003871 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003872 Src = S.ImpCastExprToType(Src.take(),
3873 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003874 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003875 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003876 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003877 Src = S.ImpCastExprToType(Src.take(),
3878 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003879 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003880 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003881 case Type::STK_Pointer:
3882 llvm_unreachable("valid float->pointer cast?");
3883 case Type::STK_MemberPointer:
3884 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003885 }
3886 break;
3887
John McCall8cb679e2010-11-15 09:13:47 +00003888 case Type::STK_FloatingComplex:
3889 switch (DestTy->getScalarTypeKind()) {
3890 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003891 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003892 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003893 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003894 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003895 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003896 if (S.Context.hasSameType(ET, DestTy))
3897 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003898 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003899 return CK_FloatingCast;
3900 }
John McCall8cb679e2010-11-15 09:13:47 +00003901 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003902 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003903 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003904 Src = S.ImpCastExprToType(Src.take(),
3905 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003906 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003907 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003908 case Type::STK_Pointer:
3909 llvm_unreachable("valid complex float->pointer cast?");
3910 case Type::STK_MemberPointer:
3911 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003912 }
3913 break;
3914
John McCall8cb679e2010-11-15 09:13:47 +00003915 case Type::STK_IntegralComplex:
3916 switch (DestTy->getScalarTypeKind()) {
3917 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003918 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003919 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003920 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003921 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003922 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003923 if (S.Context.hasSameType(ET, DestTy))
3924 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003925 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003926 return CK_IntegralCast;
3927 }
John McCall8cb679e2010-11-15 09:13:47 +00003928 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003929 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003930 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003931 Src = S.ImpCastExprToType(Src.take(),
3932 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003933 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003934 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003935 case Type::STK_Pointer:
3936 llvm_unreachable("valid complex int->pointer cast?");
3937 case Type::STK_MemberPointer:
3938 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003939 }
3940 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003941 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003942
John McCalld7646252010-11-14 08:17:51 +00003943 llvm_unreachable("Unhandled scalar cast");
3944 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003945}
3946
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003947/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003948ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3949 QualType castType, Expr *castExpr,
3950 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003951 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003952 if (castExpr->getType() == Context.UnknownAnyTy)
3953 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3954
Sebastian Redl9f831db2009-07-25 15:41:38 +00003955 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003956 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003957 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003958 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003959 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003960
John McCall3aef3d82011-04-10 19:13:55 +00003961 assert(!castExpr->getType()->isPlaceholderType());
3962
John McCall7decc9e2010-11-18 06:31:45 +00003963 // We only support r-value casts in C.
3964 VK = VK_RValue;
3965
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003966 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3967 // type needs to be scalar.
3968 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003969 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003970 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3971 if (castExprRes.isInvalid())
3972 return ExprError();
3973 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003974
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003975 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003976 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003977 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003978 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
John Wiegley01296292011-04-08 18:41:53 +00003980 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3981 if (castExprRes.isInvalid())
3982 return ExprError();
3983 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003984
Eli Friedmane98194d2010-07-17 20:43:49 +00003985 if (RequireCompleteType(TyR.getBegin(), castType,
3986 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003987 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003988
Anders Carlssonef918ac2009-10-16 02:35:04 +00003989 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003990 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003991 (castType->isStructureType() || castType->isUnionType())) {
3992 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003993 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003994 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3995 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003996 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003997 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003998 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003999
Anders Carlsson525b76b2009-10-16 02:48:28 +00004000 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004001 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004002 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004003 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004004 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004005 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004006 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004007 castExpr->getType()) &&
4008 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004009 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4010 << castExpr->getSourceRange();
4011 break;
4012 }
4013 }
John Wiegley01296292011-04-08 18:41:53 +00004014 if (Field == FieldEnd) {
4015 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004016 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004017 return ExprError();
4018 }
John McCalle3027922010-08-25 11:45:40 +00004019 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004020 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004021 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004022
Anders Carlsson525b76b2009-10-16 02:48:28 +00004023 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004024 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004025 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004026 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004027 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004028
John McCalld7646252010-11-14 08:17:51 +00004029 // The type we're casting to is known to be a scalar or vector.
4030
4031 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004032 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004033 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004034 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004035 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004036 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004037 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004038 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004039
4040 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004041 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004042
Anton Yartsev28ccef72011-03-27 09:32:40 +00004043 if (castType->isVectorType()) {
4044 if (castType->getAs<VectorType>()->getVectorKind() ==
4045 VectorType::AltiVecVector &&
4046 (castExpr->getType()->isIntegerType() ||
4047 castExpr->getType()->isFloatingType())) {
4048 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004049 return Owned(castExpr);
4050 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4051 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004052 } else
John Wiegley01296292011-04-08 18:41:53 +00004053 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004054 }
John Wiegley01296292011-04-08 18:41:53 +00004055 if (castExpr->getType()->isVectorType()) {
4056 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4057 return ExprError();
4058 else
4059 return Owned(castExpr);
4060 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004061
John McCalld7646252010-11-14 08:17:51 +00004062 // The source and target types are both scalars, i.e.
4063 // - arithmetic types (fundamental, enum, and complex)
4064 // - all kinds of pointers
4065 // Note that member pointers were filtered out with C++, above.
4066
John Wiegley01296292011-04-08 18:41:53 +00004067 if (isa<ObjCSelectorExpr>(castExpr)) {
4068 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4069 return ExprError();
4070 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004071
John McCalld7646252010-11-14 08:17:51 +00004072 // If either type is a pointer, the other type has to be either an
4073 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004074 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004075 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004076 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004077 castExprType->isArithmeticType()) {
4078 Diag(castExpr->getLocStart(),
4079 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004080 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004081 return ExprError();
4082 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004083 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004084 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4085 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004086 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004087 return ExprError();
4088 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004089 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004090
John McCall31168b02011-06-15 23:02:42 +00004091 if (getLangOptions().ObjCAutoRefCount) {
4092 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4093 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4094 castType, castExpr, CCK_CStyleCast);
4095
4096 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4097 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4098 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4099 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4100 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4101 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4102 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4103 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004104 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004105 << castExprType << castType << AA_Casting
4106 << castExpr->getSourceRange();
4107
4108 return ExprError();
4109 }
4110 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004111 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004112 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4113 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004114 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004115 << castExprType << castType
4116 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004117 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004118 }
4119 }
4120
John Wiegley01296292011-04-08 18:41:53 +00004121 castExprRes = Owned(castExpr);
4122 Kind = PrepareScalarCast(*this, castExprRes, castType);
4123 if (castExprRes.isInvalid())
4124 return ExprError();
4125 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004126
John McCalld7646252010-11-14 08:17:51 +00004127 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004128 CheckCastAlign(castExpr, castType, TyR);
4129
John Wiegley01296292011-04-08 18:41:53 +00004130 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004131}
4132
Anders Carlsson525b76b2009-10-16 02:48:28 +00004133bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004134 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004135 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004136
Anders Carlssonde71adf2007-11-27 05:51:55 +00004137 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004138 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004139 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004140 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004141 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004142 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004143 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004144 } else
4145 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004146 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004147 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004148
John McCalle3027922010-08-25 11:45:40 +00004149 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004150 return false;
4151}
4152
John Wiegley01296292011-04-08 18:41:53 +00004153ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4154 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004155 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004156
Anders Carlsson43d70f82009-10-16 05:23:41 +00004157 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004158
Nate Begemanc8961a42009-06-27 22:05:55 +00004159 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4160 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004161 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004162 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4163 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004164 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004165 return ExprError();
4166 }
John McCalle3027922010-08-25 11:45:40 +00004167 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004168 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004169 }
4170
Nate Begemanbd956c42009-06-28 02:36:38 +00004171 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004172 // conversion will take place first from scalar to elt type, and then
4173 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004174 if (SrcTy->isPointerType())
4175 return Diag(R.getBegin(),
4176 diag::err_invalid_conversion_between_vector_and_scalar)
4177 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004178
4179 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004180 ExprResult CastExprRes = Owned(CastExpr);
4181 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4182 if (CastExprRes.isInvalid())
4183 return ExprError();
4184 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004185
John McCalle3027922010-08-25 11:45:40 +00004186 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004187 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004188}
4189
John McCalldadc5752010-08-24 06:29:42 +00004190ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004191Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4192 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004193 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004194 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004195 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004196
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004197 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4198 if (D.isInvalidType())
4199 return ExprError();
4200
4201 if (getLangOptions().CPlusPlus) {
4202 // Check that there are no default arguments (C++ only).
4203 CheckExtraCXXDefaultArguments(D);
4204 }
4205
4206 QualType castType = castTInfo->getType();
4207 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004208
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004209 bool isVectorLiteral = false;
4210
4211 // Check for an altivec or OpenCL literal,
4212 // i.e. all the elements are integer constants.
4213 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4214 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4215 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4216 if (PLE && PLE->getNumExprs() == 0) {
4217 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4218 return ExprError();
4219 }
4220 if (PE || PLE->getNumExprs() == 1) {
4221 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4222 if (!E->getType()->isVectorType())
4223 isVectorLiteral = true;
4224 }
4225 else
4226 isVectorLiteral = true;
4227 }
4228
4229 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4230 // then handle it as such.
4231 if (isVectorLiteral)
4232 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4233
Nate Begeman5ec4b312009-08-10 23:49:36 +00004234 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004235 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4236 // sequence of BinOp comma operators.
4237 if (isa<ParenListExpr>(castExpr)) {
4238 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4239 if (Result.isInvalid()) return ExprError();
4240 castExpr = Result.take();
4241 }
John McCallebe54742010-01-15 18:56:44 +00004242
John McCallb268a282010-08-23 23:25:46 +00004243 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004244}
4245
John McCalldadc5752010-08-24 06:29:42 +00004246ExprResult
John McCallebe54742010-01-15 18:56:44 +00004247Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004248 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004249 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004250 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004251 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004252 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004253 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4254 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004255 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004256 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004257 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004258
Richard Trieucfc491d2011-08-02 04:35:43 +00004259 return Owned(CStyleCastExpr::Create(
4260 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4261 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004262}
4263
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004264ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4265 SourceLocation RParenLoc, Expr *E,
4266 TypeSourceInfo *TInfo) {
4267 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4268 "Expected paren or paren list expression");
4269
4270 Expr **exprs;
4271 unsigned numExprs;
4272 Expr *subExpr;
4273 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4274 exprs = PE->getExprs();
4275 numExprs = PE->getNumExprs();
4276 } else {
4277 subExpr = cast<ParenExpr>(E)->getSubExpr();
4278 exprs = &subExpr;
4279 numExprs = 1;
4280 }
4281
4282 QualType Ty = TInfo->getType();
4283 assert(Ty->isVectorType() && "Expected vector type");
4284
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004285 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004286 const VectorType *VTy = Ty->getAs<VectorType>();
4287 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4288
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004289 // '(...)' form of vector initialization in AltiVec: the number of
4290 // initializers must be one or must match the size of the vector.
4291 // If a single value is specified in the initializer then it will be
4292 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004293 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004294 // The number of initializers must be one or must match the size of the
4295 // vector. If a single value is specified in the initializer then it will
4296 // be replicated to all the components of the vector
4297 if (numExprs == 1) {
4298 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4299 ExprResult Literal = Owned(exprs[0]);
4300 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4301 PrepareScalarCast(*this, Literal, ElemTy));
4302 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4303 }
4304 else if (numExprs < numElems) {
4305 Diag(E->getExprLoc(),
4306 diag::err_incorrect_number_of_vector_initializers);
4307 return ExprError();
4308 }
4309 else
4310 for (unsigned i = 0, e = numExprs; i != e; ++i)
4311 initExprs.push_back(exprs[i]);
4312 }
Tanya Lattner83559382011-07-15 23:07:01 +00004313 else {
4314 // For OpenCL, when the number of initializers is a single value,
4315 // it will be replicated to all components of the vector.
4316 if (getLangOptions().OpenCL &&
4317 VTy->getVectorKind() == VectorType::GenericVector &&
4318 numExprs == 1) {
4319 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4320 ExprResult Literal = Owned(exprs[0]);
4321 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4322 PrepareScalarCast(*this, Literal, ElemTy));
4323 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4324 }
4325
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004326 for (unsigned i = 0, e = numExprs; i != e; ++i)
4327 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004328 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004329 // FIXME: This means that pretty-printing the final AST will produce curly
4330 // braces instead of the original commas.
4331 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4332 &initExprs[0],
4333 initExprs.size(), RParenLoc);
4334 initE->setType(Ty);
4335 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4336}
4337
Nate Begeman5ec4b312009-08-10 23:49:36 +00004338/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4339/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004340ExprResult
John McCallb268a282010-08-23 23:25:46 +00004341Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004342 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4343 if (!E)
4344 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004345
John McCalldadc5752010-08-24 06:29:42 +00004346 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004347
Nate Begeman5ec4b312009-08-10 23:49:36 +00004348 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004349 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4350 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004351
John McCallb268a282010-08-23 23:25:46 +00004352 if (Result.isInvalid()) return ExprError();
4353
4354 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004355}
4356
John McCalldadc5752010-08-24 06:29:42 +00004357ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004358 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004359 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004360 unsigned nexprs = Val.size();
4361 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004362 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4363 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004364 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004365 expr = new (Context) ParenExpr(L, R, exprs[0]);
4366 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004367 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4368 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004369 return Owned(expr);
4370}
4371
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004372/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004373/// constant and the other is not a pointer. Returns true if a diagnostic is
4374/// emitted.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004375bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4376 SourceLocation QuestionLoc) {
4377 Expr *NullExpr = LHS;
4378 Expr *NonPointerExpr = RHS;
4379 Expr::NullPointerConstantKind NullKind =
4380 NullExpr->isNullPointerConstant(Context,
4381 Expr::NPC_ValueDependentIsNotNull);
4382
4383 if (NullKind == Expr::NPCK_NotNull) {
4384 NullExpr = RHS;
4385 NonPointerExpr = LHS;
4386 NullKind =
4387 NullExpr->isNullPointerConstant(Context,
4388 Expr::NPC_ValueDependentIsNotNull);
4389 }
4390
4391 if (NullKind == Expr::NPCK_NotNull)
4392 return false;
4393
4394 if (NullKind == Expr::NPCK_ZeroInteger) {
4395 // In this case, check to make sure that we got here from a "NULL"
4396 // string in the source code.
4397 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004398 SourceLocation loc = NullExpr->getExprLoc();
4399 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004400 return false;
4401 }
4402
4403 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4404 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4405 << NonPointerExpr->getType() << DiagType
4406 << NonPointerExpr->getSourceRange();
4407 return true;
4408}
4409
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004410/// \brief Return false if the condition expression is valid, true otherwise.
4411static bool checkCondition(Sema &S, Expr *Cond) {
4412 QualType CondTy = Cond->getType();
4413
4414 // C99 6.5.15p2
4415 if (CondTy->isScalarType()) return false;
4416
4417 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4418 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4419 return false;
4420
4421 // Emit the proper error message.
4422 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4423 diag::err_typecheck_cond_expect_scalar :
4424 diag::err_typecheck_cond_expect_scalar_or_vector)
4425 << CondTy;
4426 return true;
4427}
4428
4429/// \brief Return false if the two expressions can be converted to a vector,
4430/// true otherwise
4431static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4432 ExprResult &RHS,
4433 QualType CondTy) {
4434 // Both operands should be of scalar type.
4435 if (!LHS.get()->getType()->isScalarType()) {
4436 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4437 << CondTy;
4438 return true;
4439 }
4440 if (!RHS.get()->getType()->isScalarType()) {
4441 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4442 << CondTy;
4443 return true;
4444 }
4445
4446 // Implicity convert these scalars to the type of the condition.
4447 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4448 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4449 return false;
4450}
4451
4452/// \brief Handle when one or both operands are void type.
4453static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4454 ExprResult &RHS) {
4455 Expr *LHSExpr = LHS.get();
4456 Expr *RHSExpr = RHS.get();
4457
4458 if (!LHSExpr->getType()->isVoidType())
4459 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4460 << RHSExpr->getSourceRange();
4461 if (!RHSExpr->getType()->isVoidType())
4462 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4463 << LHSExpr->getSourceRange();
4464 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4465 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4466 return S.Context.VoidTy;
4467}
4468
4469/// \brief Return false if the NullExpr can be promoted to PointerTy,
4470/// true otherwise.
4471static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4472 QualType PointerTy) {
4473 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4474 !NullExpr.get()->isNullPointerConstant(S.Context,
4475 Expr::NPC_ValueDependentIsNull))
4476 return true;
4477
4478 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4479 return false;
4480}
4481
4482/// \brief Checks compatibility between two pointers and return the resulting
4483/// type.
4484static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4485 ExprResult &RHS,
4486 SourceLocation Loc) {
4487 QualType LHSTy = LHS.get()->getType();
4488 QualType RHSTy = RHS.get()->getType();
4489
4490 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4491 // Two identical pointers types are always compatible.
4492 return LHSTy;
4493 }
4494
4495 QualType lhptee, rhptee;
4496
4497 // Get the pointee types.
4498 if (LHSTy->isBlockPointerType()) {
4499 lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4500 rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4501 } else {
4502 lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4503 rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4504 }
4505
4506 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4507 rhptee.getUnqualifiedType())) {
4508 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4509 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4510 << RHS.get()->getSourceRange();
4511 // In this situation, we assume void* type. No especially good
4512 // reason, but this is what gcc does, and we do have to pick
4513 // to get a consistent AST.
4514 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4515 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4516 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4517 return incompatTy;
4518 }
4519
4520 // The pointer types are compatible.
4521 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4522 // differently qualified versions of compatible types, the result type is
4523 // a pointer to an appropriately qualified version of the *composite*
4524 // type.
4525 // FIXME: Need to calculate the composite type.
4526 // FIXME: Need to add qualifiers
4527
4528 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4529 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4530 return LHSTy;
4531}
4532
4533/// \brief Return the resulting type when the operands are both block pointers.
4534static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4535 ExprResult &LHS,
4536 ExprResult &RHS,
4537 SourceLocation Loc) {
4538 QualType LHSTy = LHS.get()->getType();
4539 QualType RHSTy = RHS.get()->getType();
4540
4541 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4542 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4543 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4544 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4545 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4546 return destType;
4547 }
4548 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4549 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4550 << RHS.get()->getSourceRange();
4551 return QualType();
4552 }
4553
4554 // We have 2 block pointer types.
4555 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4556}
4557
4558/// \brief Return the resulting type when the operands are both pointers.
4559static QualType
4560checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4561 ExprResult &RHS,
4562 SourceLocation Loc) {
4563 // get the pointer types
4564 QualType LHSTy = LHS.get()->getType();
4565 QualType RHSTy = RHS.get()->getType();
4566
4567 // get the "pointed to" types
4568 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4569 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4570
4571 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4572 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4573 // Figure out necessary qualifiers (C99 6.5.15p6)
4574 QualType destPointee
4575 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4576 QualType destType = S.Context.getPointerType(destPointee);
4577 // Add qualifiers if necessary.
4578 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4579 // Promote to void*.
4580 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4581 return destType;
4582 }
4583 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4584 QualType destPointee
4585 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4586 QualType destType = S.Context.getPointerType(destPointee);
4587 // Add qualifiers if necessary.
4588 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4589 // Promote to void*.
4590 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4591 return destType;
4592 }
4593
4594 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4595}
4596
4597/// \brief Return false if the first expression is not an integer and the second
4598/// expression is not a pointer, true otherwise.
4599static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4600 Expr* PointerExpr, SourceLocation Loc,
4601 bool isIntFirstExpr) {
4602 if (!PointerExpr->getType()->isPointerType() ||
4603 !Int.get()->getType()->isIntegerType())
4604 return false;
4605
4606 Expr *Expr1 = isIntFirstExpr ? Int.get() : PointerExpr;
4607 Expr *Expr2 = isIntFirstExpr ? PointerExpr : Int.get();
4608
4609 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4610 << Expr1->getType() << Expr2->getType()
4611 << Expr1->getSourceRange() << Expr2->getSourceRange();
4612 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4613 CK_IntegralToPointer);
4614 return true;
4615}
4616
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004617/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4618/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004619/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004620QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4621 ExprResult &RHS, ExprValueKind &VK,
4622 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004623 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004624
John McCall3aef3d82011-04-10 19:13:55 +00004625 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004626 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004627 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004628
John McCall3aef3d82011-04-10 19:13:55 +00004629 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004630 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004631 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004632
Sebastian Redl1a99f442009-04-16 17:51:27 +00004633 // C++ is sufficiently different to merit its own checker.
4634 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004635 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004636
4637 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004638 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004639
John Wiegley01296292011-04-08 18:41:53 +00004640 Cond = UsualUnaryConversions(Cond.take());
4641 if (Cond.isInvalid())
4642 return QualType();
4643 LHS = UsualUnaryConversions(LHS.take());
4644 if (LHS.isInvalid())
4645 return QualType();
4646 RHS = UsualUnaryConversions(RHS.take());
4647 if (RHS.isInvalid())
4648 return QualType();
4649
4650 QualType CondTy = Cond.get()->getType();
4651 QualType LHSTy = LHS.get()->getType();
4652 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004653
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004654 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004655 if (checkCondition(*this, Cond.get()))
4656 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004657
Chris Lattnere2949f42008-01-06 22:42:25 +00004658 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004659 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004660 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004661
Nate Begemanabb5a732010-09-20 22:41:17 +00004662 // OpenCL: If the condition is a vector, and both operands are scalar,
4663 // attempt to implicity convert them to the vector type to act like the
4664 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004665 if (getLangOptions().OpenCL && CondTy->isVectorType())
4666 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004667 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004668
Chris Lattnere2949f42008-01-06 22:42:25 +00004669 // If both operands have arithmetic type, do the usual arithmetic conversions
4670 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004671 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4672 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004673 if (LHS.isInvalid() || RHS.isInvalid())
4674 return QualType();
4675 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004676 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004677
Chris Lattnere2949f42008-01-06 22:42:25 +00004678 // If both operands are the same structure or union type, the result is that
4679 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004680 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4681 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004682 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004684 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004685 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004686 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004687 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004688
Chris Lattnere2949f42008-01-06 22:42:25 +00004689 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004690 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004691 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004692 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004693 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004694
Steve Naroff039ad3c2008-01-08 01:11:38 +00004695 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4696 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004697 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4698 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004699
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004700 // All objective-c pointer type analysis is done here.
4701 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4702 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004703 if (LHS.isInvalid() || RHS.isInvalid())
4704 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004705 if (!compositeType.isNull())
4706 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004707
4708
Steve Naroff05efa972009-07-01 14:36:47 +00004709 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004710 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4711 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4712 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713
Steve Naroff05efa972009-07-01 14:36:47 +00004714 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004715 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4716 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4717 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004718
John McCalle84af4e2010-11-13 01:35:44 +00004719 // GCC compatibility: soften pointer/integer mismatch. Note that
4720 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004721 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4722 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004723 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004724 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4725 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004726 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004727
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004728 // Emit a better diagnostic if one of the expressions is a null pointer
4729 // constant and the other is not a pointer type. In this case, the user most
4730 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004731 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004732 return QualType();
4733
Chris Lattnere2949f42008-01-06 22:42:25 +00004734 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004735 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004736 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4737 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004738 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004739}
4740
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004741/// FindCompositeObjCPointerType - Helper method to find composite type of
4742/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004743QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004744 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004745 QualType LHSTy = LHS.get()->getType();
4746 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004747
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004748 // Handle things like Class and struct objc_class*. Here we case the result
4749 // to the pseudo-builtin, because that will be implicitly cast back to the
4750 // redefinition type if an attempt is made to access its fields.
4751 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004752 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004753 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004754 return LHSTy;
4755 }
4756 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004757 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004758 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004759 return RHSTy;
4760 }
4761 // And the same for struct objc_object* / id
4762 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004763 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004764 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004765 return LHSTy;
4766 }
4767 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004768 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004769 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004770 return RHSTy;
4771 }
4772 // And the same for struct objc_selector* / SEL
4773 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004774 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004775 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004776 return LHSTy;
4777 }
4778 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004779 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004780 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004781 return RHSTy;
4782 }
4783 // Check constraints for Objective-C object pointers types.
4784 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004785
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004786 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4787 // Two identical object pointer types are always compatible.
4788 return LHSTy;
4789 }
4790 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4791 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4792 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004793
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004794 // If both operands are interfaces and either operand can be
4795 // assigned to the other, use that type as the composite
4796 // type. This allows
4797 // xxx ? (A*) a : (B*) b
4798 // where B is a subclass of A.
4799 //
4800 // Additionally, as for assignment, if either type is 'id'
4801 // allow silent coercion. Finally, if the types are
4802 // incompatible then make sure to use 'id' as the composite
4803 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004804
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004805 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4806 // It could return the composite type.
4807 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4808 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4809 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4810 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4811 } else if ((LHSTy->isObjCQualifiedIdType() ||
4812 RHSTy->isObjCQualifiedIdType()) &&
4813 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4814 // Need to handle "id<xx>" explicitly.
4815 // GCC allows qualified id and any Objective-C type to devolve to
4816 // id. Currently localizing to here until clear this should be
4817 // part of ObjCQualifiedIdTypesAreCompatible.
4818 compositeType = Context.getObjCIdType();
4819 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4820 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004821 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004822 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4823 ;
4824 else {
4825 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4826 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004827 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004828 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004829 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4830 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004831 return incompatTy;
4832 }
4833 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004834 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4835 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004836 return compositeType;
4837 }
4838 // Check Objective-C object pointer types and 'void *'
4839 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4840 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4841 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4842 QualType destPointee
4843 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4844 QualType destType = Context.getPointerType(destPointee);
4845 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004846 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004847 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004848 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 return destType;
4850 }
4851 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4852 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4853 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4854 QualType destPointee
4855 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4856 QualType destType = Context.getPointerType(destPointee);
4857 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004858 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004859 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004860 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004861 return destType;
4862 }
4863 return QualType();
4864}
4865
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004866/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004867/// ParenRange in parentheses.
4868static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004869 const PartialDiagnostic &Note,
4870 SourceRange ParenRange) {
4871 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4872 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4873 EndLoc.isValid()) {
4874 Self.Diag(Loc, Note)
4875 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4876 << FixItHint::CreateInsertion(EndLoc, ")");
4877 } else {
4878 // We can't display the parentheses, so just show the bare note.
4879 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004880 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004881}
4882
4883static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4884 return Opc >= BO_Mul && Opc <= BO_Shr;
4885}
4886
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004887/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4888/// expression, either using a built-in or overloaded operator,
4889/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4890static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4891 Expr **RHS) {
4892 E = E->IgnoreParenImpCasts();
4893 E = E->IgnoreConversionOperator();
4894 E = E->IgnoreParenImpCasts();
4895
4896 // Built-in binary operator.
4897 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4898 if (IsArithmeticOp(OP->getOpcode())) {
4899 *Opcode = OP->getOpcode();
4900 *RHS = OP->getRHS();
4901 return true;
4902 }
4903 }
4904
4905 // Overloaded operator.
4906 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4907 if (Call->getNumArgs() != 2)
4908 return false;
4909
4910 // Make sure this is really a binary operator that is safe to pass into
4911 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4912 OverloadedOperatorKind OO = Call->getOperator();
4913 if (OO < OO_Plus || OO > OO_Arrow)
4914 return false;
4915
4916 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4917 if (IsArithmeticOp(OpKind)) {
4918 *Opcode = OpKind;
4919 *RHS = Call->getArg(1);
4920 return true;
4921 }
4922 }
4923
4924 return false;
4925}
4926
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004927static bool IsLogicOp(BinaryOperatorKind Opc) {
4928 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4929}
4930
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004931/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4932/// or is a logical expression such as (x==y) which has int type, but is
4933/// commonly interpreted as boolean.
4934static bool ExprLooksBoolean(Expr *E) {
4935 E = E->IgnoreParenImpCasts();
4936
4937 if (E->getType()->isBooleanType())
4938 return true;
4939 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4940 return IsLogicOp(OP->getOpcode());
4941 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4942 return OP->getOpcode() == UO_LNot;
4943
4944 return false;
4945}
4946
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004947/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4948/// and binary operator are mixed in a way that suggests the programmer assumed
4949/// the conditional operator has higher precedence, for example:
4950/// "int x = a + someBinaryCondition ? 1 : 2".
4951static void DiagnoseConditionalPrecedence(Sema &Self,
4952 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004953 Expr *Condition,
4954 Expr *LHS,
4955 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004956 BinaryOperatorKind CondOpcode;
4957 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004958
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004959 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004960 return;
4961 if (!ExprLooksBoolean(CondRHS))
4962 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004963
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004964 // The condition is an arithmetic binary expression, with a right-
4965 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004966
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004967 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004968 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004969 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004970
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004971 SuggestParentheses(Self, OpLoc,
4972 Self.PDiag(diag::note_precedence_conditional_silence)
4973 << BinaryOperator::getOpcodeStr(CondOpcode),
4974 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004975
4976 SuggestParentheses(Self, OpLoc,
4977 Self.PDiag(diag::note_precedence_conditional_first),
4978 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004979}
4980
Steve Naroff83895f72007-09-16 03:34:24 +00004981/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004982/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004983ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004984 SourceLocation ColonLoc,
4985 Expr *CondExpr, Expr *LHSExpr,
4986 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004987 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4988 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004989 OpaqueValueExpr *opaqueValue = 0;
4990 Expr *commonExpr = 0;
4991 if (LHSExpr == 0) {
4992 commonExpr = CondExpr;
4993
4994 // We usually want to apply unary conversions *before* saving, except
4995 // in the special case of a C++ l-value conditional.
4996 if (!(getLangOptions().CPlusPlus
4997 && !commonExpr->isTypeDependent()
4998 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4999 && commonExpr->isGLValue()
5000 && commonExpr->isOrdinaryOrBitFieldObject()
5001 && RHSExpr->isOrdinaryOrBitFieldObject()
5002 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005003 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5004 if (commonRes.isInvalid())
5005 return ExprError();
5006 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005007 }
5008
5009 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5010 commonExpr->getType(),
5011 commonExpr->getValueKind(),
5012 commonExpr->getObjectKind());
5013 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005014 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005015
John McCall7decc9e2010-11-18 06:31:45 +00005016 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005017 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005018 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5019 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005020 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005021 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5022 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005023 return ExprError();
5024
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005025 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5026 RHS.get());
5027
John McCallc07a0c72011-02-17 10:25:35 +00005028 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005029 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5030 LHS.take(), ColonLoc,
5031 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005032
5033 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005034 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005035 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5036 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005037}
5038
John McCallaba90822011-01-31 23:13:11 +00005039// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005040// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005041// routine is it effectively iqnores the qualifiers on the top level pointee.
5042// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5043// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005044static Sema::AssignConvertType
5045checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5046 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5047 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005048
Steve Naroff1f4d7272007-05-11 04:00:31 +00005049 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005050 const Type *lhptee, *rhptee;
5051 Qualifiers lhq, rhq;
5052 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5053 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005054
John McCallaba90822011-01-31 23:13:11 +00005055 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005056
5057 // C99 6.5.16.1p1: This following citation is common to constraints
5058 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5059 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005060 Qualifiers lq;
5061
John McCall31168b02011-06-15 23:02:42 +00005062 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5063 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5064 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5065 // Ignore lifetime for further calculation.
5066 lhq.removeObjCLifetime();
5067 rhq.removeObjCLifetime();
5068 }
5069
John McCall4fff8f62011-02-01 00:10:29 +00005070 if (!lhq.compatiblyIncludes(rhq)) {
5071 // Treat address-space mismatches as fatal. TODO: address subspaces
5072 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5073 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5074
John McCall31168b02011-06-15 23:02:42 +00005075 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005076 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005077 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5078 .compatiblyIncludes(
5079 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005080 && (lhptee->isVoidType() || rhptee->isVoidType()))
5081 ; // keep old
5082
John McCall31168b02011-06-15 23:02:42 +00005083 // Treat lifetime mismatches as fatal.
5084 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5085 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5086
John McCall4fff8f62011-02-01 00:10:29 +00005087 // For GCC compatibility, other qualifier mismatches are treated
5088 // as still compatible in C.
5089 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5090 }
Steve Naroff3f597292007-05-11 22:18:03 +00005091
Mike Stump4e1f26a2009-02-19 03:04:26 +00005092 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5093 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005094 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005095 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005096 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005097 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005098
Chris Lattner0a788432008-01-03 22:56:36 +00005099 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005100 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005101 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005102 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005103
Chris Lattner0a788432008-01-03 22:56:36 +00005104 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005105 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005106 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005107
5108 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005109 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005110 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005111 }
John McCall4fff8f62011-02-01 00:10:29 +00005112
Mike Stump4e1f26a2009-02-19 03:04:26 +00005113 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005114 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005115 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5116 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005117 // Check if the pointee types are compatible ignoring the sign.
5118 // We explicitly check for char so that we catch "char" vs
5119 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005120 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005121 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005122 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005123 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005124
Chris Lattnerec3a1562009-10-17 20:33:28 +00005125 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005126 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005127 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005128 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005129
John McCall4fff8f62011-02-01 00:10:29 +00005130 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005131 // Types are compatible ignoring the sign. Qualifier incompatibility
5132 // takes priority over sign incompatibility because the sign
5133 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005134 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005135 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005136
John McCallaba90822011-01-31 23:13:11 +00005137 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005138 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005139
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005140 // If we are a multi-level pointer, it's possible that our issue is simply
5141 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5142 // the eventual target type is the same and the pointers have the same
5143 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005144 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005145 do {
John McCall4fff8f62011-02-01 00:10:29 +00005146 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5147 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005148 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005149
John McCall4fff8f62011-02-01 00:10:29 +00005150 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005151 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005152 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005153
Eli Friedman80160bd2009-03-22 23:59:44 +00005154 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005155 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005156 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005157 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005158}
5159
John McCallaba90822011-01-31 23:13:11 +00005160/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005161/// block pointer types are compatible or whether a block and normal pointer
5162/// are compatible. It is more restrict than comparing two function pointer
5163// types.
John McCallaba90822011-01-31 23:13:11 +00005164static Sema::AssignConvertType
5165checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5166 QualType rhsType) {
5167 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5168 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5169
Steve Naroff081c7422008-09-04 15:10:53 +00005170 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005171
Steve Naroff081c7422008-09-04 15:10:53 +00005172 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005173 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5174 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005175
John McCallaba90822011-01-31 23:13:11 +00005176 // In C++, the types have to match exactly.
5177 if (S.getLangOptions().CPlusPlus)
5178 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005179
John McCallaba90822011-01-31 23:13:11 +00005180 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005181
Steve Naroff081c7422008-09-04 15:10:53 +00005182 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005183 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5184 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005185
John McCallaba90822011-01-31 23:13:11 +00005186 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5187 return Sema::IncompatibleBlockPointer;
5188
Steve Naroff081c7422008-09-04 15:10:53 +00005189 return ConvTy;
5190}
5191
John McCallaba90822011-01-31 23:13:11 +00005192/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005193/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005194static Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005195checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5196 QualType rhsType) {
John McCallaba90822011-01-31 23:13:11 +00005197 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5198 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5199
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005200 if (lhsType->isObjCBuiltinType()) {
5201 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005202 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5203 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005204 return Sema::IncompatiblePointer;
5205 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005206 }
5207 if (rhsType->isObjCBuiltinType()) {
5208 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005209 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5210 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005211 return Sema::IncompatiblePointer;
5212 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005213 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005214 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005215 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005216 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005217 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005218
John McCallaba90822011-01-31 23:13:11 +00005219 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5220 return Sema::CompatiblePointerDiscardsQualifiers;
5221
5222 if (S.Context.typesAreCompatible(lhsType, rhsType))
5223 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005224 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005225 return Sema::IncompatibleObjCQualifiedId;
5226 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005227}
5228
John McCall29600e12010-11-16 02:32:08 +00005229Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005230Sema::CheckAssignmentConstraints(SourceLocation Loc,
5231 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005232 // Fake up an opaque expression. We don't actually care about what
5233 // cast operations are required, so if CheckAssignmentConstraints
5234 // adds casts to this they'll be wasted, but fortunately that doesn't
5235 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005236 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005237 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005238 CastKind K = CK_Invalid;
5239
5240 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5241}
5242
Mike Stump4e1f26a2009-02-19 03:04:26 +00005243/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5244/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005245/// pointers. Here are some objectionable examples that GCC considers warnings:
5246///
5247/// int a, *pint;
5248/// short *pshort;
5249/// struct foo *pfoo;
5250///
5251/// pint = pshort; // warning: assignment from incompatible pointer type
5252/// a = pint; // warning: assignment makes integer from pointer without a cast
5253/// pint = a; // warning: assignment makes pointer from integer without a cast
5254/// pint = pfoo; // warning: assignment from incompatible pointer type
5255///
5256/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005258///
John McCall8cb679e2010-11-15 09:13:47 +00005259/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005260Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005261Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005262 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005263 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005264 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005265
Chris Lattnera52c2f22008-01-04 23:18:45 +00005266 // Get canonical types. We're not formatting these types, just comparing
5267 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005268 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5269 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005270
John McCalle5255932011-01-31 22:28:28 +00005271 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005272 if (lhsType == rhsType) {
5273 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005274 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005275 }
5276
Douglas Gregor6b754842008-10-28 00:22:11 +00005277 // If the left-hand side is a reference type, then we are in a
5278 // (rare!) case where we've allowed the use of references in C,
5279 // e.g., as a parameter type in a built-in function. In this case,
5280 // just make sure that the type referenced is compatible with the
5281 // right-hand side type. The caller is responsible for adjusting
5282 // lhsType so that the resulting expression does not have reference
5283 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005284 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005285 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5286 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005287 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005288 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005289 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005290 }
John McCalle5255932011-01-31 22:28:28 +00005291
Nate Begemanbd956c42009-06-28 02:36:38 +00005292 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5293 // to the same ExtVector type.
5294 if (lhsType->isExtVectorType()) {
5295 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005296 return Incompatible;
5297 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005298 // CK_VectorSplat does T -> vector T, so first cast to the
5299 // element type.
5300 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5301 if (elType != rhsType) {
5302 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005303 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005304 }
5305 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005306 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005307 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
John McCalle5255932011-01-31 22:28:28 +00005310 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005311 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005312 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005313 // Allow assignments of an AltiVec vector type to an equivalent GCC
5314 // vector type and vice versa
5315 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5316 Kind = CK_BitCast;
5317 return Compatible;
5318 }
5319
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005320 // If we are allowing lax vector conversions, and LHS and RHS are both
5321 // vectors, the total size only needs to be the same. This is a bitcast;
5322 // no bits are changed but the result type is different.
5323 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005324 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005325 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005326 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005327 }
Chris Lattner881a2122008-01-04 23:32:24 +00005328 }
5329 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005330 }
Eli Friedman3360d892008-05-30 18:07:22 +00005331
John McCalle5255932011-01-31 22:28:28 +00005332 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005333 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005334 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005335 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005336 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005337 }
Eli Friedman3360d892008-05-30 18:07:22 +00005338
John McCalle5255932011-01-31 22:28:28 +00005339 // Conversions to normal pointers.
5340 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5341 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005342 if (isa<PointerType>(rhsType)) {
5343 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005344 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005345 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005346
John McCalle5255932011-01-31 22:28:28 +00005347 // int -> T*
5348 if (rhsType->isIntegerType()) {
5349 Kind = CK_IntegralToPointer; // FIXME: null?
5350 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005351 }
John McCalle5255932011-01-31 22:28:28 +00005352
5353 // C pointers are not compatible with ObjC object pointers,
5354 // with two exceptions:
5355 if (isa<ObjCObjectPointerType>(rhsType)) {
5356 // - conversions to void*
5357 if (lhsPointer->getPointeeType()->isVoidType()) {
5358 Kind = CK_AnyPointerToObjCPointerCast;
5359 return Compatible;
5360 }
5361
5362 // - conversions from 'Class' to the redefinition type
5363 if (rhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005364 Context.hasSameType(lhsType,
5365 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005366 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005367 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005368 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005369
John McCalle5255932011-01-31 22:28:28 +00005370 Kind = CK_BitCast;
5371 return IncompatiblePointer;
5372 }
5373
5374 // U^ -> void*
5375 if (rhsType->getAs<BlockPointerType>()) {
5376 if (lhsPointer->getPointeeType()->isVoidType()) {
5377 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005378 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005379 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005380 }
John McCalle5255932011-01-31 22:28:28 +00005381
Steve Naroff081c7422008-09-04 15:10:53 +00005382 return Incompatible;
5383 }
5384
John McCalle5255932011-01-31 22:28:28 +00005385 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005386 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005387 // U^ -> T^
5388 if (rhsType->isBlockPointerType()) {
5389 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005390 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005391 }
5392
5393 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005394 if (rhsType->isIntegerType()) {
5395 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005396 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005397 }
5398
John McCalle5255932011-01-31 22:28:28 +00005399 // id -> T^
5400 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5401 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005402 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005403 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005404
John McCalle5255932011-01-31 22:28:28 +00005405 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005406 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005407 if (RHSPT->getPointeeType()->isVoidType()) {
5408 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005409 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005410 }
John McCall8cb679e2010-11-15 09:13:47 +00005411
Chris Lattnera52c2f22008-01-04 23:18:45 +00005412 return Incompatible;
5413 }
5414
John McCalle5255932011-01-31 22:28:28 +00005415 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005416 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005417 // A* -> B*
5418 if (rhsType->isObjCObjectPointerType()) {
5419 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005420 Sema::AssignConvertType result =
5421 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5422 if (getLangOptions().ObjCAutoRefCount &&
5423 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005424 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5425 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005426 return result;
John McCalle5255932011-01-31 22:28:28 +00005427 }
5428
5429 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005430 if (rhsType->isIntegerType()) {
5431 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005432 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005433 }
5434
John McCalle5255932011-01-31 22:28:28 +00005435 // In general, C pointers are not compatible with ObjC object pointers,
5436 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005437 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005438 // - conversions from 'void*'
5439 if (rhsType->isVoidPointerType()) {
5440 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005441 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005442 }
5443
5444 // - conversions to 'Class' from its redefinition type
5445 if (lhsType->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005446 Context.hasSameType(rhsType,
5447 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005448 Kind = CK_BitCast;
5449 return Compatible;
5450 }
5451
5452 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005453 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005454 }
John McCalle5255932011-01-31 22:28:28 +00005455
5456 // T^ -> A*
5457 if (rhsType->isBlockPointerType()) {
5458 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005459 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005460 }
5461
Steve Naroff7cae42b2009-07-10 23:34:53 +00005462 return Incompatible;
5463 }
John McCalle5255932011-01-31 22:28:28 +00005464
5465 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005466 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005467 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005468 if (lhsType == Context.BoolTy) {
5469 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005470 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005471 }
Eli Friedman3360d892008-05-30 18:07:22 +00005472
John McCalle5255932011-01-31 22:28:28 +00005473 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005474 if (lhsType->isIntegerType()) {
5475 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005476 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478
Chris Lattnera52c2f22008-01-04 23:18:45 +00005479 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005480 }
John McCalle5255932011-01-31 22:28:28 +00005481
5482 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005483 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005484 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005485 if (lhsType == Context.BoolTy) {
5486 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005487 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005488 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489
John McCalle5255932011-01-31 22:28:28 +00005490 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005491 if (lhsType->isIntegerType()) {
5492 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005493 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005494 }
5495
Steve Naroff7cae42b2009-07-10 23:34:53 +00005496 return Incompatible;
5497 }
Eli Friedman3360d892008-05-30 18:07:22 +00005498
John McCalle5255932011-01-31 22:28:28 +00005499 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005500 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005501 if (Context.typesAreCompatible(lhsType, rhsType)) {
5502 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005503 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005504 }
Bill Wendling216423b2007-05-30 06:30:29 +00005505 }
John McCalle5255932011-01-31 22:28:28 +00005506
Steve Naroff98cf3e92007-06-06 18:38:38 +00005507 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005508}
5509
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005510/// \brief Constructs a transparent union from an expression that is
5511/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005512static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5513 ExprResult &EResult, QualType UnionType,
5514 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005515 // Build an initializer list that designates the appropriate member
5516 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005517 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005518 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005519 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005520 SourceLocation());
5521 Initializer->setType(UnionType);
5522 Initializer->setInitializedFieldInUnion(Field);
5523
5524 // Build a compound literal constructing a value of the transparent
5525 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005526 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005527 EResult = S.Owned(
5528 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5529 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005530}
5531
5532Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005533Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5534 ExprResult &rExpr) {
John Wiegley01296292011-04-08 18:41:53 +00005535 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005536
Mike Stump11289f42009-09-09 15:08:12 +00005537 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005538 // transparent_union GCC extension.
5539 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005540 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005541 return Incompatible;
5542
5543 // The field to initialize within the transparent union.
5544 RecordDecl *UD = UT->getDecl();
5545 FieldDecl *InitField = 0;
5546 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005547 for (RecordDecl::field_iterator it = UD->field_begin(),
5548 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005549 it != itend; ++it) {
5550 if (it->getType()->isPointerType()) {
5551 // If the transparent union contains a pointer type, we allow:
5552 // 1) void pointer
5553 // 2) null pointer constant
5554 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005555 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005556 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005557 InitField = *it;
5558 break;
5559 }
Mike Stump11289f42009-09-09 15:08:12 +00005560
John Wiegley01296292011-04-08 18:41:53 +00005561 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005562 Expr::NPC_ValueDependentIsNull)) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005563 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5564 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005565 InitField = *it;
5566 break;
5567 }
5568 }
5569
John McCall8cb679e2010-11-15 09:13:47 +00005570 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005571 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005572 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005573 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005574 InitField = *it;
5575 break;
5576 }
5577 }
5578
5579 if (!InitField)
5580 return Incompatible;
5581
John Wiegley01296292011-04-08 18:41:53 +00005582 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005583 return Compatible;
5584}
5585
Chris Lattner9bad62c2008-01-04 18:04:52 +00005586Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005587Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005588 if (getLangOptions().CPlusPlus) {
5589 if (!lhsType->isRecordType()) {
5590 // C++ 5.17p3: If the left operand is not of class type, the
5591 // expression is implicitly converted (C++ 4) to the
5592 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005593 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5594 lhsType.getUnqualifiedType(),
5595 AA_Assigning);
5596 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005597 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005598 Sema::AssignConvertType result = Compatible;
5599 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005600 !CheckObjCARCUnavailableWeakConversion(lhsType,
5601 rExpr.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005602 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005603 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005604 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005605 }
5606
5607 // FIXME: Currently, we fall through and treat C++ classes like C
5608 // structures.
John McCall34376a62010-12-04 03:47:34 +00005609 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005610
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005611 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5612 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005613 if ((lhsType->isPointerType() ||
5614 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005615 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005616 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005617 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005618 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005619 return Compatible;
5620 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005621
Chris Lattnere6dcd502007-10-16 02:55:40 +00005622 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005623 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005624 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005625 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005626 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005627 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005628 if (!lhsType->isReferenceType()) {
5629 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5630 if (rExpr.isInvalid())
5631 return Incompatible;
5632 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005633
John McCall8cb679e2010-11-15 09:13:47 +00005634 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005635 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005636 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005638 // C99 6.5.16.1p2: The value of the right operand is converted to the
5639 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005640 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5641 // so that we can use references in built-in functions even in C.
5642 // The getNonReferenceType() call makes sure that the resulting expression
5643 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005644 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieucfc491d2011-08-02 04:35:43 +00005645 rExpr = ImpCastExprToType(rExpr.take(),
5646 lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005647 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005648}
5649
Richard Trieucfc491d2011-08-02 04:35:43 +00005650QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5651 ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005652 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005653 << lex.get()->getType() << rex.get()->getType()
5654 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005655 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005656}
5657
Eli Friedman1408bc92011-06-23 18:10:35 +00005658QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5659 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005660 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005661 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005662 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005663 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005664 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005665 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005666
Nate Begeman191a6b12008-07-14 18:02:46 +00005667 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005668 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005669 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005670
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005671 // Handle the case of equivalent AltiVec and GCC vector types
5672 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5673 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005674 if (lhsType->isExtVectorType()) {
5675 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5676 return lhsType;
5677 }
5678
5679 if (!isCompAssign)
5680 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005681 return rhsType;
5682 }
5683
Eli Friedman1408bc92011-06-23 18:10:35 +00005684 if (getLangOptions().LaxVectorConversions &&
5685 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5686 // If we are allowing lax vector conversions, and LHS and RHS are both
5687 // vectors, the total size only needs to be the same. This is a
5688 // bitcast; no bits are changed but the result type is different.
5689 // FIXME: Should we really be allowing this?
5690 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5691 return lhsType;
5692 }
5693
Nate Begemanbd956c42009-06-28 02:36:38 +00005694 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5695 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5696 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005697 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005698 swapped = true;
5699 std::swap(rex, lex);
5700 std::swap(rhsType, lhsType);
5701 }
Mike Stump11289f42009-09-09 15:08:12 +00005702
Nate Begeman886448d2009-06-28 19:12:57 +00005703 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005704 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005705 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005706 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005707 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5708 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005709 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005710 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005711 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005712 if (swapped) std::swap(rex, lex);
5713 return lhsType;
5714 }
5715 }
5716 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5717 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005718 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5719 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005720 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005721 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005722 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005723 if (swapped) std::swap(rex, lex);
5724 return lhsType;
5725 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005726 }
5727 }
Mike Stump11289f42009-09-09 15:08:12 +00005728
Nate Begeman886448d2009-06-28 19:12:57 +00005729 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005730 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005731 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005732 << lex.get()->getType() << rex.get()->getType()
5733 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005734 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005735}
5736
Richard Trieucfc491d2011-08-02 04:35:43 +00005737QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5738 SourceLocation Loc,
5739 bool isCompAssign, bool isDiv) {
5740 if (lex.get()->getType()->isVectorType() ||
5741 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005742 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005743
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005744 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005745 if (lex.isInvalid() || rex.isInvalid())
5746 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005747
John Wiegley01296292011-04-08 18:41:53 +00005748 if (!lex.get()->getType()->isArithmeticType() ||
5749 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005750 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005751
Chris Lattnerfaa54172010-01-12 21:23:57 +00005752 // Check for division by zero.
5753 if (isDiv &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005754 rex.get()->isNullPointerConstant(Context,
5755 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005756 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieucfc491d2011-08-02 04:35:43 +00005757 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005758
Chris Lattnerfaa54172010-01-12 21:23:57 +00005759 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005760}
5761
Chris Lattnerfaa54172010-01-12 21:23:57 +00005762QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005763 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005764 if (lex.get()->getType()->isVectorType() ||
5765 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005766 if (lex.get()->getType()->hasIntegerRepresentation() &&
5767 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005768 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005769 return InvalidOperands(Loc, lex, rex);
5770 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005771
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005772 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005773 if (lex.isInvalid() || rex.isInvalid())
5774 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005775
Richard Trieucfc491d2011-08-02 04:35:43 +00005776 if (!lex.get()->getType()->isIntegerType() ||
5777 !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005778 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005779
Chris Lattnerfaa54172010-01-12 21:23:57 +00005780 // Check for remainder by zero.
Richard Trieucfc491d2011-08-02 04:35:43 +00005781 if (rex.get()->isNullPointerConstant(Context,
5782 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005783 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5784 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005785
Chris Lattnerfaa54172010-01-12 21:23:57 +00005786 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005787}
5788
Chandler Carruthc9332212011-06-27 08:02:19 +00005789/// \brief Diagnose invalid arithmetic on two void pointers.
5790static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5791 Expr *LHS, Expr *RHS) {
5792 S.Diag(Loc, S.getLangOptions().CPlusPlus
5793 ? diag::err_typecheck_pointer_arith_void_type
5794 : diag::ext_gnu_void_ptr)
5795 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5796}
5797
5798/// \brief Diagnose invalid arithmetic on a void pointer.
5799static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5800 Expr *Pointer) {
5801 S.Diag(Loc, S.getLangOptions().CPlusPlus
5802 ? diag::err_typecheck_pointer_arith_void_type
5803 : diag::ext_gnu_void_ptr)
5804 << 0 /* one pointer */ << Pointer->getSourceRange();
5805}
5806
5807/// \brief Diagnose invalid arithmetic on two function pointers.
5808static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5809 Expr *LHS, Expr *RHS) {
5810 assert(LHS->getType()->isAnyPointerType());
5811 assert(RHS->getType()->isAnyPointerType());
5812 S.Diag(Loc, S.getLangOptions().CPlusPlus
5813 ? diag::err_typecheck_pointer_arith_function_type
5814 : diag::ext_gnu_ptr_func_arith)
5815 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5816 // We only show the second type if it differs from the first.
5817 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5818 RHS->getType())
5819 << RHS->getType()->getPointeeType()
5820 << LHS->getSourceRange() << RHS->getSourceRange();
5821}
5822
5823/// \brief Diagnose invalid arithmetic on a function pointer.
5824static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5825 Expr *Pointer) {
5826 assert(Pointer->getType()->isAnyPointerType());
5827 S.Diag(Loc, S.getLangOptions().CPlusPlus
5828 ? diag::err_typecheck_pointer_arith_function_type
5829 : diag::ext_gnu_ptr_func_arith)
5830 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5831 << 0 /* one pointer, so only one type */
5832 << Pointer->getSourceRange();
5833}
5834
Richard Trieuaba22802011-09-02 02:15:37 +00005835/// \brief Warn if Operand is incomplete pointer type
5836///
5837/// \returns True if pointer has incomplete type
5838static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5839 Expr *Operand) {
5840 if ((Operand->getType()->isPointerType() &&
5841 !Operand->getType()->isDependentType()) ||
5842 Operand->getType()->isObjCObjectPointerType()) {
5843 QualType PointeeTy = Operand->getType()->getPointeeType();
5844 if (S.RequireCompleteType(
5845 Loc, PointeeTy,
5846 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5847 << PointeeTy << Operand->getSourceRange()))
5848 return true;
5849 }
5850 return false;
5851}
5852
Chandler Carruthc9332212011-06-27 08:02:19 +00005853/// \brief Check the validity of an arithmetic pointer operand.
5854///
5855/// If the operand has pointer type, this code will check for pointer types
5856/// which are invalid in arithmetic operations. These will be diagnosed
5857/// appropriately, including whether or not the use is supported as an
5858/// extension.
5859///
5860/// \returns True when the operand is valid to use (even if as an extension).
5861static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5862 Expr *Operand) {
5863 if (!Operand->getType()->isAnyPointerType()) return true;
5864
5865 QualType PointeeTy = Operand->getType()->getPointeeType();
5866 if (PointeeTy->isVoidType()) {
5867 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5868 return !S.getLangOptions().CPlusPlus;
5869 }
5870 if (PointeeTy->isFunctionType()) {
5871 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5872 return !S.getLangOptions().CPlusPlus;
5873 }
5874
Richard Trieuaba22802011-09-02 02:15:37 +00005875 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005876
5877 return true;
5878}
5879
5880/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5881/// operands.
5882///
5883/// This routine will diagnose any invalid arithmetic on pointer operands much
5884/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5885/// for emitting a single diagnostic even for operations where both LHS and RHS
5886/// are (potentially problematic) pointers.
5887///
5888/// \returns True when the operand is valid to use (even if as an extension).
5889static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5890 Expr *LHS, Expr *RHS) {
5891 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5892 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5893 if (!isLHSPointer && !isRHSPointer) return true;
5894
5895 QualType LHSPointeeTy, RHSPointeeTy;
5896 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5897 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5898
5899 // Check for arithmetic on pointers to incomplete types.
5900 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5901 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5902 if (isLHSVoidPtr || isRHSVoidPtr) {
5903 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5904 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5905 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5906
5907 return !S.getLangOptions().CPlusPlus;
5908 }
5909
5910 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5911 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5912 if (isLHSFuncPtr || isRHSFuncPtr) {
5913 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5914 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5915 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5916
5917 return !S.getLangOptions().CPlusPlus;
5918 }
5919
Richard Trieuaba22802011-09-02 02:15:37 +00005920 if (checkArithmeticIncompletePointerType(S, Loc, LHS)) return false;
5921 if (checkArithmeticIncompletePointerType(S, Loc, RHS)) return false;
5922
Chandler Carruthc9332212011-06-27 08:02:19 +00005923 return true;
5924}
5925
Richard Trieub10c6312011-09-01 22:53:23 +00005926/// \brief Check bad cases where we step over interface counts.
5927static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5928 SourceLocation OpLoc,
5929 Expr *Op) {
5930 assert(Op->getType()->isAnyPointerType());
5931 QualType PointeeTy = Op->getType()->getPointeeType();
5932 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5933 return true;
5934
5935 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5936 << PointeeTy << Op->getSourceRange();
5937 return false;
5938}
5939
5940/// \brief Warn when two pointers are incompatible.
5941static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
5942 Expr *LHS, Expr *RHS) {
5943 assert(LHS->getType()->isAnyPointerType());
5944 assert(RHS->getType()->isAnyPointerType());
5945 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5946 << LHS->getType() << RHS->getType() << LHS->getSourceRange()
5947 << RHS->getSourceRange();
5948}
5949
Chris Lattnerfaa54172010-01-12 21:23:57 +00005950QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005951 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005952 if (lex.get()->getType()->isVectorType() ||
5953 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005954 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005955 if (CompLHSTy) *CompLHSTy = compType;
5956 return compType;
5957 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005958
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005959 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005960 if (lex.isInvalid() || rex.isInvalid())
5961 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005962
Steve Naroffe4718892007-04-27 18:30:00 +00005963 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005964 if (lex.get()->getType()->isArithmeticType() &&
5965 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005966 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005967 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005968 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005969
Eli Friedman8e122982008-05-18 18:08:51 +00005970 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005971 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005972 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005973 std::swap(PExp, IExp);
5974
Steve Naroff6b712a72009-07-14 18:25:06 +00005975 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005976 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005977 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5978 return QualType();
5979
Chris Lattner12bdebb2009-04-24 23:50:08 +00005980 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00005981 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
Chris Lattner12bdebb2009-04-24 23:50:08 +00005982 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005983
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005984 // Check array bounds for pointer arithemtic
5985 CheckArrayAccess(PExp, IExp);
5986
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005987 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005988 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005989 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005990 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005991 if (LHSTy->isPromotableIntegerType())
5992 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005993 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005994 *CompLHSTy = LHSTy;
5995 }
Eli Friedman8e122982008-05-18 18:08:51 +00005996 return PExp->getType();
5997 }
5998 }
5999
Chris Lattner326f7572008-11-18 01:30:42 +00006000 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006001}
6002
Chris Lattner2a3569b2008-04-07 05:30:13 +00006003// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006004QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieucfc491d2011-08-02 04:35:43 +00006005 SourceLocation Loc,
6006 QualType* CompLHSTy) {
6007 if (lex.get()->getType()->isVectorType() ||
6008 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006009 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006010 if (CompLHSTy) *CompLHSTy = compType;
6011 return compType;
6012 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006013
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006014 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006015 if (lex.isInvalid() || rex.isInvalid())
6016 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006017
Chris Lattner4d62f422007-12-09 21:53:25 +00006018 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006019
Chris Lattner4d62f422007-12-09 21:53:25 +00006020 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006021 if (lex.get()->getType()->isArithmeticType() &&
6022 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006023 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006024 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006025 }
Mike Stump11289f42009-09-09 15:08:12 +00006026
Chris Lattner4d62f422007-12-09 21:53:25 +00006027 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006028 if (lex.get()->getType()->isAnyPointerType()) {
6029 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006030
Chris Lattner12bdebb2009-04-24 23:50:08 +00006031 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00006032 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, lex.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006033 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006034
Chris Lattner4d62f422007-12-09 21:53:25 +00006035 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006036 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00006037 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6038 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006039
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006040 Expr *IExpr = rex.get()->IgnoreParenCasts();
6041 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6042 OK_Ordinary, IExpr->getExprLoc());
6043 // Check array bounds for pointer arithemtic
6044 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6045
John Wiegley01296292011-04-08 18:41:53 +00006046 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6047 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006048 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006049
Chris Lattner4d62f422007-12-09 21:53:25 +00006050 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006051 if (const PointerType *RHSPTy
6052 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006053 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006054
Eli Friedman168fe152009-05-16 13:54:38 +00006055 if (getLangOptions().CPlusPlus) {
6056 // Pointee types must be the same: C++ [expr.add]
6057 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieub10c6312011-09-01 22:53:23 +00006058 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006059 }
6060 } else {
6061 // Pointee types must be compatible C99 6.5.6p3
6062 if (!Context.typesAreCompatible(
6063 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6064 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieub10c6312011-09-01 22:53:23 +00006065 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006066 return QualType();
6067 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006068 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006069
Chandler Carruthc9332212011-06-27 08:02:19 +00006070 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6071 lex.get(), rex.get()))
6072 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006073
John Wiegley01296292011-04-08 18:41:53 +00006074 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006075 return Context.getPointerDiffType();
6076 }
6077 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006078
Chris Lattner326f7572008-11-18 01:30:42 +00006079 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006080}
6081
Douglas Gregor0bf31402010-10-08 23:50:27 +00006082static bool isScopedEnumerationType(QualType T) {
6083 if (const EnumType *ET = dyn_cast<EnumType>(T))
6084 return ET->getDecl()->isScoped();
6085 return false;
6086}
6087
John Wiegley01296292011-04-08 18:41:53 +00006088static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006089 SourceLocation Loc, unsigned Opc,
6090 QualType LHSTy) {
6091 llvm::APSInt Right;
6092 // Check right/shifter operand
Richard Trieucfc491d2011-08-02 04:35:43 +00006093 if (rex.get()->isValueDependent() ||
6094 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006095 return;
6096
6097 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006098 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006099 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006100 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006101 return;
6102 }
6103 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006104 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006105 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006106 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006107 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006108 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006109 return;
6110 }
6111 if (Opc != BO_Shl)
6112 return;
6113
6114 // When left shifting an ICE which is signed, we can check for overflow which
6115 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6116 // integers have defined behavior modulo one more than the maximum value
6117 // representable in the result type, so never warn for those.
6118 llvm::APSInt Left;
Richard Trieucfc491d2011-08-02 04:35:43 +00006119 if (lex.get()->isValueDependent() ||
6120 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006121 LHSTy->hasUnsignedIntegerRepresentation())
6122 return;
6123 llvm::APInt ResultBits =
6124 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6125 if (LeftBits.uge(ResultBits))
6126 return;
6127 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6128 Result = Result.shl(Right);
6129
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006130 // Print the bit representation of the signed integer as an unsigned
6131 // hexadecimal number.
6132 llvm::SmallString<40> HexResult;
6133 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6134
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006135 // If we are only missing a sign bit, this is less likely to result in actual
6136 // bugs -- if the result is cast back to an unsigned type, it will have the
6137 // expected value. Thus we place this behind a different warning that can be
6138 // turned off separately if needed.
6139 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006140 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6141 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006142 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006143 return;
6144 }
6145
6146 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006147 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieucfc491d2011-08-02 04:35:43 +00006148 << Left.getBitWidth() << lex.get()->getSourceRange()
6149 << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006150}
6151
Chris Lattner2a3569b2008-04-07 05:30:13 +00006152// C99 6.5.7
Richard Trieucfc491d2011-08-02 04:35:43 +00006153QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6154 SourceLocation Loc, unsigned Opc,
6155 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006156 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006157 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6158 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006159 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006160
Douglas Gregor0bf31402010-10-08 23:50:27 +00006161 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6162 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006163 if (isScopedEnumerationType(lex.get()->getType()) ||
6164 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006165 return InvalidOperands(Loc, lex, rex);
6166 }
6167
Nate Begemane46ee9a2009-10-25 02:26:48 +00006168 // Vector shifts promote their scalar inputs to vector type.
Richard Trieucfc491d2011-08-02 04:35:43 +00006169 if (lex.get()->getType()->isVectorType() ||
6170 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006171 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006172
Chris Lattner5c11c412007-12-12 05:47:28 +00006173 // Shifts don't perform usual arithmetic conversions, they just do integer
6174 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006175
John McCall57cdd882010-12-16 19:28:59 +00006176 // For the LHS, do usual unary conversions, but then reset them away
6177 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006178 ExprResult old_lex = lex;
6179 lex = UsualUnaryConversions(lex.take());
6180 if (lex.isInvalid())
6181 return QualType();
6182 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006183 if (isCompAssign) lex = old_lex;
6184
6185 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006186 rex = UsualUnaryConversions(rex.take());
6187 if (rex.isInvalid())
6188 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006189
Ryan Flynnf53fab82009-08-07 16:20:20 +00006190 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006191 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006192
Chris Lattner5c11c412007-12-12 05:47:28 +00006193 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006194 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006195}
6196
Chandler Carruth17773fc2010-07-10 12:30:03 +00006197static bool IsWithinTemplateSpecialization(Decl *D) {
6198 if (DeclContext *DC = D->getDeclContext()) {
6199 if (isa<ClassTemplateSpecializationDecl>(DC))
6200 return true;
6201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6202 return FD->isFunctionTemplateSpecialization();
6203 }
6204 return false;
6205}
6206
Richard Trieueea56f72011-09-02 03:48:46 +00006207/// If two different enums are compared, raise a warning.
6208static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &lex,
6209 ExprResult &rex) {
Richard Trieueea56f72011-09-02 03:48:46 +00006210 QualType LHSStrippedType = lex.get()->IgnoreParenImpCasts()->getType();
6211 QualType RHSStrippedType = rex.get()->IgnoreParenImpCasts()->getType();
6212
6213 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6214 if (!LHSEnumType)
6215 return;
6216 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6217 if (!RHSEnumType)
6218 return;
6219
6220 // Ignore anonymous enums.
6221 if (!LHSEnumType->getDecl()->getIdentifier())
6222 return;
6223 if (!RHSEnumType->getDecl()->getIdentifier())
6224 return;
6225
6226 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6227 return;
6228
6229 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6230 << LHSStrippedType << RHSStrippedType
6231 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6232}
6233
Richard Trieudd82a5c2011-09-02 02:55:45 +00006234/// \brief Diagnose bad pointer comparisons.
6235static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6236 ExprResult &lex, ExprResult &rex,
6237 bool isError) {
6238 S.Diag(Loc, isError ? diag::err_typecheck_comparison_of_distinct_pointers
6239 : diag::ext_typecheck_comparison_of_distinct_pointers)
6240 << lex.get()->getType() << rex.get()->getType()
6241 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6242}
6243
6244/// \brief Returns false if the pointers are converted to a composite type,
6245/// true otherwise.
6246static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu48277e52011-09-02 21:44:27 +00006247 ExprResult &lex, ExprResult &rex) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006248 // C++ [expr.rel]p2:
6249 // [...] Pointer conversions (4.10) and qualification
6250 // conversions (4.4) are performed on pointer operands (or on
6251 // a pointer operand and a null pointer constant) to bring
6252 // them to their composite pointer type. [...]
6253 //
6254 // C++ [expr.eq]p1 uses the same notion for (in)equality
6255 // comparisons of pointers.
6256
6257 // C++ [expr.eq]p2:
6258 // In addition, pointers to members can be compared, or a pointer to
6259 // member and a null pointer constant. Pointer to member conversions
6260 // (4.11) and qualification conversions (4.4) are performed to bring
6261 // them to a common type. If one operand is a null pointer constant,
6262 // the common type is the type of the other operand. Otherwise, the
6263 // common type is a pointer to member type similar (4.4) to the type
6264 // of one of the operands, with a cv-qualification signature (4.4)
6265 // that is the union of the cv-qualification signatures of the operand
6266 // types.
6267
6268 QualType lType = lex.get()->getType();
6269 QualType rType = rex.get()->getType();
6270 assert((lType->isPointerType() && rType->isPointerType()) ||
6271 (lType->isMemberPointerType() && rType->isMemberPointerType()));
6272
6273 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006274 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6275 QualType T = S.FindCompositePointerType(Loc, lex, rex, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006276 if (T.isNull()) {
6277 diagnoseDistinctPointerComparison(S, Loc, lex, rex, /*isError*/true);
6278 return true;
6279 }
6280
6281 if (NonStandardCompositeType)
6282 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6283 << lType << rType << T << lex.get()->getSourceRange()
6284 << rex.get()->getSourceRange();
6285
6286 lex = S.ImpCastExprToType(lex.take(), T, CK_BitCast);
6287 rex = S.ImpCastExprToType(rex.take(), T, CK_BitCast);
6288 return false;
6289}
6290
6291static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6292 ExprResult &lex,
6293 ExprResult &rex,
6294 bool isError) {
6295 S.Diag(Loc,isError ? diag::err_typecheck_comparison_of_fptr_to_void
6296 : diag::ext_typecheck_comparison_of_fptr_to_void)
6297 << lex.get()->getType() << rex.get()->getType()
6298 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6299}
6300
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006301// C99 6.5.8, C++ [expr.rel]
Richard Trieucfc491d2011-08-02 04:35:43 +00006302QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6303 SourceLocation Loc, unsigned OpaqueOpc,
6304 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006305 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006306
Chris Lattner9a152e22009-12-05 05:40:13 +00006307 // Handle vector comparisons separately.
Richard Trieucfc491d2011-08-02 04:35:43 +00006308 if (lex.get()->getType()->isVectorType() ||
6309 rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006310 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006311
John Wiegley01296292011-04-08 18:41:53 +00006312 QualType lType = lex.get()->getType();
6313 QualType rType = rex.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006314
John Wiegley01296292011-04-08 18:41:53 +00006315 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6316 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006317
Richard Trieueea56f72011-09-02 03:48:46 +00006318 checkEnumComparison(*this, Loc, lex, rex);
Chandler Carruth712563b2011-02-17 08:37:06 +00006319
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006320 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006321 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006322 !lex.get()->getLocStart().isMacroID() &&
6323 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006324 // For non-floating point types, check for self-comparisons of the form
6325 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6326 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006327 //
6328 // NOTE: Don't warn about comparison expressions resulting from macro
6329 // expansion. Also don't warn about comparisons which are only self
6330 // comparisons within a template specialization. The warnings should catch
6331 // obvious cases in the definition of the template anyways. The idea is to
6332 // warn when the typed comparison operator will always evaluate to the same
6333 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006334 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006335 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006336 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006337 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006338 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006339 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006340 << (Opc == BO_EQ
6341 || Opc == BO_LE
6342 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006343 } else if (lType->isArrayType() && rType->isArrayType() &&
6344 !DRL->getDecl()->getType()->isReferenceType() &&
6345 !DRR->getDecl()->getType()->isReferenceType()) {
6346 // what is it always going to eval to?
6347 char always_evals_to;
6348 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006349 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006350 always_evals_to = 0; // false
6351 break;
John McCalle3027922010-08-25 11:45:40 +00006352 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006353 always_evals_to = 1; // true
6354 break;
6355 default:
6356 // best we can say is 'a constant'
6357 always_evals_to = 2; // e.g. array1 <= array2
6358 break;
6359 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006360 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006361 << 1 // array
6362 << always_evals_to);
6363 }
6364 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366
Chris Lattner222b8bd2009-03-08 19:39:53 +00006367 if (isa<CastExpr>(LHSStripped))
6368 LHSStripped = LHSStripped->IgnoreParenCasts();
6369 if (isa<CastExpr>(RHSStripped))
6370 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006371
Chris Lattner222b8bd2009-03-08 19:39:53 +00006372 // Warn about comparisons against a string constant (unless the other
6373 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006374 Expr *literalString = 0;
6375 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006376 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006377 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006378 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006379 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006380 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006381 } else if ((isa<StringLiteral>(RHSStripped) ||
6382 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006383 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006384 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006385 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006386 literalStringStripped = RHSStripped;
6387 }
6388
6389 if (literalString) {
6390 std::string resultComparison;
6391 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006392 case BO_LT: resultComparison = ") < 0"; break;
6393 case BO_GT: resultComparison = ") > 0"; break;
6394 case BO_LE: resultComparison = ") <= 0"; break;
6395 case BO_GE: resultComparison = ") >= 0"; break;
6396 case BO_EQ: resultComparison = ") == 0"; break;
6397 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006398 default: assert(false && "Invalid comparison operator");
6399 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006400
Ted Kremenek3427fac2011-02-23 01:52:04 +00006401 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006402 PDiag(diag::warn_stringcompare)
6403 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006404 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006405 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006406 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006407
Douglas Gregorec170db2010-06-08 19:50:34 +00006408 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieucfc491d2011-08-02 04:35:43 +00006409 if (lex.get()->getType()->isArithmeticType() &&
6410 rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006411 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006412 if (lex.isInvalid() || rex.isInvalid())
6413 return QualType();
6414 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006415 else {
John Wiegley01296292011-04-08 18:41:53 +00006416 lex = UsualUnaryConversions(lex.take());
6417 if (lex.isInvalid())
6418 return QualType();
6419
6420 rex = UsualUnaryConversions(rex.take());
6421 if (rex.isInvalid())
6422 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006423 }
6424
John Wiegley01296292011-04-08 18:41:53 +00006425 lType = lex.get()->getType();
6426 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006427
Douglas Gregorca63811b2008-11-19 03:25:36 +00006428 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006429 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006430
Chris Lattnerb620c342007-08-26 01:18:55 +00006431 if (isRelational) {
6432 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006433 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006434 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006435 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006436 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006437 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006438
Chris Lattnerb620c342007-08-26 01:18:55 +00006439 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006440 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006441 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006442
John Wiegley01296292011-04-08 18:41:53 +00006443 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006444 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006445 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006446 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006447
Douglas Gregorf267edd2010-06-15 21:38:40 +00006448 // All of the following pointer-related warnings are GCC extensions, except
6449 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006450 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006451 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006452 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006453 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006454 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006455
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006456 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006457 if (LCanPointeeTy == RCanPointeeTy)
6458 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006459 if (!isRelational &&
6460 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6461 // Valid unless comparison between non-null pointer and function pointer
6462 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006463 // In a SFINAE context, we treat this as a hard error to maintain
6464 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006465 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6466 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006467 diagnoseFunctionPointerToVoidComparison(
6468 *this, Loc, lex, rex, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006469
6470 if (isSFINAEContext())
6471 return QualType();
6472
John Wiegley01296292011-04-08 18:41:53 +00006473 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006474 return ResultTy;
6475 }
6476 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006477
Richard Trieudd82a5c2011-09-02 02:55:45 +00006478 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006479 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006480 else
6481 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006482 }
Eli Friedman16c209612009-08-23 00:27:47 +00006483 // C99 6.5.9p2 and C99 6.5.8p2
6484 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6485 RCanPointeeTy.getUnqualifiedType())) {
6486 // Valid unless a relational comparison of function pointers
6487 if (isRelational && LCanPointeeTy->isFunctionType()) {
6488 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006489 << lType << rType << lex.get()->getSourceRange()
6490 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006491 }
6492 } else if (!isRelational &&
6493 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6494 // Valid unless comparison between non-null pointer and function pointer
6495 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006496 && !LHSIsNull && !RHSIsNull)
6497 diagnoseFunctionPointerToVoidComparison(*this, Loc, lex, rex,
6498 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006499 } else {
6500 // Invalid
Richard Trieudd82a5c2011-09-02 02:55:45 +00006501 diagnoseDistinctPointerComparison(*this, Loc, lex, rex, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006502 }
John McCall7684dde2011-03-11 04:25:25 +00006503 if (LCanPointeeTy != RCanPointeeTy) {
6504 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006505 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006506 else
John Wiegley01296292011-04-08 18:41:53 +00006507 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006508 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006509 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006510 }
Mike Stump11289f42009-09-09 15:08:12 +00006511
Sebastian Redl576fd422009-05-10 18:38:11 +00006512 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006513 // Comparison of nullptr_t with itself.
6514 if (lType->isNullPtrType() && rType->isNullPtrType())
6515 return ResultTy;
6516
Mike Stump11289f42009-09-09 15:08:12 +00006517 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006518 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006519 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006520 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006521 (!isRelational &&
6522 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006523 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006524 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006525 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006526 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006527 return ResultTy;
6528 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006529 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006530 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006531 (!isRelational &&
6532 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006533 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006534 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006535 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006536 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006537 return ResultTy;
6538 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006539
6540 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006541 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006542 lType->isMemberPointerType() && rType->isMemberPointerType()) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006543 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006544 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006545 else
6546 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006547 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006548
6549 // Handle scoped enumeration types specifically, since they don't promote
6550 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006551 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieucfc491d2011-08-02 04:35:43 +00006552 Context.hasSameUnqualifiedType(lex.get()->getType(),
6553 rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006554 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006555 }
Mike Stump11289f42009-09-09 15:08:12 +00006556
Steve Naroff081c7422008-09-04 15:10:53 +00006557 // Handle block pointer types.
Richard Trieucfc491d2011-08-02 04:35:43 +00006558 if (!isRelational && lType->isBlockPointerType() &&
6559 rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006560 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6561 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006562
Steve Naroff081c7422008-09-04 15:10:53 +00006563 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006564 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006565 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006566 << lType << rType << lex.get()->getSourceRange()
6567 << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006568 }
John Wiegley01296292011-04-08 18:41:53 +00006569 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006570 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006571 }
John Wiegley01296292011-04-08 18:41:53 +00006572
Steve Naroffe18f94c2008-09-28 01:11:11 +00006573 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006574 if (!isRelational
6575 && ((lType->isBlockPointerType() && rType->isPointerType())
6576 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006577 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006578 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006579 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006580 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006581 ->getPointeeType()->isVoidType())))
6582 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006583 << lType << rType << lex.get()->getSourceRange()
6584 << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006585 }
John McCall7684dde2011-03-11 04:25:25 +00006586 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006587 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006588 else
John Wiegley01296292011-04-08 18:41:53 +00006589 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006590 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006591 }
Steve Naroff081c7422008-09-04 15:10:53 +00006592
John McCall7684dde2011-03-11 04:25:25 +00006593 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6594 const PointerType *LPT = lType->getAs<PointerType>();
6595 const PointerType *RPT = rType->getAs<PointerType>();
6596 if (LPT || RPT) {
6597 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6598 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006599
Steve Naroff753567f2008-11-17 19:49:16 +00006600 if (!LPtrToVoid && !RPtrToVoid &&
6601 !Context.typesAreCompatible(lType, rType)) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006602 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6603 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006604 }
John McCall7684dde2011-03-11 04:25:25 +00006605 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006606 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006607 else
John Wiegley01296292011-04-08 18:41:53 +00006608 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006609 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006610 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006611 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006612 if (!Context.areComparableObjCPointerTypes(lType, rType))
Richard Trieudd82a5c2011-09-02 02:55:45 +00006613 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6614 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006615 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006616 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006617 else
John Wiegley01296292011-04-08 18:41:53 +00006618 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006619 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006620 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006621 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006622 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6623 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006624 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006625 bool isError = false;
6626 if ((LHSIsNull && lType->isIntegerType()) ||
6627 (RHSIsNull && rType->isIntegerType())) {
6628 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006629 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006630 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006631 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006632 else if (getLangOptions().CPlusPlus) {
6633 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6634 isError = true;
6635 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006636 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006637
Chris Lattnerd99bd522009-08-23 00:03:44 +00006638 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006639 Diag(Loc, DiagID)
Richard Trieucfc491d2011-08-02 04:35:43 +00006640 << lType << rType << lex.get()->getSourceRange()
6641 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006642 if (isError)
6643 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006644 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006645
6646 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006647 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006648 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006649 else
John Wiegley01296292011-04-08 18:41:53 +00006650 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006651 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006652 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006653 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006654
Steve Naroff4b191572008-09-04 16:56:14 +00006655 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006656 if (!isRelational && RHSIsNull
6657 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006658 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006659 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006660 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006661 if (!isRelational && LHSIsNull
6662 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006663 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006664 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006665 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006666
Chris Lattner326f7572008-11-18 01:30:42 +00006667 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006668}
6669
Nate Begeman191a6b12008-07-14 18:02:46 +00006670/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006671/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006672/// like a scalar comparison, a vector comparison produces a vector of integer
6673/// types.
John Wiegley01296292011-04-08 18:41:53 +00006674QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006675 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006676 bool isRelational) {
6677 // Check to make sure we're operating on vectors of the same type and width,
6678 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006679 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006680 if (vType.isNull())
6681 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682
John Wiegley01296292011-04-08 18:41:53 +00006683 QualType lType = lex.get()->getType();
6684 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006685
Anton Yartsev530deb92011-03-27 15:36:07 +00006686 // If AltiVec, the comparison results in a numeric type, i.e.
6687 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006688 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006689 return Context.getLogicalOperationType();
6690
Nate Begeman191a6b12008-07-14 18:02:46 +00006691 // For non-floating point types, check for self-comparisons of the form
6692 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6693 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006694 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006695 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6696 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006697 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006698 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006699 PDiag(diag::warn_comparison_always)
6700 << 0 // self-
6701 << 2 // "a constant"
6702 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006703 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006704
Nate Begeman191a6b12008-07-14 18:02:46 +00006705 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006706 if (!isRelational && lType->hasFloatingRepresentation()) {
6707 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006708 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006709 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006710
Nate Begeman191a6b12008-07-14 18:02:46 +00006711 // Return the type for the comparison, which is the same as vector type for
6712 // integer vectors, or an integer type of identical size and number of
6713 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006714 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006715 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006716
John McCall9dd450b2009-09-21 23:43:11 +00006717 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006718 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006719 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006720 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006721 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006722 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6723
Mike Stump4e1f26a2009-02-19 03:04:26 +00006724 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006725 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006726 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6727}
6728
Steve Naroff218bc2b2007-05-04 21:54:46 +00006729inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006730 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00006731 if (lex.get()->getType()->isVectorType() ||
6732 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006733 if (lex.get()->getType()->hasIntegerRepresentation() &&
6734 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006735 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006736
6737 return InvalidOperands(Loc, lex, rex);
6738 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006739
John Wiegley01296292011-04-08 18:41:53 +00006740 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieucfc491d2011-08-02 04:35:43 +00006741 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6742 isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006743 if (lexResult.isInvalid() || rexResult.isInvalid())
6744 return QualType();
6745 lex = lexResult.take();
6746 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006747
John Wiegley01296292011-04-08 18:41:53 +00006748 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6749 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006750 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006751 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006752}
6753
Steve Naroff218bc2b2007-05-04 21:54:46 +00006754inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006755 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006756
6757 // Diagnose cases where the user write a logical and/or but probably meant a
6758 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6759 // is a constant.
Richard Trieucfc491d2011-08-02 04:35:43 +00006760 if (lex.get()->getType()->isIntegerType() &&
6761 !lex.get()->getType()->isBooleanType() &&
John Wiegley01296292011-04-08 18:41:53 +00006762 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006763 // Don't warn in macros or template instantiations.
6764 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006765 // If the RHS can be constant folded, and if it constant folds to something
6766 // that isn't 0 or 1 (which indicate a potential logical operation that
6767 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006768 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006769 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006770 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6771 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6772 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6773 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6774 << rex.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006775 << (Opc == BO_LAnd ? "&&" : "||");
6776 // Suggest replacing the logical operator with the bitwise version
6777 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6778 << (Opc == BO_LAnd ? "&" : "|")
6779 << FixItHint::CreateReplacement(SourceRange(
6780 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6781 getLangOptions())),
6782 Opc == BO_LAnd ? "&" : "|");
6783 if (Opc == BO_LAnd)
6784 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6785 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6786 << FixItHint::CreateRemoval(
6787 SourceRange(
6788 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6789 0, getSourceManager(),
6790 getLangOptions()),
6791 rex.get()->getLocEnd()));
6792 }
Chris Lattner938533d2010-07-24 01:10:11 +00006793 }
Chris Lattner8406c512010-07-13 19:41:32 +00006794
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006795 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006796 lex = UsualUnaryConversions(lex.take());
6797 if (lex.isInvalid())
6798 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006799
John Wiegley01296292011-04-08 18:41:53 +00006800 rex = UsualUnaryConversions(rex.take());
6801 if (rex.isInvalid())
6802 return QualType();
6803
Richard Trieucfc491d2011-08-02 04:35:43 +00006804 if (!lex.get()->getType()->isScalarType() ||
6805 !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006806 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006807
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006808 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006809 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006810
John McCall4a2429a2010-06-04 00:29:51 +00006811 // The following is safe because we only use this method for
6812 // non-overloadable operands.
6813
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006814 // C++ [expr.log.and]p1
6815 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006816 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006817 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6818 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006819 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006820 lex = move(lexRes);
6821
6822 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6823 if (rexRes.isInvalid())
6824 return InvalidOperands(Loc, lex, rex);
6825 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006826
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006827 // C++ [expr.log.and]p2
6828 // C++ [expr.log.or]p2
6829 // The result is a bool.
6830 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006831}
6832
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006833/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6834/// is a read-only property; return true if so. A readonly property expression
6835/// depends on various declarations and thus must be treated specially.
6836///
Mike Stump11289f42009-09-09 15:08:12 +00006837static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006838 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6839 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006840 if (PropExpr->isImplicitProperty()) return false;
6841
6842 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6843 QualType BaseType = PropExpr->isSuperReceiver() ?
6844 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006845 PropExpr->getBase()->getType();
6846
John McCallb7bd14f2010-12-02 01:19:52 +00006847 if (const ObjCObjectPointerType *OPT =
6848 BaseType->getAsObjCInterfacePointerType())
6849 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6850 if (S.isPropertyReadonly(PDecl, IFace))
6851 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006852 }
6853 return false;
6854}
6855
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006856static bool IsConstProperty(Expr *E, Sema &S) {
6857 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6858 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6859 if (PropExpr->isImplicitProperty()) return false;
6860
6861 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6862 QualType T = PDecl->getType();
6863 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006864 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006865 CanQualType CT = S.Context.getCanonicalType(T);
6866 return CT.isConstQualified();
6867 }
6868 return false;
6869}
6870
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006871static bool IsReadonlyMessage(Expr *E, Sema &S) {
6872 if (E->getStmtClass() != Expr::MemberExprClass)
6873 return false;
6874 const MemberExpr *ME = cast<MemberExpr>(E);
6875 NamedDecl *Member = ME->getMemberDecl();
6876 if (isa<FieldDecl>(Member)) {
6877 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6878 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6879 return false;
6880 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6881 }
6882 return false;
6883}
6884
Chris Lattner30bd3272008-11-18 01:22:49 +00006885/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6886/// emit an error and return true. If so, return false.
6887static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006888 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006889 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006890 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006891 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6892 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006893 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6894 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006895 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6896 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006897 if (IsLV == Expr::MLV_Valid)
6898 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006899
Chris Lattner30bd3272008-11-18 01:22:49 +00006900 unsigned Diag = 0;
6901 bool NeedType = false;
6902 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006903 case Expr::MLV_ConstQualified:
6904 Diag = diag::err_typecheck_assign_const;
6905
John McCalld4631322011-06-17 06:42:21 +00006906 // In ARC, use some specialized diagnostics for occasions where we
6907 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006908 if (S.getLangOptions().ObjCAutoRefCount) {
6909 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6910 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6911 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6912
John McCalld4631322011-06-17 06:42:21 +00006913 // Use the normal diagnostic if it's pseudo-__strong but the
6914 // user actually wrote 'const'.
6915 if (var->isARCPseudoStrong() &&
6916 (!var->getTypeSourceInfo() ||
6917 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6918 // There are two pseudo-strong cases:
6919 // - self
John McCall31168b02011-06-15 23:02:42 +00006920 ObjCMethodDecl *method = S.getCurMethodDecl();
6921 if (method && var == method->getSelfDecl())
6922 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006923
6924 // - fast enumeration variables
6925 else
John McCall31168b02011-06-15 23:02:42 +00006926 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006927
John McCall31168b02011-06-15 23:02:42 +00006928 SourceRange Assign;
6929 if (Loc != OrigLoc)
6930 Assign = SourceRange(OrigLoc, OrigLoc);
6931 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6932 // We need to preserve the AST regardless, so migration tool
6933 // can do its job.
6934 return false;
6935 }
6936 }
6937 }
6938
6939 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006940 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006941 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6942 NeedType = true;
6943 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006944 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006945 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6946 NeedType = true;
6947 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006948 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006949 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6950 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006951 case Expr::MLV_Valid:
6952 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006953 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006954 case Expr::MLV_MemberFunction:
6955 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006956 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6957 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006958 case Expr::MLV_IncompleteType:
6959 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006960 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006961 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006962 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006963 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006964 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6965 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006966 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006967 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6968 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006969 case Expr::MLV_ReadonlyProperty:
6970 Diag = diag::error_readonly_property_assignment;
6971 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006972 case Expr::MLV_NoSetterProperty:
6973 Diag = diag::error_nosetter_property_assignment;
6974 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006975 case Expr::MLV_InvalidMessageExpression:
6976 Diag = diag::error_readonly_message_assignment;
6977 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006978 case Expr::MLV_SubObjCPropertySetting:
6979 Diag = diag::error_no_subobject_property_setting;
6980 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006981 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006982
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006983 SourceRange Assign;
6984 if (Loc != OrigLoc)
6985 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006986 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006987 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006988 else
Mike Stump11289f42009-09-09 15:08:12 +00006989 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006990 return true;
6991}
6992
6993
6994
6995// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006996QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006997 SourceLocation Loc,
6998 QualType CompoundType) {
6999 // Verify that LHS is a modifiable lvalue, and emit error if not.
7000 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007001 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007002
7003 QualType LHSType = LHS->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007004 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7005 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007006 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007007 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007008 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007009 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007010 if (LHS->getObjectKind() == OK_ObjCProperty) {
7011 ExprResult LHSResult = Owned(LHS);
7012 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7013 if (LHSResult.isInvalid())
7014 return QualType();
7015 LHS = LHSResult.take();
7016 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007017 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007018 if (RHS.isInvalid())
7019 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007020 // Special case of NSObject attributes on c-style pointer types.
7021 if (ConvTy == IncompatiblePointer &&
7022 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007023 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007024 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007025 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007026 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007027
John McCall7decc9e2010-11-18 06:31:45 +00007028 if (ConvTy == Compatible &&
7029 getLangOptions().ObjCNonFragileABI &&
7030 LHSType->isObjCObjectType())
7031 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7032 << LHSType;
7033
Chris Lattnerea714382008-08-21 18:04:13 +00007034 // If the RHS is a unary plus or minus, check to see if they = and + are
7035 // right next to each other. If so, the user may have typo'd "x =+ 4"
7036 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007037 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007038 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7039 RHSCheck = ICE->getSubExpr();
7040 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007041 if ((UO->getOpcode() == UO_Plus ||
7042 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007043 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007044 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007045 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7046 // And there is a space or other character before the subexpr of the
7047 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007048 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7049 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007050 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007051 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007052 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007053 }
Chris Lattnerea714382008-08-21 18:04:13 +00007054 }
John McCall31168b02011-06-15 23:02:42 +00007055
7056 if (ConvTy == Compatible) {
7057 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7058 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007059 else if (getLangOptions().ObjCAutoRefCount)
7060 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007061 }
Chris Lattnerea714382008-08-21 18:04:13 +00007062 } else {
7063 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007064 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007065 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007066
Chris Lattner326f7572008-11-18 01:30:42 +00007067 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007068 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007069 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007070
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007071 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007072
Steve Naroff98cf3e92007-06-06 18:38:38 +00007073 // C99 6.5.16p3: The type of an assignment expression is the type of the
7074 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007075 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007076 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7077 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007078 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007079 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007080 return (getLangOptions().CPlusPlus
7081 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007082}
7083
Chris Lattner326f7572008-11-18 01:30:42 +00007084// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007085static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007086 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007087 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007088
John McCall3aef3d82011-04-10 19:13:55 +00007089 LHS = S.CheckPlaceholderExpr(LHS.take());
7090 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007091 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007092 return QualType();
7093
John McCall73d36182010-10-12 07:14:40 +00007094 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7095 // operands, but not unary promotions.
7096 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007097
John McCall34376a62010-12-04 03:47:34 +00007098 // So we treat the LHS as a ignored value, and in C++ we allow the
7099 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007100 LHS = S.IgnoredValueConversions(LHS.take());
7101 if (LHS.isInvalid())
7102 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007103
7104 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007105 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7106 if (RHS.isInvalid())
7107 return QualType();
7108 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007109 S.RequireCompleteType(Loc, RHS.get()->getType(),
7110 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007111 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007112
John Wiegley01296292011-04-08 18:41:53 +00007113 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007114}
7115
Steve Naroff7a5af782007-07-13 16:58:59 +00007116/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7117/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007118static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7119 ExprValueKind &VK,
7120 SourceLocation OpLoc,
7121 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007122 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007123 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007124
Chris Lattner6b0cf142008-11-21 07:05:48 +00007125 QualType ResType = Op->getType();
7126 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007127
John McCall4bc41ae2010-11-18 19:01:18 +00007128 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007129 // Decrement of bool is not allowed.
7130 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007131 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007132 return QualType();
7133 }
7134 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007135 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007136 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007137 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007138 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007139 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007140 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007141 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007142
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007143 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007144 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007145 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007146 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007147 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007148 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007149 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007150 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007151 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007152 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007153 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7154 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007155 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7156 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007157 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007158 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007159 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007160 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007161 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007162 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007163 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007164 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007165 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007166 // In C++, a prefix increment is the same type as the operand. Otherwise
7167 // (in C or with postfix), the increment is the unqualified type of the
7168 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007169 if (isPrefix && S.getLangOptions().CPlusPlus) {
7170 VK = VK_LValue;
7171 return ResType;
7172 } else {
7173 VK = VK_RValue;
7174 return ResType.getUnqualifiedType();
7175 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007176}
7177
John Wiegley01296292011-04-08 18:41:53 +00007178ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007179 assert(E->getValueKind() == VK_LValue &&
7180 E->getObjectKind() == OK_ObjCProperty);
7181 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7182
Douglas Gregor33823722011-06-11 01:09:30 +00007183 QualType T = E->getType();
7184 QualType ReceiverType;
7185 if (PRE->isObjectReceiver())
7186 ReceiverType = PRE->getBase()->getType();
7187 else if (PRE->isSuperReceiver())
7188 ReceiverType = PRE->getSuperReceiverType();
7189 else
7190 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7191
John McCall34376a62010-12-04 03:47:34 +00007192 ExprValueKind VK = VK_RValue;
7193 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007194 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007195 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007196 T = getMessageSendResultType(ReceiverType, GetterMethod,
7197 PRE->isClassReceiver(),
7198 PRE->isSuperReceiver());
7199 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007200 }
7201 else {
7202 Diag(PRE->getLocation(), diag::err_getter_not_found)
7203 << PRE->getBase()->getType();
7204 }
John McCall34376a62010-12-04 03:47:34 +00007205 }
Douglas Gregor33823722011-06-11 01:09:30 +00007206
7207 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007208 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007209
7210 ExprResult Result = MaybeBindToTemporary(E);
7211 if (!Result.isInvalid())
7212 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007213
7214 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007215}
7216
Richard Trieucfc491d2011-08-02 04:35:43 +00007217void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7218 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007219 assert(LHS.get()->getValueKind() == VK_LValue &&
7220 LHS.get()->getObjectKind() == OK_ObjCProperty);
7221 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007222
John McCall31168b02011-06-15 23:02:42 +00007223 bool Consumed = false;
7224
John Wiegley01296292011-04-08 18:41:53 +00007225 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007226 // If using property-dot syntax notation for assignment, and there is a
7227 // setter, RHS expression is being passed to the setter argument. So,
7228 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007229 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007230 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7231 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007232 Consumed = (getLangOptions().ObjCAutoRefCount &&
7233 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007234
7235 // Otherwise, if the getter returns an l-value, just call that.
7236 } else {
John Wiegley01296292011-04-08 18:41:53 +00007237 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007238 ExprValueKind VK = Expr::getValueKindForType(Result);
7239 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007240 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7241 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007242 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007243 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007244 }
John McCall31168b02011-06-15 23:02:42 +00007245 } else if (getLangOptions().ObjCAutoRefCount) {
7246 const ObjCMethodDecl *setter
7247 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7248 if (setter) {
7249 ObjCMethodDecl::param_iterator P = setter->param_begin();
7250 LHSTy = (*P)->getType();
7251 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7252 }
John McCall34376a62010-12-04 03:47:34 +00007253 }
7254
John McCall31168b02011-06-15 23:02:42 +00007255 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7256 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007257 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007258 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007259 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007260 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007261 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007262 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7263 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7264 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007265 }
7266}
7267
7268
Anders Carlsson806700f2008-02-01 07:15:58 +00007269/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007270/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007271/// where the declaration is needed for type checking. We only need to
7272/// handle cases when the expression references a function designator
7273/// or is an lvalue. Here are some examples:
7274/// - &(x) => x
7275/// - &*****f => f for f a function designator.
7276/// - &s.xx => s
7277/// - &s.zz[1].yy -> s, if zz is an array
7278/// - *(x + 1) -> x, if x is an array
7279/// - &"123"[2] -> 0
7280/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007281static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007282 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007283 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007284 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007285 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007286 // If this is an arrow operator, the address is an offset from
7287 // the base's value, so the object the base refers to is
7288 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007289 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007290 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007291 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007292 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007293 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007294 // FIXME: This code shouldn't be necessary! We should catch the implicit
7295 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007296 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7297 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7298 if (ICE->getSubExpr()->getType()->isArrayType())
7299 return getPrimaryDecl(ICE->getSubExpr());
7300 }
7301 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007302 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007303 case Stmt::UnaryOperatorClass: {
7304 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007305
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007306 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007307 case UO_Real:
7308 case UO_Imag:
7309 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007310 return getPrimaryDecl(UO->getSubExpr());
7311 default:
7312 return 0;
7313 }
7314 }
Steve Naroff47500512007-04-19 23:00:49 +00007315 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007316 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007317 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007318 // If the result of an implicit cast is an l-value, we care about
7319 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007320 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007321 default:
7322 return 0;
7323 }
7324}
7325
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007326/// \brief Diagnose invalid operand for address of operations.
7327///
7328/// \param Type The type of operand which cannot have its address taken.
7329/// 0:bit-field 1:vector element 2:property expression 3:register variable
7330static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7331 Expr *E, unsigned Type) {
7332 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7333}
7334
Steve Naroff47500512007-04-19 23:00:49 +00007335/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007336/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007337/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007338/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007339/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007340/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007341/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007342static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7343 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007344 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007345 return S.Context.DependentTy;
7346 if (OrigOp->getType() == S.Context.OverloadTy)
7347 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007348 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7349 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007350 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7351 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7352 << OrigOp->getSourceRange();
7353 return QualType();
7354 }
John McCall8d08b9b2010-08-27 09:08:28 +00007355
John McCall2979fe02011-04-12 00:42:48 +00007356 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007357
John McCall8d08b9b2010-08-27 09:08:28 +00007358 // Make sure to ignore parentheses in subsequent checks
7359 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007360
John McCall4bc41ae2010-11-18 19:01:18 +00007361 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007362 // Implement C99-only parts of addressof rules.
7363 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007364 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007365 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7366 // (assuming the deref expression is valid).
7367 return uOp->getSubExpr()->getType();
7368 }
7369 // Technically, there should be a check for array subscript
7370 // expressions here, but the result of one is always an lvalue anyway.
7371 }
John McCallf3a88602011-02-03 08:15:49 +00007372 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007373 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007374
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007375 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007376 bool sfinae = S.isSFINAEContext();
7377 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7378 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007379 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007380 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007381 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007382 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007383 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007384 } else if (lval == Expr::LV_MemberFunction) {
7385 // If it's an instance method, make a member pointer.
7386 // The expression must have exactly the form &A::foo.
7387
7388 // If the underlying expression isn't a decl ref, give up.
7389 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007390 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007391 << OrigOp->getSourceRange();
7392 return QualType();
7393 }
7394 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7395 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7396
7397 // The id-expression was parenthesized.
7398 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007399 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007400 << OrigOp->getSourceRange();
7401
7402 // The method was named without a qualifier.
7403 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007404 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007405 << op->getSourceRange();
7406 }
7407
John McCall4bc41ae2010-11-18 19:01:18 +00007408 return S.Context.getMemberPointerType(op->getType(),
7409 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007410 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007411 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007412 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007413 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007414 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007415 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007416 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007417 return QualType();
7418 }
John McCall086a4642010-11-24 05:12:34 +00007419 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007420 // The operand cannot be a bit-field
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007421 diagnoseAddressOfInvalidType(S, OpLoc, op, /*bit-field*/ 0);
7422 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007423 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007424 // The operand cannot be an element of a vector
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007425 diagnoseAddressOfInvalidType(S, OpLoc, op, /*vector element*/ 1);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007426 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007427 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007428 // cannot take address of a property expression.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007429 diagnoseAddressOfInvalidType(S, OpLoc, op, /*property expression*/ 2);
Fariborz Jahanian385db802009-07-07 18:50:52 +00007430 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007431 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007432 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007433 // with the register storage-class specifier.
7434 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007435 // in C++ it is not error to take address of a register
7436 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007437 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007438 !S.getLangOptions().CPlusPlus) {
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007439 diagnoseAddressOfInvalidType(S, OpLoc, op, /*register variable*/ 3);
Steve Naroff35d85152007-05-07 00:24:15 +00007440 return QualType();
7441 }
John McCalld14a8642009-11-21 08:51:07 +00007442 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007443 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007444 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007445 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007446 // Could be a pointer to member, though, if there is an explicit
7447 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007448 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007449 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007450 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007451 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007452 S.Diag(OpLoc,
7453 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007454 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007455 return QualType();
7456 }
Mike Stump11289f42009-09-09 15:08:12 +00007457
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007458 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7459 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007460 return S.Context.getMemberPointerType(op->getType(),
7461 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007462 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007463 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007464 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007465 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007466 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007467
Eli Friedmance7f9002009-05-16 23:27:50 +00007468 if (lval == Expr::LV_IncompleteVoidType) {
7469 // Taking the address of a void variable is technically illegal, but we
7470 // allow it in cases which are otherwise valid.
7471 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007472 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007473 }
7474
Steve Naroff47500512007-04-19 23:00:49 +00007475 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007476 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007477 return S.Context.getObjCObjectPointerType(op->getType());
7478 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007479}
7480
Chris Lattner9156f1b2010-07-05 19:17:26 +00007481/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007482static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7483 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007484 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007485 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007486
John Wiegley01296292011-04-08 18:41:53 +00007487 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7488 if (ConvResult.isInvalid())
7489 return QualType();
7490 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007491 QualType OpTy = Op->getType();
7492 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007493
7494 if (isa<CXXReinterpretCastExpr>(Op)) {
7495 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7496 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7497 Op->getSourceRange());
7498 }
7499
Chris Lattner9156f1b2010-07-05 19:17:26 +00007500 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7501 // is an incomplete type or void. It would be possible to warn about
7502 // dereferencing a void pointer, but it's completely well-defined, and such a
7503 // warning is unlikely to catch any mistakes.
7504 if (const PointerType *PT = OpTy->getAs<PointerType>())
7505 Result = PT->getPointeeType();
7506 else if (const ObjCObjectPointerType *OPT =
7507 OpTy->getAs<ObjCObjectPointerType>())
7508 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007509 else {
John McCall3aef3d82011-04-10 19:13:55 +00007510 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007511 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007512 if (PR.take() != Op)
7513 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007514 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007515
Chris Lattner9156f1b2010-07-05 19:17:26 +00007516 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007517 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007518 << OpTy << Op->getSourceRange();
7519 return QualType();
7520 }
John McCall4bc41ae2010-11-18 19:01:18 +00007521
7522 // Dereferences are usually l-values...
7523 VK = VK_LValue;
7524
7525 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007526 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007527 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007528
7529 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007530}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007531
John McCalle3027922010-08-25 11:45:40 +00007532static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007533 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007534 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007535 switch (Kind) {
7536 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007537 case tok::periodstar: Opc = BO_PtrMemD; break;
7538 case tok::arrowstar: Opc = BO_PtrMemI; break;
7539 case tok::star: Opc = BO_Mul; break;
7540 case tok::slash: Opc = BO_Div; break;
7541 case tok::percent: Opc = BO_Rem; break;
7542 case tok::plus: Opc = BO_Add; break;
7543 case tok::minus: Opc = BO_Sub; break;
7544 case tok::lessless: Opc = BO_Shl; break;
7545 case tok::greatergreater: Opc = BO_Shr; break;
7546 case tok::lessequal: Opc = BO_LE; break;
7547 case tok::less: Opc = BO_LT; break;
7548 case tok::greaterequal: Opc = BO_GE; break;
7549 case tok::greater: Opc = BO_GT; break;
7550 case tok::exclaimequal: Opc = BO_NE; break;
7551 case tok::equalequal: Opc = BO_EQ; break;
7552 case tok::amp: Opc = BO_And; break;
7553 case tok::caret: Opc = BO_Xor; break;
7554 case tok::pipe: Opc = BO_Or; break;
7555 case tok::ampamp: Opc = BO_LAnd; break;
7556 case tok::pipepipe: Opc = BO_LOr; break;
7557 case tok::equal: Opc = BO_Assign; break;
7558 case tok::starequal: Opc = BO_MulAssign; break;
7559 case tok::slashequal: Opc = BO_DivAssign; break;
7560 case tok::percentequal: Opc = BO_RemAssign; break;
7561 case tok::plusequal: Opc = BO_AddAssign; break;
7562 case tok::minusequal: Opc = BO_SubAssign; break;
7563 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7564 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7565 case tok::ampequal: Opc = BO_AndAssign; break;
7566 case tok::caretequal: Opc = BO_XorAssign; break;
7567 case tok::pipeequal: Opc = BO_OrAssign; break;
7568 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007569 }
7570 return Opc;
7571}
7572
John McCalle3027922010-08-25 11:45:40 +00007573static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007574 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007575 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007576 switch (Kind) {
7577 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007578 case tok::plusplus: Opc = UO_PreInc; break;
7579 case tok::minusminus: Opc = UO_PreDec; break;
7580 case tok::amp: Opc = UO_AddrOf; break;
7581 case tok::star: Opc = UO_Deref; break;
7582 case tok::plus: Opc = UO_Plus; break;
7583 case tok::minus: Opc = UO_Minus; break;
7584 case tok::tilde: Opc = UO_Not; break;
7585 case tok::exclaim: Opc = UO_LNot; break;
7586 case tok::kw___real: Opc = UO_Real; break;
7587 case tok::kw___imag: Opc = UO_Imag; break;
7588 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007589 }
7590 return Opc;
7591}
7592
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007593/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7594/// This warning is only emitted for builtin assignment operations. It is also
7595/// suppressed in the event of macro expansions.
7596static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7597 SourceLocation OpLoc) {
7598 if (!S.ActiveTemplateInstantiations.empty())
7599 return;
7600 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7601 return;
7602 lhs = lhs->IgnoreParenImpCasts();
7603 rhs = rhs->IgnoreParenImpCasts();
7604 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7605 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7606 if (!LeftDeclRef || !RightDeclRef ||
7607 LeftDeclRef->getLocation().isMacroID() ||
7608 RightDeclRef->getLocation().isMacroID())
7609 return;
7610 const ValueDecl *LeftDecl =
7611 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7612 const ValueDecl *RightDecl =
7613 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7614 if (LeftDecl != RightDecl)
7615 return;
7616 if (LeftDecl->getType().isVolatileQualified())
7617 return;
7618 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7619 if (RefTy->getPointeeType().isVolatileQualified())
7620 return;
7621
7622 S.Diag(OpLoc, diag::warn_self_assignment)
7623 << LeftDeclRef->getType()
7624 << lhs->getSourceRange() << rhs->getSourceRange();
7625}
7626
Richard Trieueea56f72011-09-02 03:48:46 +00007627// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7628// expression. These are mainly cases where the null pointer is used as an
7629// integer instead of a pointer.
7630static void checkArithmeticNull(Sema &S, ExprResult &lex, ExprResult &rex,
7631 SourceLocation Loc, bool isCompare) {
7632 // The canonical way to check for a GNU null is with isNullPointerConstant,
7633 // but we use a bit of a hack here for speed; this is a relatively
7634 // hot path, and isNullPointerConstant is slow.
7635 bool LeftNull = isa<GNUNullExpr>(lex.get()->IgnoreParenImpCasts());
7636 bool RightNull = isa<GNUNullExpr>(rex.get()->IgnoreParenImpCasts());
7637
7638 // Detect when a NULL constant is used improperly in an expression. These
7639 // are mainly cases where the null pointer is used as an integer instead
7640 // of a pointer.
7641 if (!LeftNull && !RightNull)
7642 return;
7643
7644 QualType LeftType = lex.get()->getType();
7645 QualType RightType = rex.get()->getType();
7646
7647 // Avoid analyzing cases where the result will either be invalid (and
7648 // diagnosed as such) or entirely valid and not something to warn about.
7649 if (LeftType->isBlockPointerType() || LeftType->isMemberPointerType() ||
7650 LeftType->isFunctionType() || RightType->isBlockPointerType() ||
7651 RightType->isMemberPointerType() || RightType->isFunctionType())
7652 return;
7653
7654 // Comparison operations would not make sense with a null pointer no matter
7655 // what the other expression is.
7656 if (!isCompare) {
7657 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7658 << (LeftNull ? lex.get()->getSourceRange() : SourceRange())
7659 << (RightNull ? rex.get()->getSourceRange() : SourceRange());
7660 return;
7661 }
7662
7663 // The rest of the operations only make sense with a null pointer
7664 // if the other expression is a pointer.
7665 if (LeftNull == RightNull || LeftType->isAnyPointerType() ||
7666 LeftType->canDecayToPointerType() || RightType->isAnyPointerType() ||
7667 RightType->canDecayToPointerType())
7668 return;
7669
7670 S.Diag(Loc, diag::warn_null_in_comparison_operation)
7671 << LeftNull /* LHS is NULL */
7672 << (LeftNull ? rex.get()->getType() : lex.get()->getType())
7673 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7674}
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007675/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7676/// operator @p Opc at location @c TokLoc. This routine only supports
7677/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007678ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007679 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007680 Expr *lhsExpr, Expr *rhsExpr) {
7681 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007682 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007683 // The following two variables are used for compound assignment operators
7684 QualType CompLHSTy; // Type of LHS after promotions for computation
7685 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007686 ExprValueKind VK = VK_RValue;
7687 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007688
Douglas Gregor1beec452011-03-12 01:48:56 +00007689 // Check if a 'foo<int>' involved in a binary op, identifies a single
7690 // function unambiguously (i.e. an lvalue ala 13.4)
7691 // But since an assignment can trigger target based overload, exclude it in
7692 // our blind search. i.e:
7693 // template<class T> void f(); template<class T, class U> void f(U);
7694 // f<int> == 0; // resolve f<int> blindly
7695 // void (*p)(int); p = f<int>; // resolve f<int> using target
7696 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007697 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007698 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007699 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007700
John McCall3aef3d82011-04-10 19:13:55 +00007701 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007702 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007703 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007704 }
7705
Richard Trieueea56f72011-09-02 03:48:46 +00007706 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7707 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7708 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7709 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7710 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7711 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign)
7712 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/false);
7713 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7714 Opc == BO_EQ || Opc == BO_NE)
7715 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/true);
Richard Trieu701fb362011-06-16 21:36:56 +00007716
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007717 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007718 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007719 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007720 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007721 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7722 VK = lhs.get()->getValueKind();
7723 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007724 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007725 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007726 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007727 break;
John McCalle3027922010-08-25 11:45:40 +00007728 case BO_PtrMemD:
7729 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007730 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007731 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007732 break;
John McCalle3027922010-08-25 11:45:40 +00007733 case BO_Mul:
7734 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007735 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007736 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007737 break;
John McCalle3027922010-08-25 11:45:40 +00007738 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007739 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7740 break;
John McCalle3027922010-08-25 11:45:40 +00007741 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007742 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7743 break;
John McCalle3027922010-08-25 11:45:40 +00007744 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007745 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7746 break;
John McCalle3027922010-08-25 11:45:40 +00007747 case BO_Shl:
7748 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007749 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007750 break;
John McCalle3027922010-08-25 11:45:40 +00007751 case BO_LE:
7752 case BO_LT:
7753 case BO_GE:
7754 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007755 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007756 break;
John McCalle3027922010-08-25 11:45:40 +00007757 case BO_EQ:
7758 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007759 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007760 break;
John McCalle3027922010-08-25 11:45:40 +00007761 case BO_And:
7762 case BO_Xor:
7763 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007764 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7765 break;
John McCalle3027922010-08-25 11:45:40 +00007766 case BO_LAnd:
7767 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007768 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007769 break;
John McCalle3027922010-08-25 11:45:40 +00007770 case BO_MulAssign:
7771 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007772 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007773 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007774 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007775 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7776 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007777 break;
John McCalle3027922010-08-25 11:45:40 +00007778 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007779 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7780 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007781 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7782 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007783 break;
John McCalle3027922010-08-25 11:45:40 +00007784 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007785 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007786 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7787 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007788 break;
John McCalle3027922010-08-25 11:45:40 +00007789 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007790 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007791 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7792 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007793 break;
John McCalle3027922010-08-25 11:45:40 +00007794 case BO_ShlAssign:
7795 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007796 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007797 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007798 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7799 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007800 break;
John McCalle3027922010-08-25 11:45:40 +00007801 case BO_AndAssign:
7802 case BO_XorAssign:
7803 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007804 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7805 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007806 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7807 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007808 break;
John McCalle3027922010-08-25 11:45:40 +00007809 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007810 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007811 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7812 VK = rhs.get()->getValueKind();
7813 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007814 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007815 break;
7816 }
John Wiegley01296292011-04-08 18:41:53 +00007817 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007818 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007819
7820 // Check for array bounds violations for both sides of the BinaryOperator
7821 CheckArrayAccess(lhs.get());
7822 CheckArrayAccess(rhs.get());
7823
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007824 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007825 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7826 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007827 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7828 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007829 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007830 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007831 }
John Wiegley01296292011-04-08 18:41:53 +00007832 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7833 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007834 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007835}
7836
Sebastian Redl44615072009-10-27 12:10:02 +00007837/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7838/// operators are mixed in a way that suggests that the programmer forgot that
7839/// comparison operators have higher precedence. The most typical example of
7840/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007841static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007842 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007843 typedef BinaryOperator BinOp;
7844 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7845 rhsopc = static_cast<BinOp::Opcode>(-1);
7846 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007847 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007848 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007849 rhsopc = BO->getOpcode();
7850
7851 // Subs are not binary operators.
7852 if (lhsopc == -1 && rhsopc == -1)
7853 return;
7854
7855 // Bitwise operations are sometimes used as eager logical ops.
7856 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007857 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7858 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007859 return;
7860
Richard Trieu73088052011-08-10 22:41:34 +00007861 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7862 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7863 if (!isLeftComp && !isRightComp) return;
7864
7865 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7866 : SourceRange(OpLoc, rhs->getLocEnd());
7867 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7868 : BinOp::getOpcodeStr(rhsopc);
7869 SourceRange ParensRange = isLeftComp ?
7870 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7871 rhs->getLocEnd())
7872 : SourceRange(lhs->getLocStart(),
7873 cast<BinOp>(rhs)->getLHS()->getLocStart());
7874
7875 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7876 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7877 SuggestParentheses(Self, OpLoc,
7878 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7879 rhs->getSourceRange());
7880 SuggestParentheses(Self, OpLoc,
7881 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7882 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007883}
7884
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007885/// \brief It accepts a '&' expr that is inside a '|' one.
7886/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7887/// in parentheses.
7888static void
7889EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7890 BinaryOperator *Bop) {
7891 assert(Bop->getOpcode() == BO_And);
7892 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7893 << Bop->getSourceRange() << OpLoc;
7894 SuggestParentheses(Self, Bop->getOperatorLoc(),
7895 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7896 Bop->getSourceRange());
7897}
7898
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007899/// \brief It accepts a '&&' expr that is inside a '||' one.
7900/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7901/// in parentheses.
7902static void
7903EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007904 BinaryOperator *Bop) {
7905 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007906 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7907 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007908 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007909 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007910 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007911}
7912
7913/// \brief Returns true if the given expression can be evaluated as a constant
7914/// 'true'.
7915static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7916 bool Res;
7917 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7918}
7919
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007920/// \brief Returns true if the given expression can be evaluated as a constant
7921/// 'false'.
7922static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7923 bool Res;
7924 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7925}
7926
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007927/// \brief Look for '&&' in the left hand of a '||' expr.
7928static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007929 Expr *OrLHS, Expr *OrRHS) {
7930 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007931 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007932 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7933 if (EvaluatesAsFalse(S, OrRHS))
7934 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007935 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7936 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7937 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7938 } else if (Bop->getOpcode() == BO_LOr) {
7939 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7940 // If it's "a || b && 1 || c" we didn't warn earlier for
7941 // "a || b && 1", but warn now.
7942 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7943 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7944 }
7945 }
7946 }
7947}
7948
7949/// \brief Look for '&&' in the right hand of a '||' expr.
7950static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007951 Expr *OrLHS, Expr *OrRHS) {
7952 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007953 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007954 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7955 if (EvaluatesAsFalse(S, OrLHS))
7956 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007957 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7958 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7959 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007960 }
7961 }
7962}
7963
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007964/// \brief Look for '&' in the left or right hand of a '|' expr.
7965static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7966 Expr *OrArg) {
7967 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7968 if (Bop->getOpcode() == BO_And)
7969 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7970 }
7971}
7972
Sebastian Redl43028242009-10-26 15:24:15 +00007973/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007974/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007975static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007976 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007977 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007978 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007979 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7980
7981 // Diagnose "arg1 & arg2 | arg3"
7982 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7983 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7984 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7985 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007986
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007987 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7988 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007989 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007990 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7991 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007992 }
Sebastian Redl43028242009-10-26 15:24:15 +00007993}
7994
Steve Naroff218bc2b2007-05-04 21:54:46 +00007995// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007996ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007997 tok::TokenKind Kind,
7998 Expr *lhs, Expr *rhs) {
7999 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008000 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8001 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008002
Sebastian Redl43028242009-10-26 15:24:15 +00008003 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8004 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8005
Douglas Gregor5287f092009-11-05 00:51:44 +00008006 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8007}
8008
John McCalldadc5752010-08-24 06:29:42 +00008009ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008010 BinaryOperatorKind Opc,
8011 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008012 if (getLangOptions().CPlusPlus) {
8013 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008014
John McCall622114c2010-12-06 05:26:58 +00008015 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8016 UseBuiltinOperator = false;
8017 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8018 UseBuiltinOperator = true;
8019 } else {
8020 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8021 !rhs->getType()->isOverloadableType();
8022 }
8023
8024 if (!UseBuiltinOperator) {
8025 // Find all of the overloaded operators visible from this
8026 // point. We perform both an operator-name lookup from the local
8027 // scope and an argument-dependent lookup based on the types of
8028 // the arguments.
8029 UnresolvedSet<16> Functions;
8030 OverloadedOperatorKind OverOp
8031 = BinaryOperator::getOverloadedOperator(Opc);
8032 if (S && OverOp != OO_None)
8033 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8034 Functions);
8035
8036 // Build the (potentially-overloaded, potentially-dependent)
8037 // binary operation.
8038 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8039 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008040 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008041
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008042 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008043 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008044}
8045
John McCalldadc5752010-08-24 06:29:42 +00008046ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008047 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008048 Expr *InputExpr) {
8049 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008050 ExprValueKind VK = VK_RValue;
8051 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008052 QualType resultType;
8053 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008054 case UO_PreInc:
8055 case UO_PreDec:
8056 case UO_PostInc:
8057 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008058 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008059 Opc == UO_PreInc ||
8060 Opc == UO_PostInc,
8061 Opc == UO_PreInc ||
8062 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008063 break;
John McCalle3027922010-08-25 11:45:40 +00008064 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008065 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008066 break;
John McCall31996342011-04-07 08:22:57 +00008067 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008068 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008069 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008070 Input = move(resolved);
8071 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8072 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008073 break;
John McCall31996342011-04-07 08:22:57 +00008074 }
John McCalle3027922010-08-25 11:45:40 +00008075 case UO_Plus:
8076 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008077 Input = UsualUnaryConversions(Input.take());
8078 if (Input.isInvalid()) return ExprError();
8079 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008080 if (resultType->isDependentType())
8081 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008082 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8083 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008084 break;
8085 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8086 resultType->isEnumeralType())
8087 break;
8088 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008089 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008090 resultType->isPointerType())
8091 break;
John McCall36226622010-10-12 02:09:17 +00008092 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008093 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008094 if (Input.isInvalid()) return ExprError();
8095 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008096 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008097
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008098 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008099 << resultType << Input.get()->getSourceRange());
8100
John McCalle3027922010-08-25 11:45:40 +00008101 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008102 Input = UsualUnaryConversions(Input.take());
8103 if (Input.isInvalid()) return ExprError();
8104 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008105 if (resultType->isDependentType())
8106 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008107 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8108 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8109 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008110 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008111 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008112 else if (resultType->hasIntegerRepresentation())
8113 break;
8114 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008115 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008116 if (Input.isInvalid()) return ExprError();
8117 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008118 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008119 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008120 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008121 }
Steve Naroff35d85152007-05-07 00:24:15 +00008122 break;
John Wiegley01296292011-04-08 18:41:53 +00008123
John McCalle3027922010-08-25 11:45:40 +00008124 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008125 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008126 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8127 if (Input.isInvalid()) return ExprError();
8128 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008129 if (resultType->isDependentType())
8130 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008131 if (resultType->isScalarType()) {
8132 // C99 6.5.3.3p1: ok, fallthrough;
8133 if (Context.getLangOptions().CPlusPlus) {
8134 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8135 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008136 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8137 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008138 }
John McCall36226622010-10-12 02:09:17 +00008139 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008140 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008141 if (Input.isInvalid()) return ExprError();
8142 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008143 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008144 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008145 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008146 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008147
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008148 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008149 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008150 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008151 break;
John McCalle3027922010-08-25 11:45:40 +00008152 case UO_Real:
8153 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008154 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008155 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008156 if (Input.isInvalid()) return ExprError();
8157 if (Input.get()->getValueKind() != VK_RValue &&
8158 Input.get()->getObjectKind() == OK_Ordinary)
8159 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008160 break;
John McCalle3027922010-08-25 11:45:40 +00008161 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008162 resultType = Input.get()->getType();
8163 VK = Input.get()->getValueKind();
8164 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008165 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008166 }
John Wiegley01296292011-04-08 18:41:53 +00008167 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008168 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008169
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008170 // Check for array bounds violations in the operand of the UnaryOperator,
8171 // except for the '*' and '&' operators that have to be handled specially
8172 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8173 // that are explicitly defined as valid by the standard).
8174 if (Opc != UO_AddrOf && Opc != UO_Deref)
8175 CheckArrayAccess(Input.get());
8176
John Wiegley01296292011-04-08 18:41:53 +00008177 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008178 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008179}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008180
John McCalldadc5752010-08-24 06:29:42 +00008181ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008182 UnaryOperatorKind Opc,
8183 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008184 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008185 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008186 // Find all of the overloaded operators visible from this
8187 // point. We perform both an operator-name lookup from the local
8188 // scope and an argument-dependent lookup based on the types of
8189 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008190 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008191 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008192 if (S && OverOp != OO_None)
8193 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8194 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008195
John McCallb268a282010-08-23 23:25:46 +00008196 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008197 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008198
John McCallb268a282010-08-23 23:25:46 +00008199 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008200}
8201
Douglas Gregor5287f092009-11-05 00:51:44 +00008202// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008203ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008204 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008205 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008206}
8207
Steve Naroff66356bd2007-09-16 14:56:35 +00008208/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008209ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008210 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008211 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008212 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008213 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008214 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008215}
8216
John McCall31168b02011-06-15 23:02:42 +00008217/// Given the last statement in a statement-expression, check whether
8218/// the result is a producing expression (like a call to an
8219/// ns_returns_retained function) and, if so, rebuild it to hoist the
8220/// release out of the full-expression. Otherwise, return null.
8221/// Cannot fail.
8222static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8223 // Should always be wrapped with one of these.
8224 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8225 if (!cleanups) return 0;
8226
8227 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8228 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8229 return 0;
8230
8231 // Splice out the cast. This shouldn't modify any interesting
8232 // features of the statement.
8233 Expr *producer = cast->getSubExpr();
8234 assert(producer->getType() == cast->getType());
8235 assert(producer->getValueKind() == cast->getValueKind());
8236 cleanups->setSubExpr(producer);
8237 return cleanups;
8238}
8239
John McCalldadc5752010-08-24 06:29:42 +00008240ExprResult
John McCallb268a282010-08-23 23:25:46 +00008241Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008242 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008243 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8244 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8245
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008246 bool isFileScope
8247 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008248 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008249 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008250
Chris Lattner366727f2007-07-24 16:58:17 +00008251 // FIXME: there are a variety of strange constraints to enforce here, for
8252 // example, it is not possible to goto into a stmt expression apparently.
8253 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008254
Chris Lattner366727f2007-07-24 16:58:17 +00008255 // If there are sub stmts in the compound stmt, take the type of the last one
8256 // as the type of the stmtexpr.
8257 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008258 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008259 if (!Compound->body_empty()) {
8260 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008261 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008262 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008263 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8264 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008265 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008266 }
John McCall31168b02011-06-15 23:02:42 +00008267
John Wiegley01296292011-04-08 18:41:53 +00008268 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008269 // Do function/array conversion on the last expression, but not
8270 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008271 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8272 if (LastExpr.isInvalid())
8273 return ExprError();
8274 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008275
John Wiegley01296292011-04-08 18:41:53 +00008276 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008277 // In ARC, if the final expression ends in a consume, splice
8278 // the consume out and bind it later. In the alternate case
8279 // (when dealing with a retainable type), the result
8280 // initialization will create a produce. In both cases the
8281 // result will be +1, and we'll need to balance that out with
8282 // a bind.
8283 if (Expr *rebuiltLastStmt
8284 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8285 LastExpr = rebuiltLastStmt;
8286 } else {
8287 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008288 InitializedEntity::InitializeResult(LPLoc,
8289 Ty,
8290 false),
8291 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008292 LastExpr);
8293 }
8294
John Wiegley01296292011-04-08 18:41:53 +00008295 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008296 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008297 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008298 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008299 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008300 else
John Wiegley01296292011-04-08 18:41:53 +00008301 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008302 StmtExprMayBindToTemp = true;
8303 }
8304 }
8305 }
Chris Lattner944d3062008-07-26 19:51:01 +00008306 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008307
Eli Friedmanba961a92009-03-23 00:24:07 +00008308 // FIXME: Check that expression type is complete/non-abstract; statement
8309 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008310 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8311 if (StmtExprMayBindToTemp)
8312 return MaybeBindToTemporary(ResStmtExpr);
8313 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008314}
Steve Naroff78864672007-08-01 22:05:33 +00008315
John McCalldadc5752010-08-24 06:29:42 +00008316ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008317 TypeSourceInfo *TInfo,
8318 OffsetOfComponent *CompPtr,
8319 unsigned NumComponents,
8320 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008321 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008322 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008323 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008324
Chris Lattnerf17bd422007-08-30 17:45:32 +00008325 // We must have at least one component that refers to the type, and the first
8326 // one is known to be a field designator. Verify that the ArgTy represents
8327 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008328 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008329 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8330 << ArgTy << TypeRange);
8331
8332 // Type must be complete per C99 7.17p3 because a declaring a variable
8333 // with an incomplete type would be ill-formed.
8334 if (!Dependent
8335 && RequireCompleteType(BuiltinLoc, ArgTy,
8336 PDiag(diag::err_offsetof_incomplete_type)
8337 << TypeRange))
8338 return ExprError();
8339
Chris Lattner78502cf2007-08-31 21:49:13 +00008340 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8341 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008342 // FIXME: This diagnostic isn't actually visible because the location is in
8343 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008344 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008345 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8346 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008347
8348 bool DidWarnAboutNonPOD = false;
8349 QualType CurrentType = ArgTy;
8350 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008351 SmallVector<OffsetOfNode, 4> Comps;
8352 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008353 for (unsigned i = 0; i != NumComponents; ++i) {
8354 const OffsetOfComponent &OC = CompPtr[i];
8355 if (OC.isBrackets) {
8356 // Offset of an array sub-field. TODO: Should we allow vector elements?
8357 if (!CurrentType->isDependentType()) {
8358 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8359 if(!AT)
8360 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8361 << CurrentType);
8362 CurrentType = AT->getElementType();
8363 } else
8364 CurrentType = Context.DependentTy;
8365
8366 // The expression must be an integral expression.
8367 // FIXME: An integral constant expression?
8368 Expr *Idx = static_cast<Expr*>(OC.U.E);
8369 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8370 !Idx->getType()->isIntegerType())
8371 return ExprError(Diag(Idx->getLocStart(),
8372 diag::err_typecheck_subscript_not_integer)
8373 << Idx->getSourceRange());
8374
8375 // Record this array index.
8376 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8377 Exprs.push_back(Idx);
8378 continue;
8379 }
8380
8381 // Offset of a field.
8382 if (CurrentType->isDependentType()) {
8383 // We have the offset of a field, but we can't look into the dependent
8384 // type. Just record the identifier of the field.
8385 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8386 CurrentType = Context.DependentTy;
8387 continue;
8388 }
8389
8390 // We need to have a complete type to look into.
8391 if (RequireCompleteType(OC.LocStart, CurrentType,
8392 diag::err_offsetof_incomplete_type))
8393 return ExprError();
8394
8395 // Look for the designated field.
8396 const RecordType *RC = CurrentType->getAs<RecordType>();
8397 if (!RC)
8398 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8399 << CurrentType);
8400 RecordDecl *RD = RC->getDecl();
8401
8402 // C++ [lib.support.types]p5:
8403 // The macro offsetof accepts a restricted set of type arguments in this
8404 // International Standard. type shall be a POD structure or a POD union
8405 // (clause 9).
8406 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8407 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008408 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008409 PDiag(diag::warn_offsetof_non_pod_type)
8410 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8411 << CurrentType))
8412 DidWarnAboutNonPOD = true;
8413 }
8414
8415 // Look for the field.
8416 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8417 LookupQualifiedName(R, RD);
8418 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008419 IndirectFieldDecl *IndirectMemberDecl = 0;
8420 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008421 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008422 MemberDecl = IndirectMemberDecl->getAnonField();
8423 }
8424
Douglas Gregor882211c2010-04-28 22:16:22 +00008425 if (!MemberDecl)
8426 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8427 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8428 OC.LocEnd));
8429
Douglas Gregor10982ea2010-04-28 22:36:06 +00008430 // C99 7.17p3:
8431 // (If the specified member is a bit-field, the behavior is undefined.)
8432 //
8433 // We diagnose this as an error.
8434 if (MemberDecl->getBitWidth()) {
8435 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8436 << MemberDecl->getDeclName()
8437 << SourceRange(BuiltinLoc, RParenLoc);
8438 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8439 return ExprError();
8440 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008441
8442 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008443 if (IndirectMemberDecl)
8444 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008445
Douglas Gregord1702062010-04-29 00:18:15 +00008446 // If the member was found in a base class, introduce OffsetOfNodes for
8447 // the base class indirections.
8448 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8449 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008450 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008451 CXXBasePath &Path = Paths.front();
8452 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8453 B != BEnd; ++B)
8454 Comps.push_back(OffsetOfNode(B->Base));
8455 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008456
Francois Pichet783dd6e2010-11-21 06:08:52 +00008457 if (IndirectMemberDecl) {
8458 for (IndirectFieldDecl::chain_iterator FI =
8459 IndirectMemberDecl->chain_begin(),
8460 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8461 assert(isa<FieldDecl>(*FI));
8462 Comps.push_back(OffsetOfNode(OC.LocStart,
8463 cast<FieldDecl>(*FI), OC.LocEnd));
8464 }
8465 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008466 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008467
Douglas Gregor882211c2010-04-28 22:16:22 +00008468 CurrentType = MemberDecl->getType().getNonReferenceType();
8469 }
8470
8471 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8472 TInfo, Comps.data(), Comps.size(),
8473 Exprs.data(), Exprs.size(), RParenLoc));
8474}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008475
John McCalldadc5752010-08-24 06:29:42 +00008476ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008477 SourceLocation BuiltinLoc,
8478 SourceLocation TypeLoc,
8479 ParsedType argty,
8480 OffsetOfComponent *CompPtr,
8481 unsigned NumComponents,
8482 SourceLocation RPLoc) {
8483
Douglas Gregor882211c2010-04-28 22:16:22 +00008484 TypeSourceInfo *ArgTInfo;
8485 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8486 if (ArgTy.isNull())
8487 return ExprError();
8488
Eli Friedman06dcfd92010-08-05 10:15:45 +00008489 if (!ArgTInfo)
8490 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8491
8492 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8493 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008494}
8495
8496
John McCalldadc5752010-08-24 06:29:42 +00008497ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008498 Expr *CondExpr,
8499 Expr *LHSExpr, Expr *RHSExpr,
8500 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008501 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8502
John McCall7decc9e2010-11-18 06:31:45 +00008503 ExprValueKind VK = VK_RValue;
8504 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008505 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008506 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008507 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008508 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008509 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008510 } else {
8511 // The conditional expression is required to be a constant expression.
8512 llvm::APSInt condEval(32);
8513 SourceLocation ExpLoc;
8514 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008515 return ExprError(Diag(ExpLoc,
8516 diag::err_typecheck_choose_expr_requires_constant)
8517 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008518
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008519 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008520 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8521
8522 resType = ActiveExpr->getType();
8523 ValueDependent = ActiveExpr->isValueDependent();
8524 VK = ActiveExpr->getValueKind();
8525 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008526 }
8527
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008528 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008529 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008530 resType->isDependentType(),
8531 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008532}
8533
Steve Naroffc540d662008-09-03 18:15:37 +00008534//===----------------------------------------------------------------------===//
8535// Clang Extensions.
8536//===----------------------------------------------------------------------===//
8537
8538/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008539void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008540 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8541 PushBlockScope(BlockScope, Block);
8542 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008543 if (BlockScope)
8544 PushDeclContext(BlockScope, Block);
8545 else
8546 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008547}
8548
Mike Stump82f071f2009-02-04 22:31:32 +00008549void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008550 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008551 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008552 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008553
John McCall8cb7bdf2010-06-04 23:28:52 +00008554 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008555 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008556
John McCall3882ace2011-01-05 12:14:39 +00008557 // GetTypeForDeclarator always produces a function type for a block
8558 // literal signature. Furthermore, it is always a FunctionProtoType
8559 // unless the function was written with a typedef.
8560 assert(T->isFunctionType() &&
8561 "GetTypeForDeclarator made a non-function block signature");
8562
8563 // Look for an explicit signature in that function type.
8564 FunctionProtoTypeLoc ExplicitSignature;
8565
8566 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8567 if (isa<FunctionProtoTypeLoc>(tmp)) {
8568 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8569
8570 // Check whether that explicit signature was synthesized by
8571 // GetTypeForDeclarator. If so, don't save that as part of the
8572 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008573 if (ExplicitSignature.getLocalRangeBegin() ==
8574 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008575 // This would be much cheaper if we stored TypeLocs instead of
8576 // TypeSourceInfos.
8577 TypeLoc Result = ExplicitSignature.getResultLoc();
8578 unsigned Size = Result.getFullDataSize();
8579 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8580 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8581
8582 ExplicitSignature = FunctionProtoTypeLoc();
8583 }
John McCalla3ccba02010-06-04 11:21:44 +00008584 }
Mike Stump11289f42009-09-09 15:08:12 +00008585
John McCall3882ace2011-01-05 12:14:39 +00008586 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8587 CurBlock->FunctionType = T;
8588
8589 const FunctionType *Fn = T->getAs<FunctionType>();
8590 QualType RetTy = Fn->getResultType();
8591 bool isVariadic =
8592 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8593
John McCall8e346702010-06-04 19:02:56 +00008594 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008595
John McCalla3ccba02010-06-04 11:21:44 +00008596 // Don't allow returning a objc interface by value.
8597 if (RetTy->isObjCObjectType()) {
8598 Diag(ParamInfo.getSourceRange().getBegin(),
8599 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8600 return;
8601 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008602
John McCalla3ccba02010-06-04 11:21:44 +00008603 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008604 // return type. TODO: what should we do with declarators like:
8605 // ^ * { ... }
8606 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008607 if (RetTy != Context.DependentTy)
8608 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008609
John McCalla3ccba02010-06-04 11:21:44 +00008610 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008611 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008612 if (ExplicitSignature) {
8613 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8614 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008615 if (Param->getIdentifier() == 0 &&
8616 !Param->isImplicit() &&
8617 !Param->isInvalidDecl() &&
8618 !getLangOptions().CPlusPlus)
8619 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008620 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008621 }
John McCalla3ccba02010-06-04 11:21:44 +00008622
8623 // Fake up parameter variables if we have a typedef, like
8624 // ^ fntype { ... }
8625 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8626 for (FunctionProtoType::arg_type_iterator
8627 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8628 ParmVarDecl *Param =
8629 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8630 ParamInfo.getSourceRange().getBegin(),
8631 *I);
John McCall8e346702010-06-04 19:02:56 +00008632 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008633 }
Steve Naroffc540d662008-09-03 18:15:37 +00008634 }
John McCalla3ccba02010-06-04 11:21:44 +00008635
John McCall8e346702010-06-04 19:02:56 +00008636 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008637 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008638 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008639 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8640 CurBlock->TheDecl->param_end(),
8641 /*CheckParameterNames=*/false);
8642 }
8643
John McCalla3ccba02010-06-04 11:21:44 +00008644 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008645 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008646
John McCall8e346702010-06-04 19:02:56 +00008647 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008648 Diag(ParamInfo.getAttributes()->getLoc(),
8649 diag::warn_attribute_sentinel_not_variadic) << 1;
8650 // FIXME: remove the attribute.
8651 }
8652
8653 // Put the parameter variables in scope. We can bail out immediately
8654 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008655 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008656 return;
8657
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008658 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008659 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8660 (*AI)->setOwningFunction(CurBlock->TheDecl);
8661
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008662 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008663 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008664 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008665
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008666 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008667 }
John McCallf7b2fb52010-01-22 00:28:27 +00008668 }
Steve Naroffc540d662008-09-03 18:15:37 +00008669}
8670
8671/// ActOnBlockError - If there is an error parsing a block, this callback
8672/// is invoked to pop the information about the block from the action impl.
8673void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008674 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008675 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008676 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008677}
8678
8679/// ActOnBlockStmtExpr - This is called when the body of a block statement
8680/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008681ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008682 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008683 // If blocks are disabled, emit an error.
8684 if (!LangOpts.Blocks)
8685 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008686
Douglas Gregor9a28e842010-03-01 23:15:13 +00008687 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008688
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008689 PopDeclContext();
8690
Steve Naroffc540d662008-09-03 18:15:37 +00008691 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008692 if (!BSI->ReturnType.isNull())
8693 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008694
Mike Stump3bf1ab42009-07-28 22:04:01 +00008695 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008696 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008697
John McCallc63de662011-02-02 13:00:07 +00008698 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008699 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8700 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008701
John McCall8e346702010-06-04 19:02:56 +00008702 // If the user wrote a function type in some form, try to use that.
8703 if (!BSI->FunctionType.isNull()) {
8704 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8705
8706 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8707 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8708
8709 // Turn protoless block types into nullary block types.
8710 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008711 FunctionProtoType::ExtProtoInfo EPI;
8712 EPI.ExtInfo = Ext;
8713 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008714
8715 // Otherwise, if we don't need to change anything about the function type,
8716 // preserve its sugar structure.
8717 } else if (FTy->getResultType() == RetTy &&
8718 (!NoReturn || FTy->getNoReturnAttr())) {
8719 BlockTy = BSI->FunctionType;
8720
8721 // Otherwise, make the minimal modifications to the function type.
8722 } else {
8723 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008724 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8725 EPI.TypeQuals = 0; // FIXME: silently?
8726 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008727 BlockTy = Context.getFunctionType(RetTy,
8728 FPT->arg_type_begin(),
8729 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008730 EPI);
John McCall8e346702010-06-04 19:02:56 +00008731 }
8732
8733 // If we don't have a function type, just build one from nothing.
8734 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008735 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008736 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008737 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008738 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008739
John McCall8e346702010-06-04 19:02:56 +00008740 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8741 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008742 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008743
Chris Lattner45542ea2009-04-19 05:28:12 +00008744 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008745 if (getCurFunction()->NeedsScopeChecking() &&
8746 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008747 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008748
Chris Lattner60f84492011-02-17 23:58:47 +00008749 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008750
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008751 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8752 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8753 const VarDecl *variable = ci->getVariable();
8754 QualType T = variable->getType();
8755 QualType::DestructionKind destructKind = T.isDestructedType();
8756 if (destructKind != QualType::DK_none)
8757 getCurFunction()->setHasBranchProtectedScope();
8758 }
8759
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008760 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8761 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8762 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8763
Douglas Gregor9a28e842010-03-01 23:15:13 +00008764 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008765}
8766
John McCalldadc5752010-08-24 06:29:42 +00008767ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008768 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008769 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008770 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008771 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008772 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008773}
8774
John McCalldadc5752010-08-24 06:29:42 +00008775ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008776 Expr *E, TypeSourceInfo *TInfo,
8777 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008778 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008779
Eli Friedman121ba0c2008-08-09 23:32:40 +00008780 // Get the va_list type
8781 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008782 if (VaListType->isArrayType()) {
8783 // Deal with implicit array decay; for example, on x86-64,
8784 // va_list is an array, but it's supposed to decay to
8785 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008786 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008787 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008788 ExprResult Result = UsualUnaryConversions(E);
8789 if (Result.isInvalid())
8790 return ExprError();
8791 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008792 } else {
8793 // Otherwise, the va_list argument must be an l-value because
8794 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008795 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008796 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008797 return ExprError();
8798 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008799
Douglas Gregorad3150c2009-05-19 23:10:31 +00008800 if (!E->isTypeDependent() &&
8801 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008802 return ExprError(Diag(E->getLocStart(),
8803 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008804 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008805 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008806
David Majnemerc75d1a12011-06-14 05:17:32 +00008807 if (!TInfo->getType()->isDependentType()) {
8808 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8809 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8810 << TInfo->getTypeLoc().getSourceRange()))
8811 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008812
David Majnemerc75d1a12011-06-14 05:17:32 +00008813 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8814 TInfo->getType(),
8815 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8816 << TInfo->getTypeLoc().getSourceRange()))
8817 return ExprError();
8818
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008819 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008820 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008821 TInfo->getType()->isObjCLifetimeType()
8822 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8823 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008824 << TInfo->getType()
8825 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008826 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008827
8828 // Check for va_arg where arguments of the given type will be promoted
8829 // (i.e. this va_arg is guaranteed to have undefined behavior).
8830 QualType PromoteType;
8831 if (TInfo->getType()->isPromotableIntegerType()) {
8832 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8833 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8834 PromoteType = QualType();
8835 }
8836 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8837 PromoteType = Context.DoubleTy;
8838 if (!PromoteType.isNull())
8839 Diag(TInfo->getTypeLoc().getBeginLoc(),
8840 diag::warn_second_parameter_to_va_arg_never_compatible)
8841 << TInfo->getType()
8842 << PromoteType
8843 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008844 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008845
Abramo Bagnara27db2392010-08-10 10:06:15 +00008846 QualType T = TInfo->getType().getNonLValueExprType(Context);
8847 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008848}
8849
John McCalldadc5752010-08-24 06:29:42 +00008850ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008851 // The type of __null will be int or long, depending on the size of
8852 // pointers on the target.
8853 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008854 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8855 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008856 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008857 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008858 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008859 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008860 Ty = Context.LongLongTy;
8861 else {
8862 assert(!"I don't know size of pointer!");
8863 Ty = Context.IntTy;
8864 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008865
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008866 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008867}
8868
Alexis Huntc46382e2010-04-28 23:02:27 +00008869static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008870 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008871 if (!SemaRef.getLangOptions().ObjC1)
8872 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008873
Anders Carlssonace5d072009-11-10 04:46:30 +00008874 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8875 if (!PT)
8876 return;
8877
8878 // Check if the destination is of type 'id'.
8879 if (!PT->isObjCIdType()) {
8880 // Check if the destination is the 'NSString' interface.
8881 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8882 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8883 return;
8884 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008885
Anders Carlssonace5d072009-11-10 04:46:30 +00008886 // Strip off any parens and casts.
8887 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008888 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008889 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008890
Douglas Gregora771f462010-03-31 17:46:05 +00008891 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008892}
8893
Chris Lattner9bad62c2008-01-04 18:04:52 +00008894bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8895 SourceLocation Loc,
8896 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008897 Expr *SrcExpr, AssignmentAction Action,
8898 bool *Complained) {
8899 if (Complained)
8900 *Complained = false;
8901
Chris Lattner9bad62c2008-01-04 18:04:52 +00008902 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008903 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008904 bool isInvalid = false;
8905 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008906 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008907 ConversionFixItGenerator ConvHints;
8908 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008909
Chris Lattner9bad62c2008-01-04 18:04:52 +00008910 switch (ConvTy) {
8911 default: assert(0 && "Unknown conversion type");
8912 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008913 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008914 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008915 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8916 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008917 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008918 case IntToPointer:
8919 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008920 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8921 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008922 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008923 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008924 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008925 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008926 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8927 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008928 if (Hint.isNull() && !CheckInferredResultType) {
8929 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8930 }
8931 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008932 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008933 case IncompatiblePointerSign:
8934 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8935 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008936 case FunctionVoidPointer:
8937 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8938 break;
John McCall4fff8f62011-02-01 00:10:29 +00008939 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008940 // Perform array-to-pointer decay if necessary.
8941 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8942
John McCall4fff8f62011-02-01 00:10:29 +00008943 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8944 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8945 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8946 DiagKind = diag::err_typecheck_incompatible_address_space;
8947 break;
John McCall31168b02011-06-15 23:02:42 +00008948
8949
8950 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008951 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008952 break;
John McCall4fff8f62011-02-01 00:10:29 +00008953 }
8954
8955 llvm_unreachable("unknown error case for discarding qualifiers!");
8956 // fallthrough
8957 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008958 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008959 // If the qualifiers lost were because we were applying the
8960 // (deprecated) C++ conversion from a string literal to a char*
8961 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8962 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008963 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008964 // bit of refactoring (so that the second argument is an
8965 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008966 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008967 // C++ semantics.
8968 if (getLangOptions().CPlusPlus &&
8969 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8970 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008971 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8972 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008973 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008974 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008975 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008976 case IntToBlockPointer:
8977 DiagKind = diag::err_int_to_block_pointer;
8978 break;
8979 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008980 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008981 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008982 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008983 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008984 // it can give a more specific diagnostic.
8985 DiagKind = diag::warn_incompatible_qualified_id;
8986 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008987 case IncompatibleVectors:
8988 DiagKind = diag::warn_incompatible_vectors;
8989 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008990 case IncompatibleObjCWeakRef:
8991 DiagKind = diag::err_arc_weak_unavailable_assign;
8992 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008993 case Incompatible:
8994 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008995 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8996 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008997 isInvalid = true;
8998 break;
8999 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009000
Douglas Gregorc68e1402010-04-09 00:35:39 +00009001 QualType FirstType, SecondType;
9002 switch (Action) {
9003 case AA_Assigning:
9004 case AA_Initializing:
9005 // The destination type comes first.
9006 FirstType = DstType;
9007 SecondType = SrcType;
9008 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009009
Douglas Gregorc68e1402010-04-09 00:35:39 +00009010 case AA_Returning:
9011 case AA_Passing:
9012 case AA_Converting:
9013 case AA_Sending:
9014 case AA_Casting:
9015 // The source type comes first.
9016 FirstType = SrcType;
9017 SecondType = DstType;
9018 break;
9019 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009020
Anna Zaks3b402712011-07-28 19:51:27 +00009021 PartialDiagnostic FDiag = PDiag(DiagKind);
9022 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9023
9024 // If we can fix the conversion, suggest the FixIts.
9025 assert(ConvHints.isNull() || Hint.isNull());
9026 if (!ConvHints.isNull()) {
9027 for (llvm::SmallVector<FixItHint, 1>::iterator
9028 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9029 HI != HE; ++HI)
9030 FDiag << *HI;
9031 } else {
9032 FDiag << Hint;
9033 }
9034 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9035
9036 Diag(Loc, FDiag);
9037
Douglas Gregor33823722011-06-11 01:09:30 +00009038 if (CheckInferredResultType)
9039 EmitRelatedResultTypeNote(SrcExpr);
9040
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009041 if (Complained)
9042 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009043 return isInvalid;
9044}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009045
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009046bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009047 llvm::APSInt ICEResult;
9048 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9049 if (Result)
9050 *Result = ICEResult;
9051 return false;
9052 }
9053
Anders Carlssone54e8a12008-11-30 19:50:32 +00009054 Expr::EvalResult EvalResult;
9055
Mike Stump4e1f26a2009-02-19 03:04:26 +00009056 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009057 EvalResult.HasSideEffects) {
9058 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9059
9060 if (EvalResult.Diag) {
9061 // We only show the note if it's not the usual "invalid subexpression"
9062 // or if it's actually in a subexpression.
9063 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9064 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9065 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9066 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009067
Anders Carlssone54e8a12008-11-30 19:50:32 +00009068 return true;
9069 }
9070
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009071 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9072 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009073
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009074 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009075 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9076 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009077 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009078
Anders Carlssone54e8a12008-11-30 19:50:32 +00009079 if (Result)
9080 *Result = EvalResult.Val.getInt();
9081 return false;
9082}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009083
Douglas Gregorff790f12009-11-26 00:44:06 +00009084void
Mike Stump11289f42009-09-09 15:08:12 +00009085Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009086 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009087 ExpressionEvaluationContextRecord(NewContext,
9088 ExprTemporaries.size(),
9089 ExprNeedsCleanups));
9090 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009091}
9092
Richard Trieucfc491d2011-08-02 04:35:43 +00009093void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009094 // Pop the current expression evaluation context off the stack.
9095 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9096 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009097
Douglas Gregorfab31f42009-12-12 07:57:52 +00009098 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9099 if (Rec.PotentiallyReferenced) {
9100 // Mark any remaining declarations in the current position of the stack
9101 // as "referenced". If they were not meant to be referenced, semantic
9102 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009103 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009104 I = Rec.PotentiallyReferenced->begin(),
9105 IEnd = Rec.PotentiallyReferenced->end();
9106 I != IEnd; ++I)
9107 MarkDeclarationReferenced(I->first, I->second);
9108 }
9109
9110 if (Rec.PotentiallyDiagnosed) {
9111 // Emit any pending diagnostics.
9112 for (PotentiallyEmittedDiagnostics::iterator
9113 I = Rec.PotentiallyDiagnosed->begin(),
9114 IEnd = Rec.PotentiallyDiagnosed->end();
9115 I != IEnd; ++I)
9116 Diag(I->first, I->second);
9117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009118 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009119
9120 // When are coming out of an unevaluated context, clear out any
9121 // temporaries that we may have created as part of the evaluation of
9122 // the expression in that context: they aren't relevant because they
9123 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009124 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009125 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9126 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009127 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9128
9129 // Otherwise, merge the contexts together.
9130 } else {
9131 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9132 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009133
9134 // Destroy the popped expression evaluation record.
9135 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009136}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009137
John McCall31168b02011-06-15 23:02:42 +00009138void Sema::DiscardCleanupsInEvaluationContext() {
9139 ExprTemporaries.erase(
9140 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9141 ExprTemporaries.end());
9142 ExprNeedsCleanups = false;
9143}
9144
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009145/// \brief Note that the given declaration was referenced in the source code.
9146///
9147/// This routine should be invoke whenever a given declaration is referenced
9148/// in the source code, and where that reference occurred. If this declaration
9149/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9150/// C99 6.9p3), then the declaration will be marked as used.
9151///
9152/// \param Loc the location where the declaration was referenced.
9153///
9154/// \param D the declaration that has been referenced by the source code.
9155void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9156 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009157
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009158 D->setReferenced();
9159
Douglas Gregorebada0772010-06-17 23:14:26 +00009160 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009161 return;
Mike Stump11289f42009-09-09 15:08:12 +00009162
Richard Trieucfc491d2011-08-02 04:35:43 +00009163 // Mark a parameter or variable declaration "used", regardless of whether
9164 // we're in a template or not. The reason for this is that unevaluated
9165 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9166 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009167 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009168 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009169 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009170 return;
9171 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009172
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009173 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9174 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009175
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009176 // Do not mark anything as "used" within a dependent context; wait for
9177 // an instantiation.
9178 if (CurContext->isDependentContext())
9179 return;
Mike Stump11289f42009-09-09 15:08:12 +00009180
Douglas Gregorff790f12009-11-26 00:44:06 +00009181 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009182 case Unevaluated:
9183 // We are in an expression that is not potentially evaluated; do nothing.
9184 return;
Mike Stump11289f42009-09-09 15:08:12 +00009185
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009186 case PotentiallyEvaluated:
9187 // We are in a potentially-evaluated expression, so this declaration is
9188 // "used"; handle this below.
9189 break;
Mike Stump11289f42009-09-09 15:08:12 +00009190
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009191 case PotentiallyPotentiallyEvaluated:
9192 // We are in an expression that may be potentially evaluated; queue this
9193 // declaration reference until we know whether the expression is
9194 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009195 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009196 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009197
9198 case PotentiallyEvaluatedIfUsed:
9199 // Referenced declarations will only be used if the construct in the
9200 // containing expression is used.
9201 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009202 }
Mike Stump11289f42009-09-09 15:08:12 +00009203
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009204 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009205 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009206 if (Constructor->isDefaulted()) {
9207 if (Constructor->isDefaultConstructor()) {
9208 if (Constructor->isTrivial())
9209 return;
9210 if (!Constructor->isUsed(false))
9211 DefineImplicitDefaultConstructor(Loc, Constructor);
9212 } else if (Constructor->isCopyConstructor()) {
9213 if (!Constructor->isUsed(false))
9214 DefineImplicitCopyConstructor(Loc, Constructor);
9215 } else if (Constructor->isMoveConstructor()) {
9216 if (!Constructor->isUsed(false))
9217 DefineImplicitMoveConstructor(Loc, Constructor);
9218 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009219 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009220
Douglas Gregor88d292c2010-05-13 16:44:06 +00009221 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009222 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009223 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009224 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009225 if (Destructor->isVirtual())
9226 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009227 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009228 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009229 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009230 if (!MethodDecl->isUsed(false)) {
9231 if (MethodDecl->isCopyAssignmentOperator())
9232 DefineImplicitCopyAssignment(Loc, MethodDecl);
9233 else
9234 DefineImplicitMoveAssignment(Loc, MethodDecl);
9235 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009236 } else if (MethodDecl->isVirtual())
9237 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009238 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009239 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009240 // Recursive functions should be marked when used from another function.
9241 if (CurContext == Function) return;
9242
Mike Stump11289f42009-09-09 15:08:12 +00009243 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009244 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009245 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009246 bool AlreadyInstantiated = false;
9247 if (FunctionTemplateSpecializationInfo *SpecInfo
9248 = Function->getTemplateSpecializationInfo()) {
9249 if (SpecInfo->getPointOfInstantiation().isInvalid())
9250 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009251 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009252 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009253 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009254 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009255 = Function->getMemberSpecializationInfo()) {
9256 if (MSInfo->getPointOfInstantiation().isInvalid())
9257 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009258 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009259 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009260 AlreadyInstantiated = true;
9261 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009262
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009263 if (!AlreadyInstantiated) {
9264 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9265 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9266 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9267 Loc));
9268 else
Chandler Carruth54080172010-08-25 08:44:16 +00009269 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009270 }
John McCall83779672011-02-19 02:53:41 +00009271 } else {
9272 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009273 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9274 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009275 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009276 MarkDeclarationReferenced(Loc, *i);
9277 }
John McCall83779672011-02-19 02:53:41 +00009278 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009279
John McCall83779672011-02-19 02:53:41 +00009280 // Keep track of used but undefined functions.
9281 if (!Function->isPure() && !Function->hasBody() &&
9282 Function->getLinkage() != ExternalLinkage) {
9283 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9284 if (old.isInvalid()) old = Loc;
9285 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009286
John McCall83779672011-02-19 02:53:41 +00009287 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009288 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009289 }
Mike Stump11289f42009-09-09 15:08:12 +00009290
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009291 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009292 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009293 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009294 Var->getInstantiatedFromStaticDataMember()) {
9295 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9296 assert(MSInfo && "Missing member specialization information?");
9297 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9298 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9299 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009300 // This is a modification of an existing AST node. Notify listeners.
9301 if (ASTMutationListener *L = getASTMutationListener())
9302 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009303 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009304 }
9305 }
Mike Stump11289f42009-09-09 15:08:12 +00009306
John McCall15dd4042011-02-21 19:25:48 +00009307 // Keep track of used but undefined variables. We make a hole in
9308 // the warning for static const data members with in-line
9309 // initializers.
John McCall83779672011-02-19 02:53:41 +00009310 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009311 && Var->getLinkage() != ExternalLinkage
9312 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009313 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9314 if (old.isInvalid()) old = Loc;
9315 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009316
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009317 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009318 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009319 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009320}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009321
Douglas Gregor5597ab42010-05-07 23:12:07 +00009322namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009323 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009324 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009325 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009326 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9327 Sema &S;
9328 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009329
Douglas Gregor5597ab42010-05-07 23:12:07 +00009330 public:
9331 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009332
Douglas Gregor5597ab42010-05-07 23:12:07 +00009333 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009334
9335 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9336 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009337 };
9338}
9339
Chandler Carruthaf80f662010-06-09 08:17:30 +00009340bool MarkReferencedDecls::TraverseTemplateArgument(
9341 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009342 if (Arg.getKind() == TemplateArgument::Declaration) {
9343 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9344 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009345
9346 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009347}
9348
Chandler Carruthaf80f662010-06-09 08:17:30 +00009349bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009350 if (ClassTemplateSpecializationDecl *Spec
9351 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9352 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009353 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009354 }
9355
Chandler Carruthc65667c2010-06-10 10:31:57 +00009356 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009357}
9358
9359void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9360 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009361 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009362}
9363
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009364namespace {
9365 /// \brief Helper class that marks all of the declarations referenced by
9366 /// potentially-evaluated subexpressions as "referenced".
9367 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9368 Sema &S;
9369
9370 public:
9371 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9372
9373 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9374
9375 void VisitDeclRefExpr(DeclRefExpr *E) {
9376 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9377 }
9378
9379 void VisitMemberExpr(MemberExpr *E) {
9380 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009381 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009382 }
9383
9384 void VisitCXXNewExpr(CXXNewExpr *E) {
9385 if (E->getConstructor())
9386 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9387 if (E->getOperatorNew())
9388 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9389 if (E->getOperatorDelete())
9390 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009391 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009392 }
9393
9394 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9395 if (E->getOperatorDelete())
9396 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009397 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9398 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9399 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9400 S.MarkDeclarationReferenced(E->getLocStart(),
9401 S.LookupDestructor(Record));
9402 }
9403
Douglas Gregor32b3de52010-09-11 23:32:50 +00009404 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009405 }
9406
9407 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9408 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009409 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009410 }
9411
9412 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9413 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9414 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009415
9416 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9417 Visit(E->getExpr());
9418 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009419 };
9420}
9421
9422/// \brief Mark any declarations that appear within this expression or any
9423/// potentially-evaluated subexpressions as "referenced".
9424void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9425 EvaluatedExprMarker(*this).Visit(E);
9426}
9427
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009428/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9429/// of the program being compiled.
9430///
9431/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009432/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009433/// possibility that the code will actually be executable. Code in sizeof()
9434/// expressions, code used only during overload resolution, etc., are not
9435/// potentially evaluated. This routine will suppress such diagnostics or,
9436/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009437/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009438/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009439///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009440/// This routine should be used for all diagnostics that describe the run-time
9441/// behavior of a program, such as passing a non-POD value through an ellipsis.
9442/// Failure to do so will likely result in spurious diagnostics or failures
9443/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009444bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009445 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009446 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009447 case Unevaluated:
9448 // The argument will never be evaluated, so don't complain.
9449 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009450
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009451 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009452 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009453 if (stmt && getCurFunctionOrMethodDecl()) {
9454 FunctionScopes.back()->PossiblyUnreachableDiags.
9455 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9456 }
9457 else
9458 Diag(Loc, PD);
9459
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009460 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009461
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009462 case PotentiallyPotentiallyEvaluated:
9463 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9464 break;
9465 }
9466
9467 return false;
9468}
9469
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009470bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9471 CallExpr *CE, FunctionDecl *FD) {
9472 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9473 return false;
9474
9475 PartialDiagnostic Note =
9476 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9477 << FD->getDeclName() : PDiag();
9478 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009479
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009480 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009481 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009482 PDiag(diag::err_call_function_incomplete_return)
9483 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009484 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009485 << CE->getSourceRange(),
9486 std::make_pair(NoteLoc, Note)))
9487 return true;
9488
9489 return false;
9490}
9491
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009492// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009493// will prevent this condition from triggering, which is what we want.
9494void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9495 SourceLocation Loc;
9496
John McCall0506e4a2009-11-11 02:41:58 +00009497 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009498 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009499
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009500 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009501 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009502 return;
9503
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009504 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9505
John McCallb0e419e2009-11-12 00:06:05 +00009506 // Greylist some idioms by putting them into a warning subcategory.
9507 if (ObjCMessageExpr *ME
9508 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9509 Selector Sel = ME->getSelector();
9510
John McCallb0e419e2009-11-12 00:06:05 +00009511 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009512 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009513 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9514
9515 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009516 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009517 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9518 }
John McCall0506e4a2009-11-11 02:41:58 +00009519
John McCalld5707ab2009-10-12 21:59:07 +00009520 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009521 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009522 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009523 return;
9524
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009525 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009526 Loc = Op->getOperatorLoc();
9527 } else {
9528 // Not an assignment.
9529 return;
9530 }
9531
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009532 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009533
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009534 SourceLocation Open = E->getSourceRange().getBegin();
9535 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9536 Diag(Loc, diag::note_condition_assign_silence)
9537 << FixItHint::CreateInsertion(Open, "(")
9538 << FixItHint::CreateInsertion(Close, ")");
9539
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009540 if (IsOrAssign)
9541 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9542 << FixItHint::CreateReplacement(Loc, "!=");
9543 else
9544 Diag(Loc, diag::note_condition_assign_to_comparison)
9545 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009546}
9547
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009548/// \brief Redundant parentheses over an equality comparison can indicate
9549/// that the user intended an assignment used as condition.
9550void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009551 // Don't warn if the parens came from a macro.
9552 SourceLocation parenLoc = parenE->getLocStart();
9553 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9554 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009555 // Don't warn for dependent expressions.
9556 if (parenE->isTypeDependent())
9557 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009558
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009559 Expr *E = parenE->IgnoreParens();
9560
9561 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009562 if (opE->getOpcode() == BO_EQ &&
9563 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9564 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009565 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009566
Ted Kremenekae022092011-02-02 02:20:30 +00009567 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009568 Diag(Loc, diag::note_equality_comparison_silence)
9569 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9570 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009571 Diag(Loc, diag::note_equality_comparison_to_assign)
9572 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009573 }
9574}
9575
John Wiegley01296292011-04-08 18:41:53 +00009576ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009577 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009578 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9579 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009580
John McCall0009fcc2011-04-26 20:42:42 +00009581 ExprResult result = CheckPlaceholderExpr(E);
9582 if (result.isInvalid()) return ExprError();
9583 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009584
John McCall0009fcc2011-04-26 20:42:42 +00009585 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009586 if (getLangOptions().CPlusPlus)
9587 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9588
John Wiegley01296292011-04-08 18:41:53 +00009589 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9590 if (ERes.isInvalid())
9591 return ExprError();
9592 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009593
9594 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009595 if (!T->isScalarType()) { // C99 6.8.4.1p1
9596 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9597 << T << E->getSourceRange();
9598 return ExprError();
9599 }
John McCalld5707ab2009-10-12 21:59:07 +00009600 }
9601
John Wiegley01296292011-04-08 18:41:53 +00009602 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009603}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009604
John McCalldadc5752010-08-24 06:29:42 +00009605ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9606 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009607 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009608 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009609
9610 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009611}
John McCall36e7fe32010-10-12 00:20:44 +00009612
John McCall31996342011-04-07 08:22:57 +00009613namespace {
John McCall2979fe02011-04-12 00:42:48 +00009614 /// A visitor for rebuilding a call to an __unknown_any expression
9615 /// to have an appropriate type.
9616 struct RebuildUnknownAnyFunction
9617 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9618
9619 Sema &S;
9620
9621 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9622
9623 ExprResult VisitStmt(Stmt *S) {
9624 llvm_unreachable("unexpected statement!");
9625 return ExprError();
9626 }
9627
9628 ExprResult VisitExpr(Expr *expr) {
9629 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9630 << expr->getSourceRange();
9631 return ExprError();
9632 }
9633
9634 /// Rebuild an expression which simply semantically wraps another
9635 /// expression which it shares the type and value kind of.
9636 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9637 ExprResult subResult = Visit(expr->getSubExpr());
9638 if (subResult.isInvalid()) return ExprError();
9639
9640 Expr *subExpr = subResult.take();
9641 expr->setSubExpr(subExpr);
9642 expr->setType(subExpr->getType());
9643 expr->setValueKind(subExpr->getValueKind());
9644 assert(expr->getObjectKind() == OK_Ordinary);
9645 return expr;
9646 }
9647
9648 ExprResult VisitParenExpr(ParenExpr *paren) {
9649 return rebuildSugarExpr(paren);
9650 }
9651
9652 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9653 return rebuildSugarExpr(op);
9654 }
9655
9656 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9657 ExprResult subResult = Visit(op->getSubExpr());
9658 if (subResult.isInvalid()) return ExprError();
9659
9660 Expr *subExpr = subResult.take();
9661 op->setSubExpr(subExpr);
9662 op->setType(S.Context.getPointerType(subExpr->getType()));
9663 assert(op->getValueKind() == VK_RValue);
9664 assert(op->getObjectKind() == OK_Ordinary);
9665 return op;
9666 }
9667
9668 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9669 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9670
9671 expr->setType(decl->getType());
9672
9673 assert(expr->getValueKind() == VK_RValue);
9674 if (S.getLangOptions().CPlusPlus &&
9675 !(isa<CXXMethodDecl>(decl) &&
9676 cast<CXXMethodDecl>(decl)->isInstance()))
9677 expr->setValueKind(VK_LValue);
9678
9679 return expr;
9680 }
9681
9682 ExprResult VisitMemberExpr(MemberExpr *mem) {
9683 return resolveDecl(mem, mem->getMemberDecl());
9684 }
9685
9686 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9687 return resolveDecl(ref, ref->getDecl());
9688 }
9689 };
9690}
9691
9692/// Given a function expression of unknown-any type, try to rebuild it
9693/// to have a function type.
9694static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9695 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9696 if (result.isInvalid()) return ExprError();
9697 return S.DefaultFunctionArrayConversion(result.take());
9698}
9699
9700namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009701 /// A visitor for rebuilding an expression of type __unknown_anytype
9702 /// into one which resolves the type directly on the referring
9703 /// expression. Strict preservation of the original source
9704 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009705 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009706 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009707
9708 Sema &S;
9709
9710 /// The current destination type.
9711 QualType DestType;
9712
9713 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9714 : S(S), DestType(castType) {}
9715
John McCall39439732011-04-09 22:50:59 +00009716 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009717 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009718 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009719 }
9720
John McCall2d2e8702011-04-11 07:02:50 +00009721 ExprResult VisitExpr(Expr *expr) {
9722 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9723 << expr->getSourceRange();
9724 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009725 }
9726
John McCall2d2e8702011-04-11 07:02:50 +00009727 ExprResult VisitCallExpr(CallExpr *call);
9728 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9729
John McCall39439732011-04-09 22:50:59 +00009730 /// Rebuild an expression which simply semantically wraps another
9731 /// expression which it shares the type and value kind of.
9732 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9733 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009734 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009735 Expr *subExpr = subResult.take();
9736 expr->setSubExpr(subExpr);
9737 expr->setType(subExpr->getType());
9738 expr->setValueKind(subExpr->getValueKind());
9739 assert(expr->getObjectKind() == OK_Ordinary);
9740 return expr;
9741 }
John McCall31996342011-04-07 08:22:57 +00009742
John McCall39439732011-04-09 22:50:59 +00009743 ExprResult VisitParenExpr(ParenExpr *paren) {
9744 return rebuildSugarExpr(paren);
9745 }
9746
9747 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9748 return rebuildSugarExpr(op);
9749 }
9750
John McCall2979fe02011-04-12 00:42:48 +00009751 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9752 const PointerType *ptr = DestType->getAs<PointerType>();
9753 if (!ptr) {
9754 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9755 << op->getSourceRange();
9756 return ExprError();
9757 }
9758 assert(op->getValueKind() == VK_RValue);
9759 assert(op->getObjectKind() == OK_Ordinary);
9760 op->setType(DestType);
9761
9762 // Build the sub-expression as if it were an object of the pointee type.
9763 DestType = ptr->getPointeeType();
9764 ExprResult subResult = Visit(op->getSubExpr());
9765 if (subResult.isInvalid()) return ExprError();
9766 op->setSubExpr(subResult.take());
9767 return op;
9768 }
9769
John McCall2d2e8702011-04-11 07:02:50 +00009770 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009771
John McCall2979fe02011-04-12 00:42:48 +00009772 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009773
John McCall2979fe02011-04-12 00:42:48 +00009774 ExprResult VisitMemberExpr(MemberExpr *mem) {
9775 return resolveDecl(mem, mem->getMemberDecl());
9776 }
John McCall39439732011-04-09 22:50:59 +00009777
9778 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009779 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009780 }
9781 };
9782}
9783
John McCall2d2e8702011-04-11 07:02:50 +00009784/// Rebuilds a call expression which yielded __unknown_anytype.
9785ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9786 Expr *callee = call->getCallee();
9787
9788 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009789 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009790 FK_FunctionPointer,
9791 FK_BlockPointer
9792 };
9793
9794 FnKind kind;
9795 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009796 if (type == S.Context.BoundMemberTy) {
9797 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9798 kind = FK_MemberFunction;
9799 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009800 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9801 type = ptr->getPointeeType();
9802 kind = FK_FunctionPointer;
9803 } else {
9804 type = type->castAs<BlockPointerType>()->getPointeeType();
9805 kind = FK_BlockPointer;
9806 }
9807 const FunctionType *fnType = type->castAs<FunctionType>();
9808
9809 // Verify that this is a legal result type of a function.
9810 if (DestType->isArrayType() || DestType->isFunctionType()) {
9811 unsigned diagID = diag::err_func_returning_array_function;
9812 if (kind == FK_BlockPointer)
9813 diagID = diag::err_block_returning_array_function;
9814
9815 S.Diag(call->getExprLoc(), diagID)
9816 << DestType->isFunctionType() << DestType;
9817 return ExprError();
9818 }
9819
9820 // Otherwise, go ahead and set DestType as the call's result.
9821 call->setType(DestType.getNonLValueExprType(S.Context));
9822 call->setValueKind(Expr::getValueKindForType(DestType));
9823 assert(call->getObjectKind() == OK_Ordinary);
9824
9825 // Rebuild the function type, replacing the result type with DestType.
9826 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9827 DestType = S.Context.getFunctionType(DestType,
9828 proto->arg_type_begin(),
9829 proto->getNumArgs(),
9830 proto->getExtProtoInfo());
9831 else
9832 DestType = S.Context.getFunctionNoProtoType(DestType,
9833 fnType->getExtInfo());
9834
9835 // Rebuild the appropriate pointer-to-function type.
9836 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009837 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009838 // Nothing to do.
9839 break;
9840
9841 case FK_FunctionPointer:
9842 DestType = S.Context.getPointerType(DestType);
9843 break;
9844
9845 case FK_BlockPointer:
9846 DestType = S.Context.getBlockPointerType(DestType);
9847 break;
9848 }
9849
9850 // Finally, we can recurse.
9851 ExprResult calleeResult = Visit(callee);
9852 if (!calleeResult.isUsable()) return ExprError();
9853 call->setCallee(calleeResult.take());
9854
9855 // Bind a temporary if necessary.
9856 return S.MaybeBindToTemporary(call);
9857}
9858
9859ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009860 // Verify that this is a legal result type of a call.
9861 if (DestType->isArrayType() || DestType->isFunctionType()) {
9862 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9863 << DestType->isFunctionType() << DestType;
9864 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009865 }
9866
John McCall3f4138c2011-07-13 17:56:40 +00009867 // Rewrite the method result type if available.
9868 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9869 assert(method->getResultType() == S.Context.UnknownAnyTy);
9870 method->setResultType(DestType);
9871 }
John McCall2979fe02011-04-12 00:42:48 +00009872
John McCall2d2e8702011-04-11 07:02:50 +00009873 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009874 msg->setType(DestType.getNonReferenceType());
9875 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009876
John McCall2979fe02011-04-12 00:42:48 +00009877 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009878}
9879
9880ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009881 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009882 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009883 assert(ice->getValueKind() == VK_RValue);
9884 assert(ice->getObjectKind() == OK_Ordinary);
9885
John McCall2979fe02011-04-12 00:42:48 +00009886 ice->setType(DestType);
9887
John McCall2d2e8702011-04-11 07:02:50 +00009888 // Rebuild the sub-expression as the pointee (function) type.
9889 DestType = DestType->castAs<PointerType>()->getPointeeType();
9890
9891 ExprResult result = Visit(ice->getSubExpr());
9892 if (!result.isUsable()) return ExprError();
9893
9894 ice->setSubExpr(result.take());
9895 return S.Owned(ice);
9896}
9897
John McCall2979fe02011-04-12 00:42:48 +00009898ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009899 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009900 QualType type = DestType;
9901
9902 // We know how to make this work for certain kinds of decls:
9903
9904 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009905 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall9a877fe2011-08-10 04:12:23 +00009906 if (const PointerType *ptr = type->getAs<PointerType>()) {
9907 DestType = ptr->getPointeeType();
9908 ExprResult result = resolveDecl(expr, decl);
9909 if (result.isInvalid()) return ExprError();
9910 return S.ImpCastExprToType(result.take(), type,
9911 CK_FunctionToPointerDecay, VK_RValue);
9912 }
9913
9914 if (!type->isFunctionType()) {
9915 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9916 << decl << expr->getSourceRange();
9917 return ExprError();
9918 }
John McCall2d2e8702011-04-11 07:02:50 +00009919
John McCall4adb38c2011-04-27 00:36:17 +00009920 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9921 if (method->isInstance()) {
9922 valueKind = VK_RValue;
9923 type = S.Context.BoundMemberTy;
9924 }
9925
John McCall2d2e8702011-04-11 07:02:50 +00009926 // Function references aren't l-values in C.
9927 if (!S.getLangOptions().CPlusPlus)
9928 valueKind = VK_RValue;
9929
9930 // - variables
9931 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009932 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9933 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009934 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009935 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9936 << decl << expr->getSourceRange();
9937 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009938 }
9939
9940 // - nothing else
9941 } else {
9942 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9943 << decl << expr->getSourceRange();
9944 return ExprError();
9945 }
9946
John McCall2979fe02011-04-12 00:42:48 +00009947 decl->setType(DestType);
9948 expr->setType(type);
9949 expr->setValueKind(valueKind);
9950 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009951}
9952
John McCall31996342011-04-07 08:22:57 +00009953/// Check a cast of an unknown-any type. We intentionally only
9954/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009955ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9956 Expr *castExpr, CastKind &castKind,
9957 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009958 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009959 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9960 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009961
John McCall39439732011-04-09 22:50:59 +00009962 castExpr = result.take();
9963 VK = castExpr->getValueKind();
9964 castKind = CK_NoOp;
9965
9966 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009967}
9968
9969static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9970 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009971 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009972 while (true) {
9973 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009974 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009975 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009976 diagID = diag::err_uncasted_call_of_unknown_any;
9977 } else {
John McCall31996342011-04-07 08:22:57 +00009978 break;
John McCall2d2e8702011-04-11 07:02:50 +00009979 }
John McCall31996342011-04-07 08:22:57 +00009980 }
9981
John McCall2d2e8702011-04-11 07:02:50 +00009982 SourceLocation loc;
9983 NamedDecl *d;
9984 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9985 loc = ref->getLocation();
9986 d = ref->getDecl();
9987 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9988 loc = mem->getMemberLoc();
9989 d = mem->getMemberDecl();
9990 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9991 diagID = diag::err_uncasted_call_of_unknown_any;
9992 loc = msg->getSelectorLoc();
9993 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +00009994 if (!d) {
9995 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
9996 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
9997 << orig->getSourceRange();
9998 return ExprError();
9999 }
John McCall2d2e8702011-04-11 07:02:50 +000010000 } else {
10001 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10002 << e->getSourceRange();
10003 return ExprError();
10004 }
10005
10006 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010007
10008 // Never recoverable.
10009 return ExprError();
10010}
10011
John McCall36e7fe32010-10-12 00:20:44 +000010012/// Check for operands with placeholder types and complain if found.
10013/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010014ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010015 // Placeholder types are always *exactly* the appropriate builtin type.
10016 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010017
John McCall31996342011-04-07 08:22:57 +000010018 // Overloaded expressions.
10019 if (type == Context.OverloadTy)
10020 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010021 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010022 QualType(),
10023 diag::err_ovl_unresolvable);
10024
John McCall0009fcc2011-04-26 20:42:42 +000010025 // Bound member functions.
10026 if (type == Context.BoundMemberTy) {
10027 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10028 << E->getSourceRange();
10029 return ExprError();
10030 }
10031
John McCall31996342011-04-07 08:22:57 +000010032 // Expressions of unknown type.
10033 if (type == Context.UnknownAnyTy)
10034 return diagnoseUnknownAnyExpr(*this, E);
10035
10036 assert(!type->isPlaceholderType());
10037 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010038}
Richard Trieu2c850c02011-04-21 21:44:26 +000010039
10040bool Sema::CheckCaseExpression(Expr *expr) {
10041 if (expr->isTypeDependent())
10042 return true;
10043 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10044 return expr->getType()->isIntegralOrEnumerationType();
10045 return false;
10046}