blob: 928b11bd0b6e21bb8415c2bd31b5f8f3f6d8a443 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000043
David Chisnall0f436562009-08-17 16:35:33 +000044
Douglas Gregor48f3bb92009-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 Jahanian8e5fc9b2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000059///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-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 Lattner5f9e2722011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-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 Gregor0a0d2b12011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-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 Smith34b41d92011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-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 Smith34b41d92011-02-20 03:19:35 +000085 }
86
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000094 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000095
Douglas Gregor0a0d2b12011-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 Kyrtzidis12189f52011-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 Gregor0a0d2b12011-03-23 00:50:03 +0000121 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson2127ecc2010-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 Gregor48f3bb92009-02-18 21:56:37 +0000129 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000130}
131
Douglas Gregor0a0d2b12011-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 Jahanian5b530052009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-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 Stump1eb44332009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000158
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000206 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000207 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-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 Jahanian236673e2009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-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 Gregorf78c4e52011-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 McCall8eb662e2010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000263}
264
Douglas Gregor4b2d3f72009-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 Lattnere7a2e912008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattnere7a2e912008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-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 Kyrtzidisc39a3d72008-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 McCall7eb0a9e2010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000297 }
John Wiegley429bb272011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidis8a285ae2011-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 Wiegley429bb272011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000325
John McCall409fa9a2010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000328
John McCall409fa9a2010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000337 }
John McCall409fa9a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000345 return Owned(E);
John McCall409fa9a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000353 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000354
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall409fa9a2010-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 Kremeneka0125d82011-02-16 01:57:07 +0000368
John Wiegley429bb272011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000371}
372
John Wiegley429bb272011-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 Gregora873dfc2010-02-03 00:27:59 +0000381}
382
383
Chris Lattnere7a2e912008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-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 Wiegley429bb272011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000425 }
Eli Friedman04e83572009-08-20 04:21:42 +0000426 }
John Wiegley429bb272011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000428}
429
Chris Lattner05faf172008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000436
John Wiegley429bb272011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000441
Chris Lattner05faf172008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
John McCall96a914a2011-08-27 22:06:17 +0000446 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-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 McCall96a914a2011-08-27 22:06:17 +0000457 if (getLangOptions().CPlusPlus && E->isGLValue() &&
458 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-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 Wiegley429bb272011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000469}
470
Chris Lattner312531a2009-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 Wiegley429bb272011-04-08 18:41:53 +0000473/// interfaces passed by value.
474ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000475 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000476 ExprResult ExprRes = CheckPlaceholderExpr(E);
477 if (ExprRes.isInvalid())
478 return ExprError();
479
480 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000481 if (ExprRes.isInvalid())
482 return ExprError();
483 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000485 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000486 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-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 Wiegley429bb272011-04-08 18:41:53 +0000490 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000491
John McCallf85e1932011-06-15 23:02:42 +0000492 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-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 McCallf85e1932011-06-15 23:02:42 +0000507
508 if (!TrivialEnough &&
509 getLangOptions().ObjCAutoRefCount &&
510 E->getType()->isObjCLifetimeType())
511 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000512
513 if (TrivialEnough) {
514 // Nothing to diagnose. This is okay.
515 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000516 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000517 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-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 McCall66c20302011-08-26 18:41:18 +0000536 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000537 E = Comma.get();
538 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000539 }
540
John Wiegley429bb272011-04-08 18:41:53 +0000541 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000542}
543
Chris Lattnere7a2e912008-07-25 21:10:04 +0000544/// UsualArithmeticConversions - Performs various conversions that are common to
545/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000546/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000547/// responsible for emitting appropriate error diagnostics.
548/// FIXME: verify the conversion rules for "complex int" are consistent with
549/// GCC.
Richard Trieu67e29332011-08-02 04:35:43 +0000550QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
551 ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000552 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000553 if (!isCompAssign) {
554 lhsExpr = UsualUnaryConversions(lhsExpr.take());
555 if (lhsExpr.isInvalid())
556 return QualType();
557 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000558
John Wiegley429bb272011-04-08 18:41:53 +0000559 rhsExpr = UsualUnaryConversions(rhsExpr.take());
560 if (rhsExpr.isInvalid())
561 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000562
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000564 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000565 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000566 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000567 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000568 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000569
570 // If both types are identical, no conversion is needed.
571 if (lhs == rhs)
572 return lhs;
573
574 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
575 // The caller can deal with this (e.g. pointer + int).
576 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
577 return lhs;
578
John McCallcf33b242010-11-13 08:17:45 +0000579 // Apply unary and bitfield promotions to the LHS's type.
580 QualType lhs_unpromoted = lhs;
581 if (lhs->isPromotableIntegerType())
582 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000583 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000584 if (!LHSBitfieldPromoteTy.isNull())
585 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000586 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000587 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000588
John McCallcf33b242010-11-13 08:17:45 +0000589 // If both types are identical, no conversion is needed.
590 if (lhs == rhs)
591 return lhs;
592
593 // At this point, we have two different arithmetic types.
594
595 // Handle complex types first (C99 6.3.1.8p1).
596 bool LHSComplexFloat = lhs->isComplexType();
597 bool RHSComplexFloat = rhs->isComplexType();
598 if (LHSComplexFloat || RHSComplexFloat) {
599 // if we have an integer operand, the result is the complex type.
600
John McCall2bb5d002010-11-13 09:02:35 +0000601 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
602 if (rhs->isIntegerType()) {
603 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000604 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieu67e29332011-08-02 04:35:43 +0000605 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
606 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000607 } else {
608 assert(rhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000609 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
610 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000611 }
John McCallcf33b242010-11-13 08:17:45 +0000612 return lhs;
613 }
614
John McCall2bb5d002010-11-13 09:02:35 +0000615 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
616 if (!isCompAssign) {
617 // int -> float -> _Complex float
618 if (lhs->isIntegerType()) {
619 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieu67e29332011-08-02 04:35:43 +0000620 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
621 CK_IntegralToFloating);
622 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
623 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000624 } else {
625 assert(lhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000626 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
627 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000628 }
629 }
John McCallcf33b242010-11-13 08:17:45 +0000630 return rhs;
631 }
632
633 // This handles complex/complex, complex/float, or float/complex.
634 // When both operands are complex, the shorter operand is converted to the
635 // type of the longer, and that is the type of the result. This corresponds
636 // to what is done when combining two real floating-point operands.
637 // The fun begins when size promotion occur across type domains.
638 // From H&S 6.3.4: When one operand is complex and the other is a real
639 // floating-point type, the less precise type is converted, within it's
640 // real or complex domain, to the precision of the other type. For example,
641 // when combining a "long double" with a "double _Complex", the
642 // "double _Complex" is promoted to "long double _Complex".
643 int order = Context.getFloatingTypeOrder(lhs, rhs);
644
645 // If both are complex, just cast to the more precise type.
646 if (LHSComplexFloat && RHSComplexFloat) {
647 if (order > 0) {
648 // _Complex float -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000649 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
650 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000651 return lhs;
652
653 } else if (order < 0) {
654 // _Complex float -> _Complex double
655 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000656 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
657 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000658 return rhs;
659 }
660 return lhs;
661 }
662
663 // If just the LHS is complex, the RHS needs to be converted,
664 // and the LHS might need to be promoted.
665 if (LHSComplexFloat) {
666 if (order > 0) { // LHS is wider
667 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000668 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000669 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000670 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
671 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000672 return lhs;
673 }
674
675 // RHS is at least as wide. Find its corresponding complex type.
676 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
677
678 // double -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000679 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
680 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000681
682 // _Complex float -> _Complex double
683 if (!isCompAssign && order < 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
685 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000686
687 return result;
688 }
689
690 // Just the RHS is complex, so the LHS needs to be converted
691 // and the RHS might need to be promoted.
692 assert(RHSComplexFloat);
693
694 if (order < 0) { // RHS is wider
695 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000696 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000697 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000698 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000699 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
700 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000701 }
John McCallcf33b242010-11-13 08:17:45 +0000702 return rhs;
703 }
704
705 // LHS is at least as wide. Find its corresponding complex type.
706 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
707
708 // double -> _Complex double
709 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000710 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
711 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000712
713 // _Complex float -> _Complex double
714 if (order > 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000715 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
716 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000717
718 return result;
719 }
720
721 // Now handle "real" floating types (i.e. float, double, long double).
722 bool LHSFloat = lhs->isRealFloatingType();
723 bool RHSFloat = rhs->isRealFloatingType();
724 if (LHSFloat || RHSFloat) {
725 // If we have two real floating types, convert the smaller operand
726 // to the bigger result.
727 if (LHSFloat && RHSFloat) {
728 int order = Context.getFloatingTypeOrder(lhs, rhs);
729 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000730 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000731 return lhs;
732 }
733
734 assert(order < 0 && "illegal float comparison");
735 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000736 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000737 return rhs;
738 }
739
740 // If we have an integer operand, the result is the real floating type.
741 if (LHSFloat) {
742 if (rhs->isIntegerType()) {
743 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000744 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000745 return lhs;
746 }
747
748 // Convert both sides to the appropriate complex float.
749 assert(rhs->isComplexIntegerType());
750 QualType result = Context.getComplexType(lhs);
751
752 // _Complex int -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000753 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
754 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000755
756 // float -> _Complex float
757 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000758 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
759 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000760
761 return result;
762 }
763
764 assert(RHSFloat);
765 if (lhs->isIntegerType()) {
766 // Convert lhs to the rhs floating point type.
767 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000768 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000769 return rhs;
770 }
771
772 // Convert both sides to the appropriate complex float.
773 assert(lhs->isComplexIntegerType());
774 QualType result = Context.getComplexType(rhs);
775
776 // _Complex int -> _Complex float
777 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000778 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
779 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000780
781 // float -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000782 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
783 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000784
785 return result;
786 }
787
788 // Handle GCC complex int extension.
789 // FIXME: if the operands are (int, _Complex long), we currently
790 // don't promote the complex. Also, signedness?
791 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
792 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
793 if (lhsComplexInt && rhsComplexInt) {
794 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
795 rhsComplexInt->getElementType());
796 assert(order && "inequal types with equal element ordering");
797 if (order > 0) {
798 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000799 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000800 return lhs;
801 }
802
803 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000805 return rhs;
806 } else if (lhsComplexInt) {
807 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000808 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000809 return lhs;
810 } else if (rhsComplexInt) {
811 // int -> _Complex int
812 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000813 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
814 CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000815 return rhs;
816 }
817
818 // Finally, we have two differing integer types.
819 // The rules for this case are in C99 6.3.1.8
820 int compare = Context.getIntegerTypeOrder(lhs, rhs);
821 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
822 rhsSigned = rhs->hasSignedIntegerRepresentation();
823 if (lhsSigned == rhsSigned) {
824 // Same signedness; use the higher-ranked type
825 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000826 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000827 return lhs;
828 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000829 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000830 return rhs;
831 } else if (compare != (lhsSigned ? 1 : -1)) {
832 // The unsigned type has greater than or equal rank to the
833 // signed type, so use the unsigned type
834 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000835 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000836 return lhs;
837 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000838 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000839 return rhs;
840 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
841 // The two types are different widths; if we are here, that
842 // means the signed type is larger than the unsigned type, so
843 // use the signed type.
844 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000845 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000846 return lhs;
847 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000848 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000849 return rhs;
850 } else {
851 // The signed type is higher-ranked than the unsigned type,
852 // but isn't actually any bigger (like unsigned int and long
853 // on most 32-bit systems). Use the unsigned type corresponding
854 // to the signed type.
855 QualType result =
856 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000857 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000858 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000859 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000860 return result;
861 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000862}
863
Chris Lattnere7a2e912008-07-25 21:10:04 +0000864//===----------------------------------------------------------------------===//
865// Semantic Analysis for various Expression Types
866//===----------------------------------------------------------------------===//
867
868
Peter Collingbournef111d932011-04-15 00:35:48 +0000869ExprResult
870Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
871 SourceLocation DefaultLoc,
872 SourceLocation RParenLoc,
873 Expr *ControllingExpr,
874 MultiTypeArg types,
875 MultiExprArg exprs) {
876 unsigned NumAssocs = types.size();
877 assert(NumAssocs == exprs.size());
878
879 ParsedType *ParsedTypes = types.release();
880 Expr **Exprs = exprs.release();
881
882 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
883 for (unsigned i = 0; i < NumAssocs; ++i) {
884 if (ParsedTypes[i])
885 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
886 else
887 Types[i] = 0;
888 }
889
890 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
891 ControllingExpr, Types, Exprs,
892 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000893 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000894 return ER;
895}
896
897ExprResult
898Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
899 SourceLocation DefaultLoc,
900 SourceLocation RParenLoc,
901 Expr *ControllingExpr,
902 TypeSourceInfo **Types,
903 Expr **Exprs,
904 unsigned NumAssocs) {
905 bool TypeErrorFound = false,
906 IsResultDependent = ControllingExpr->isTypeDependent(),
907 ContainsUnexpandedParameterPack
908 = ControllingExpr->containsUnexpandedParameterPack();
909
910 for (unsigned i = 0; i < NumAssocs; ++i) {
911 if (Exprs[i]->containsUnexpandedParameterPack())
912 ContainsUnexpandedParameterPack = true;
913
914 if (Types[i]) {
915 if (Types[i]->getType()->containsUnexpandedParameterPack())
916 ContainsUnexpandedParameterPack = true;
917
918 if (Types[i]->getType()->isDependentType()) {
919 IsResultDependent = true;
920 } else {
921 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
922 // complete object type other than a variably modified type."
923 unsigned D = 0;
924 if (Types[i]->getType()->isIncompleteType())
925 D = diag::err_assoc_type_incomplete;
926 else if (!Types[i]->getType()->isObjectType())
927 D = diag::err_assoc_type_nonobject;
928 else if (Types[i]->getType()->isVariablyModifiedType())
929 D = diag::err_assoc_type_variably_modified;
930
931 if (D != 0) {
932 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
933 << Types[i]->getTypeLoc().getSourceRange()
934 << Types[i]->getType();
935 TypeErrorFound = true;
936 }
937
938 // C1X 6.5.1.1p2 "No two generic associations in the same generic
939 // selection shall specify compatible types."
940 for (unsigned j = i+1; j < NumAssocs; ++j)
941 if (Types[j] && !Types[j]->getType()->isDependentType() &&
942 Context.typesAreCompatible(Types[i]->getType(),
943 Types[j]->getType())) {
944 Diag(Types[j]->getTypeLoc().getBeginLoc(),
945 diag::err_assoc_compatible_types)
946 << Types[j]->getTypeLoc().getSourceRange()
947 << Types[j]->getType()
948 << Types[i]->getType();
949 Diag(Types[i]->getTypeLoc().getBeginLoc(),
950 diag::note_compat_assoc)
951 << Types[i]->getTypeLoc().getSourceRange()
952 << Types[i]->getType();
953 TypeErrorFound = true;
954 }
955 }
956 }
957 }
958 if (TypeErrorFound)
959 return ExprError();
960
961 // If we determined that the generic selection is result-dependent, don't
962 // try to compute the result expression.
963 if (IsResultDependent)
964 return Owned(new (Context) GenericSelectionExpr(
965 Context, KeyLoc, ControllingExpr,
966 Types, Exprs, NumAssocs, DefaultLoc,
967 RParenLoc, ContainsUnexpandedParameterPack));
968
Chris Lattner5f9e2722011-07-23 10:55:15 +0000969 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +0000970 unsigned DefaultIndex = -1U;
971 for (unsigned i = 0; i < NumAssocs; ++i) {
972 if (!Types[i])
973 DefaultIndex = i;
974 else if (Context.typesAreCompatible(ControllingExpr->getType(),
975 Types[i]->getType()))
976 CompatIndices.push_back(i);
977 }
978
979 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
980 // type compatible with at most one of the types named in its generic
981 // association list."
982 if (CompatIndices.size() > 1) {
983 // We strip parens here because the controlling expression is typically
984 // parenthesized in macro definitions.
985 ControllingExpr = ControllingExpr->IgnoreParens();
986 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
987 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
988 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000989 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +0000990 E = CompatIndices.end(); I != E; ++I) {
991 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
992 diag::note_compat_assoc)
993 << Types[*I]->getTypeLoc().getSourceRange()
994 << Types[*I]->getType();
995 }
996 return ExprError();
997 }
998
999 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1000 // its controlling expression shall have type compatible with exactly one of
1001 // the types named in its generic association list."
1002 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1003 // We strip parens here because the controlling expression is typically
1004 // parenthesized in macro definitions.
1005 ControllingExpr = ControllingExpr->IgnoreParens();
1006 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1007 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1008 return ExprError();
1009 }
1010
1011 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1012 // type name that is compatible with the type of the controlling expression,
1013 // then the result expression of the generic selection is the expression
1014 // in that generic association. Otherwise, the result expression of the
1015 // generic selection is the expression in the default generic association."
1016 unsigned ResultIndex =
1017 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1018
1019 return Owned(new (Context) GenericSelectionExpr(
1020 Context, KeyLoc, ControllingExpr,
1021 Types, Exprs, NumAssocs, DefaultLoc,
1022 RParenLoc, ContainsUnexpandedParameterPack,
1023 ResultIndex));
1024}
1025
Steve Narofff69936d2007-09-16 03:34:24 +00001026/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001027/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1028/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1029/// multiple tokens. However, the common case is that StringToks points to one
1030/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001031///
John McCall60d7b3a2010-08-24 06:29:42 +00001032ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001033Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 assert(NumStringToks && "Must have at least one string!");
1035
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001036 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001038 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
Chris Lattner5f9e2722011-07-23 10:55:15 +00001040 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 for (unsigned i = 0; i != NumStringToks; ++i)
1042 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001043
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001044 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001045 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001046 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001047 else if (Literal.isUTF16())
1048 StrTy = Context.Char16Ty;
1049 else if (Literal.isUTF32())
1050 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001051 else if (Literal.Pascal)
1052 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001053
Douglas Gregor5cee1192011-07-27 05:40:30 +00001054 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1055 if (Literal.isWide())
1056 Kind = StringLiteral::Wide;
1057 else if (Literal.isUTF8())
1058 Kind = StringLiteral::UTF8;
1059 else if (Literal.isUTF16())
1060 Kind = StringLiteral::UTF16;
1061 else if (Literal.isUTF32())
1062 Kind = StringLiteral::UTF32;
1063
Douglas Gregor77a52232008-09-12 00:47:35 +00001064 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001065 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001066 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001067
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001068 // Get an array type for the string, according to C99 6.4.5. This includes
1069 // the nul terminator character as well as the string length for pascal
1070 // strings.
1071 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001072 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001073 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001076 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001077 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001078 &StringTokLocs[0],
1079 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001080}
1081
John McCall469a1eb2011-02-02 13:00:07 +00001082enum CaptureResult {
1083 /// No capture is required.
1084 CR_NoCapture,
1085
1086 /// A capture is required.
1087 CR_Capture,
1088
John McCall6b5a61b2011-02-07 10:33:21 +00001089 /// A by-ref capture is required.
1090 CR_CaptureByRef,
1091
John McCall469a1eb2011-02-02 13:00:07 +00001092 /// An error occurred when trying to capture the given variable.
1093 CR_Error
1094};
1095
1096/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001097///
John McCall469a1eb2011-02-02 13:00:07 +00001098/// \param var - the variable referenced
1099/// \param DC - the context which we couldn't capture through
1100static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001101diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001102 VarDecl *var, DeclContext *DC) {
1103 switch (S.ExprEvalContexts.back().Context) {
1104 case Sema::Unevaluated:
1105 // The argument will never be evaluated, so don't complain.
1106 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
John McCall469a1eb2011-02-02 13:00:07 +00001108 case Sema::PotentiallyEvaluated:
1109 case Sema::PotentiallyEvaluatedIfUsed:
1110 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001111
John McCall469a1eb2011-02-02 13:00:07 +00001112 case Sema::PotentiallyPotentiallyEvaluated:
1113 // FIXME: delay these!
1114 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116
John McCall469a1eb2011-02-02 13:00:07 +00001117 // Don't diagnose about capture if we're not actually in code right
1118 // now; in general, there are more appropriate places that will
1119 // diagnose this.
1120 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1121
John McCall4f38f412011-03-22 23:15:50 +00001122 // Certain madnesses can happen with parameter declarations, which
1123 // we want to ignore.
1124 if (isa<ParmVarDecl>(var)) {
1125 // - If the parameter still belongs to the translation unit, then
1126 // we're actually just using one parameter in the declaration of
1127 // the next. This is useful in e.g. VLAs.
1128 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1129 return CR_NoCapture;
1130
1131 // - This particular madness can happen in ill-formed default
1132 // arguments; claim it's okay and let downstream code handle it.
1133 if (S.CurContext == var->getDeclContext()->getParent())
1134 return CR_NoCapture;
1135 }
John McCall469a1eb2011-02-02 13:00:07 +00001136
1137 DeclarationName functionName;
1138 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1139 functionName = fn->getDeclName();
1140 // FIXME: variable from enclosing block that we couldn't capture from!
1141
1142 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1143 << var->getIdentifier() << functionName;
1144 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1145 << var->getIdentifier();
1146
1147 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001148}
1149
John McCall6b5a61b2011-02-07 10:33:21 +00001150/// There is a well-formed capture at a particular scope level;
1151/// propagate it through all the nested blocks.
1152static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1153 const BlockDecl::Capture &capture) {
1154 VarDecl *var = capture.getVariable();
1155
1156 // Update all the inner blocks with the capture information.
1157 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1158 i != e; ++i) {
1159 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1160 innerBlock->Captures.push_back(
1161 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1162 /*nested*/ true, capture.getCopyExpr()));
1163 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1164 }
1165
1166 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1167}
1168
1169/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001170/// given value in the current context requires a variable capture.
1171///
1172/// This also keeps the captures set in the BlockScopeInfo records
1173/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001174static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001175 ValueDecl *value) {
1176 // Only variables ever require capture.
1177 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001178 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001179
1180 // Fast path: variables from the current context never require capture.
1181 DeclContext *DC = S.CurContext;
1182 if (var->getDeclContext() == DC) return CR_NoCapture;
1183
1184 // Only variables with local storage require capture.
1185 // FIXME: What about 'const' variables in C++?
1186 if (!var->hasLocalStorage()) return CR_NoCapture;
1187
1188 // Otherwise, we need to capture.
1189
1190 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001191 do {
1192 // Only blocks (and eventually C++0x closures) can capture; other
1193 // scopes don't work.
1194 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001195 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001196
1197 BlockScopeInfo *blockScope =
1198 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1199 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1200
John McCall6b5a61b2011-02-07 10:33:21 +00001201 // Check whether we've already captured it in this block. If so,
1202 // we're done.
1203 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1204 return propagateCapture(S, functionScopesIndex,
1205 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001206
1207 functionScopesIndex--;
1208 DC = cast<BlockDecl>(DC)->getDeclContext();
1209 } while (var->getDeclContext() != DC);
1210
John McCall6b5a61b2011-02-07 10:33:21 +00001211 // Okay, we descended all the way to the block that defines the variable.
1212 // Actually try to capture it.
1213 QualType type = var->getType();
1214
1215 // Prohibit variably-modified types.
1216 if (type->isVariablyModifiedType()) {
1217 S.Diag(loc, diag::err_ref_vm_type);
1218 S.Diag(var->getLocation(), diag::note_declared_at);
1219 return CR_Error;
1220 }
1221
1222 // Prohibit arrays, even in __block variables, but not references to
1223 // them.
1224 if (type->isArrayType()) {
1225 S.Diag(loc, diag::err_ref_array_type);
1226 S.Diag(var->getLocation(), diag::note_declared_at);
1227 return CR_Error;
1228 }
1229
1230 S.MarkDeclarationReferenced(loc, var);
1231
1232 // The BlocksAttr indicates the variable is bound by-reference.
1233 bool byRef = var->hasAttr<BlocksAttr>();
1234
1235 // Build a copy expression.
1236 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001237 const RecordType *rtype;
1238 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1239 (rtype = type->getAs<RecordType>())) {
1240
1241 // The capture logic needs the destructor, so make sure we mark it.
1242 // Usually this is unnecessary because most local variables have
1243 // their destructors marked at declaration time, but parameters are
1244 // an exception because it's technically only the call site that
1245 // actually requires the destructor.
1246 if (isa<ParmVarDecl>(var))
1247 S.FinalizeVarWithDestructor(var, rtype);
1248
John McCall6b5a61b2011-02-07 10:33:21 +00001249 // According to the blocks spec, the capture of a variable from
1250 // the stack requires a const copy constructor. This is not true
1251 // of the copy/move done to move a __block variable to the heap.
1252 type.addConst();
1253
1254 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1255 ExprResult result =
1256 S.PerformCopyInitialization(
1257 InitializedEntity::InitializeBlock(var->getLocation(),
1258 type, false),
1259 loc, S.Owned(declRef));
1260
1261 // Build a full-expression copy expression if initialization
1262 // succeeded and used a non-trivial constructor. Recover from
1263 // errors by pretending that the copy isn't necessary.
1264 if (!result.isInvalid() &&
1265 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1266 result = S.MaybeCreateExprWithCleanups(result);
1267 copyExpr = result.take();
1268 }
1269 }
1270
1271 // We're currently at the declarer; go back to the closure.
1272 functionScopesIndex++;
1273 BlockScopeInfo *blockScope =
1274 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1275
1276 // Build a valid capture in this scope.
1277 blockScope->Captures.push_back(
1278 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1279 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1280
1281 // Propagate that to inner captures if necessary.
1282 return propagateCapture(S, functionScopesIndex,
1283 blockScope->Captures.back());
1284}
1285
1286static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1287 const DeclarationNameInfo &NameInfo,
1288 bool byRef) {
1289 assert(isa<VarDecl>(vd) && "capturing non-variable");
1290
1291 VarDecl *var = cast<VarDecl>(vd);
1292 assert(var->hasLocalStorage() && "capturing non-local");
1293 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1294
1295 QualType exprType = var->getType().getNonReferenceType();
1296
1297 BlockDeclRefExpr *BDRE;
1298 if (!byRef) {
1299 // The variable will be bound by copy; make it const within the
1300 // closure, but record that this was done in the expression.
1301 bool constAdded = !exprType.isConstQualified();
1302 exprType.addConst();
1303
1304 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1305 NameInfo.getLoc(), false,
1306 constAdded);
1307 } else {
1308 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1309 NameInfo.getLoc(), true);
1310 }
1311
1312 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001313}
Chris Lattner639e2d32008-10-20 05:16:36 +00001314
John McCall60d7b3a2010-08-24 06:29:42 +00001315ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001316Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001317 SourceLocation Loc,
1318 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001319 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001320 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001321}
1322
John McCall76a40212011-02-09 01:13:10 +00001323/// BuildDeclRefExpr - Build an expression that references a
1324/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001325ExprResult
John McCall76a40212011-02-09 01:13:10 +00001326Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001327 const DeclarationNameInfo &NameInfo,
1328 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001329 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
John McCall7eb0a9e2010-11-24 05:12:34 +00001331 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001332 SS? SS->getWithLocInContext(Context)
1333 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001334 D, NameInfo, Ty, VK);
1335
1336 // Just in case we're building an illegal pointer-to-member.
1337 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1338 E->setObjectKind(OK_BitField);
1339
1340 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001341}
1342
Abramo Bagnara25777432010-08-11 22:01:17 +00001343/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001344/// possibly a list of template arguments.
1345///
1346/// If this produces template arguments, it is permitted to call
1347/// DecomposeTemplateName.
1348///
1349/// This actually loses a lot of source location information for
1350/// non-standard name kinds; we should consider preserving that in
1351/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001352void
1353Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1354 TemplateArgumentListInfo &Buffer,
1355 DeclarationNameInfo &NameInfo,
1356 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001357 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1358 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1359 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1360
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001361 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001362 Id.TemplateId->getTemplateArgs(),
1363 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001364 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001365 TemplateArgsPtr.release();
1366
John McCall2b5289b2010-08-23 07:28:44 +00001367 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001368 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001369 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001370 TemplateArgs = &Buffer;
1371 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001372 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001373 TemplateArgs = 0;
1374 }
1375}
1376
John McCall578b69b2009-12-16 08:11:27 +00001377/// Diagnose an empty lookup.
1378///
1379/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001380bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001381 CorrectTypoContext CTC,
1382 TemplateArgumentListInfo *ExplicitTemplateArgs,
1383 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001384 DeclarationName Name = R.getLookupName();
1385
John McCall578b69b2009-12-16 08:11:27 +00001386 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001387 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001388 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1389 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001390 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001391 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001392 diagnostic_suggest = diag::err_undeclared_use_suggest;
1393 }
John McCall578b69b2009-12-16 08:11:27 +00001394
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001395 // If the original lookup was an unqualified lookup, fake an
1396 // unqualified lookup. This is useful when (for example) the
1397 // original lookup would not have found something because it was a
1398 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001399 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001400 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001401 if (isa<CXXRecordDecl>(DC)) {
1402 LookupQualifiedName(R, DC);
1403
1404 if (!R.empty()) {
1405 // Don't give errors about ambiguities in this lookup.
1406 R.suppressDiagnostics();
1407
1408 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1409 bool isInstance = CurMethod &&
1410 CurMethod->isInstance() &&
1411 DC == CurMethod->getParent();
1412
1413 // Give a code modification hint to insert 'this->'.
1414 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1415 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001416 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001417 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1418 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001419 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001420 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001421 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001422 Diag(R.getNameLoc(), diagnostic) << Name
1423 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1424 QualType DepThisType = DepMethod->getThisType(Context);
1425 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1426 R.getNameLoc(), DepThisType, false);
1427 TemplateArgumentListInfo TList;
1428 if (ULE->hasExplicitTemplateArgs())
1429 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001430
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001431 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001432 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001433 CXXDependentScopeMemberExpr *DepExpr =
1434 CXXDependentScopeMemberExpr::Create(
1435 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001436 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001437 R.getLookupNameInfo(), &TList);
1438 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001439 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001440 // FIXME: we should be able to handle this case too. It is correct
1441 // to add this-> here. This is a workaround for PR7947.
1442 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001443 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001444 } else {
John McCall578b69b2009-12-16 08:11:27 +00001445 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001446 }
John McCall578b69b2009-12-16 08:11:27 +00001447
1448 // Do we really want to note all of these?
1449 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1450 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1451
1452 // Tell the callee to try to recover.
1453 return false;
1454 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001455
1456 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001457 }
1458 }
1459
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001460 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001461 TypoCorrection Corrected;
1462 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1463 S, &SS, NULL, false, CTC))) {
1464 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1465 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1466 R.setLookupName(Corrected.getCorrection());
1467
Hans Wennborg701d1e72011-07-12 08:45:31 +00001468 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001469 if (Corrected.isOverloaded()) {
1470 OverloadCandidateSet OCS(R.getNameLoc());
1471 OverloadCandidateSet::iterator Best;
1472 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1473 CDEnd = Corrected.end();
1474 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001475 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001476 dyn_cast<FunctionTemplateDecl>(*CD))
1477 AddTemplateOverloadCandidate(
1478 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1479 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001480 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1481 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1482 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1483 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001484 }
1485 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1486 case OR_Success:
1487 ND = Best->Function;
1488 break;
1489 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001490 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001491 }
1492 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001493 R.addDecl(ND);
1494 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001495 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001496 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1497 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001498 else
1499 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001500 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001501 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001502 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1503 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001504 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001505 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001506
1507 // Tell the callee to try to recover.
1508 return false;
1509 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001510
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001511 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001512 // FIXME: If we ended up with a typo for a type name or
1513 // Objective-C class name, we're in trouble because the parser
1514 // is in the wrong place to recover. Suggest the typo
1515 // correction, but don't make it a fix-it since we're not going
1516 // to recover well anyway.
1517 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001518 Diag(R.getNameLoc(), diagnostic_suggest)
1519 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001520 else
1521 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001522 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001523 << SS.getRange();
1524
1525 // Don't try to recover; it won't work.
1526 return true;
1527 }
1528 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001529 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001530 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001531 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001532 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001533 else
Douglas Gregord203a162010-01-01 00:15:04 +00001534 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001535 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001536 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001537 return true;
1538 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001539 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001540 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001541
1542 // Emit a special diagnostic for failed member lookups.
1543 // FIXME: computing the declaration context might fail here (?)
1544 if (!SS.isEmpty()) {
1545 Diag(R.getNameLoc(), diag::err_no_member)
1546 << Name << computeDeclContext(SS, false)
1547 << SS.getRange();
1548 return true;
1549 }
1550
John McCall578b69b2009-12-16 08:11:27 +00001551 // Give up, we can't recover.
1552 Diag(R.getNameLoc(), diagnostic) << Name;
1553 return true;
1554}
1555
Douglas Gregorca45da02010-11-02 20:36:02 +00001556ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1557 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001558 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1559 if (!IDecl)
1560 return 0;
1561 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1562 if (!ClassImpDecl)
1563 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001564 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001565 if (!property)
1566 return 0;
1567 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001568 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1569 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001570 return 0;
1571 return property;
1572}
1573
Douglas Gregorca45da02010-11-02 20:36:02 +00001574bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1575 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1576 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1577 if (!IDecl)
1578 return false;
1579 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1580 if (!ClassImpDecl)
1581 return false;
1582 if (ObjCPropertyImplDecl *PIDecl
1583 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1584 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1585 PIDecl->getPropertyIvarDecl())
1586 return false;
1587
1588 return true;
1589}
1590
Douglas Gregor312eadb2011-04-24 05:37:28 +00001591ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1592 IdentifierInfo *II,
1593 SourceLocation NameLoc) {
1594 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001595 bool LookForIvars;
1596 if (Lookup.empty())
1597 LookForIvars = true;
1598 else if (CurMeth->isClassMethod())
1599 LookForIvars = false;
1600 else
1601 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001602 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1603 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001604 if (!LookForIvars)
1605 return 0;
1606
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001607 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1608 if (!IDecl)
1609 return 0;
1610 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001611 if (!ClassImpDecl)
1612 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001613 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001614 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001615 if (!property)
1616 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001617 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001618 DynamicImplSeen =
1619 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001620 // property implementation has a designated ivar. No need to assume a new
1621 // one.
1622 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1623 return 0;
1624 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001625 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001626 QualType PropType = Context.getCanonicalType(property->getType());
1627 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001628 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001629 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001630 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001631 (Expr *)0, true);
1632 ClassImpDecl->addDecl(Ivar);
1633 IDecl->makeDeclVisibleInContext(Ivar, false);
1634 property->setPropertyIvarDecl(Ivar);
1635 return Ivar;
1636 }
1637 return 0;
1638}
1639
John McCall60d7b3a2010-08-24 06:29:42 +00001640ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001641 CXXScopeSpec &SS,
1642 UnqualifiedId &Id,
1643 bool HasTrailingLParen,
1644 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001645 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1646 "cannot be direct & operand and have a trailing lparen");
1647
1648 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001649 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001650
John McCall129e2df2009-11-30 22:42:35 +00001651 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001652
1653 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001654 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001655 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001656 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001657
Abramo Bagnara25777432010-08-11 22:01:17 +00001658 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001659 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001660 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001661
John McCallf7a1a742009-11-24 19:00:30 +00001662 // C++ [temp.dep.expr]p3:
1663 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001664 // -- an identifier that was declared with a dependent type,
1665 // (note: handled after lookup)
1666 // -- a template-id that is dependent,
1667 // (note: handled in BuildTemplateIdExpr)
1668 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001669 // -- a nested-name-specifier that contains a class-name that
1670 // names a dependent type.
1671 // Determine whether this is a member of an unknown specialization;
1672 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001673 bool DependentID = false;
1674 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1675 Name.getCXXNameType()->isDependentType()) {
1676 DependentID = true;
1677 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001678 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001679 if (RequireCompleteDeclContext(SS, DC))
1680 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001681 } else {
1682 DependentID = true;
1683 }
1684 }
1685
Chris Lattner337e5502011-02-18 01:27:55 +00001686 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001687 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001688 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001689
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001690 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001691 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001692 LookupResult R(*this, NameInfo,
1693 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1694 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001695 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001696 // Lookup the template name again to correctly establish the context in
1697 // which it was found. This is really unfortunate as we already did the
1698 // lookup to determine that it was a template name in the first place. If
1699 // this becomes a performance hit, we can work harder to preserve those
1700 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001701 bool MemberOfUnknownSpecialization;
1702 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1703 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001704
1705 if (MemberOfUnknownSpecialization ||
1706 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1707 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1708 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001709 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001710 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001711 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001713 // If the result might be in a dependent base class, this is a dependent
1714 // id-expression.
1715 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1716 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1717 TemplateArgs);
1718
John McCallf7a1a742009-11-24 19:00:30 +00001719 // If this reference is in an Objective-C method, then we need to do
1720 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001721 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001722 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001723 if (E.isInvalid())
1724 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Chris Lattner337e5502011-02-18 01:27:55 +00001726 if (Expr *Ex = E.takeAs<Expr>())
1727 return Owned(Ex);
1728
1729 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001730 if (getLangOptions().ObjCDefaultSynthProperties &&
1731 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001732 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001733 if (const ObjCPropertyDecl *Property =
1734 canSynthesizeProvisionalIvar(II)) {
1735 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1736 Diag(Property->getLocation(), diag::note_property_declare);
1737 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001738 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1739 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001740 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001741 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001742 // for further use, this must be set to false if in class method.
1743 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001744 }
Chris Lattner8a934232008-03-31 00:36:02 +00001745 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001746
John McCallf7a1a742009-11-24 19:00:30 +00001747 if (R.isAmbiguous())
1748 return ExprError();
1749
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001750 // Determine whether this name might be a candidate for
1751 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001752 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001753
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001756 // in C90, extension in C99, forbidden in C++).
1757 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1758 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1759 if (D) R.addDecl(D);
1760 }
1761
1762 // If this name wasn't predeclared and if this is not a function
1763 // call, diagnose the problem.
1764 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001765 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001766 return ExprError();
1767
1768 assert(!R.empty() &&
1769 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001770
1771 // If we found an Objective-C instance variable, let
1772 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001773 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001774 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1775 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001776 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001777 assert(E.isInvalid() || E.get());
1778 return move(E);
1779 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 }
1781 }
Mike Stump1eb44332009-09-09 15:08:12 +00001782
John McCallf7a1a742009-11-24 19:00:30 +00001783 // This is guaranteed from this point on.
1784 assert(!R.empty() || ADL);
1785
John McCallaa81e162009-12-01 22:10:20 +00001786 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001787 // C++ [class.mfct.non-static]p3:
1788 // When an id-expression that is not part of a class member access
1789 // syntax and not used to form a pointer to member is used in the
1790 // body of a non-static member function of class X, if name lookup
1791 // resolves the name in the id-expression to a non-static non-type
1792 // member of some class C, the id-expression is transformed into a
1793 // class member access expression using (*this) as the
1794 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001795 //
1796 // But we don't actually need to do this for '&' operands if R
1797 // resolved to a function or overloaded function set, because the
1798 // expression is ill-formed if it actually works out to be a
1799 // non-static member function:
1800 //
1801 // C++ [expr.ref]p4:
1802 // Otherwise, if E1.E2 refers to a non-static member function. . .
1803 // [t]he expression can be used only as the left-hand operand of a
1804 // member function call.
1805 //
1806 // There are other safeguards against such uses, but it's important
1807 // to get this right here so that we don't end up making a
1808 // spuriously dependent expression if we're inside a dependent
1809 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001810 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001811 bool MightBeImplicitMember;
1812 if (!isAddressOfOperand)
1813 MightBeImplicitMember = true;
1814 else if (!SS.isEmpty())
1815 MightBeImplicitMember = false;
1816 else if (R.isOverloadedResult())
1817 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001818 else if (R.isUnresolvableResult())
1819 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001820 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001821 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1822 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001823
1824 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001825 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001826 }
1827
John McCallf7a1a742009-11-24 19:00:30 +00001828 if (TemplateArgs)
1829 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001830
John McCallf7a1a742009-11-24 19:00:30 +00001831 return BuildDeclarationNameExpr(SS, R, ADL);
1832}
1833
John McCall129e2df2009-11-30 22:42:35 +00001834/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1835/// declaration name, generally during template instantiation.
1836/// There's a large number of things which don't need to be done along
1837/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001838ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001839Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001840 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001841 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001842 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001843 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001844
John McCall77bb1aa2010-05-01 00:40:08 +00001845 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001846 return ExprError();
1847
Abramo Bagnara25777432010-08-11 22:01:17 +00001848 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001849 LookupQualifiedName(R, DC);
1850
1851 if (R.isAmbiguous())
1852 return ExprError();
1853
1854 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001855 Diag(NameInfo.getLoc(), diag::err_no_member)
1856 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001857 return ExprError();
1858 }
1859
1860 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1861}
1862
1863/// LookupInObjCMethod - The parser has read a name in, and Sema has
1864/// detected that we're currently inside an ObjC method. Perform some
1865/// additional lookup.
1866///
1867/// Ideally, most of this would be done by lookup, but there's
1868/// actually quite a lot of extra work involved.
1869///
1870/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001871ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001872Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001873 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001874 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001875 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001876
John McCallf7a1a742009-11-24 19:00:30 +00001877 // There are two cases to handle here. 1) scoped lookup could have failed,
1878 // in which case we should look for an ivar. 2) scoped lookup could have
1879 // found a decl, but that decl is outside the current instance method (i.e.
1880 // a global variable). In these two cases, we do a lookup for an ivar with
1881 // this name, if the lookup sucedes, we replace it our current decl.
1882
1883 // If we're in a class method, we don't normally want to look for
1884 // ivars. But if we don't find anything else, and there's an
1885 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001886 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001887
1888 bool LookForIvars;
1889 if (Lookup.empty())
1890 LookForIvars = true;
1891 else if (IsClassMethod)
1892 LookForIvars = false;
1893 else
1894 LookForIvars = (Lookup.isSingleResult() &&
1895 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001896 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001897 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001898 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001899 ObjCInterfaceDecl *ClassDeclared;
1900 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1901 // Diagnose using an ivar in a class method.
1902 if (IsClassMethod)
1903 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1904 << IV->getDeclName());
1905
1906 // If we're referencing an invalid decl, just return this as a silent
1907 // error node. The error diagnostic was already emitted on the decl.
1908 if (IV->isInvalidDecl())
1909 return ExprError();
1910
1911 // Check if referencing a field with __attribute__((deprecated)).
1912 if (DiagnoseUseOfDecl(IV, Loc))
1913 return ExprError();
1914
1915 // Diagnose the use of an ivar outside of the declaring class.
1916 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1917 ClassDeclared != IFace)
1918 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1919
1920 // FIXME: This should use a new expr for a direct reference, don't
1921 // turn this into Self->ivar, just return a BareIVarExpr or something.
1922 IdentifierInfo &II = Context.Idents.get("self");
1923 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001924 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001925 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001926 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001927 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001928 SelfName, false, false);
1929 if (SelfExpr.isInvalid())
1930 return ExprError();
1931
John Wiegley429bb272011-04-08 18:41:53 +00001932 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1933 if (SelfExpr.isInvalid())
1934 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001935
John McCallf7a1a742009-11-24 19:00:30 +00001936 MarkDeclarationReferenced(Loc, IV);
1937 return Owned(new (Context)
1938 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001939 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001940 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001941 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001942 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001943 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001944 ObjCInterfaceDecl *ClassDeclared;
1945 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1946 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1947 IFace == ClassDeclared)
1948 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1949 }
1950 }
1951
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001952 if (Lookup.empty() && II && AllowBuiltinCreation) {
1953 // FIXME. Consolidate this with similar code in LookupName.
1954 if (unsigned BuiltinID = II->getBuiltinID()) {
1955 if (!(getLangOptions().CPlusPlus &&
1956 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1957 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1958 S, Lookup.isForRedeclaration(),
1959 Lookup.getNameLoc());
1960 if (D) Lookup.addDecl(D);
1961 }
1962 }
1963 }
John McCallf7a1a742009-11-24 19:00:30 +00001964 // Sentinel value saying that we didn't do anything special.
1965 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001966}
John McCallba135432009-11-21 08:51:07 +00001967
John McCall6bb80172010-03-30 21:47:33 +00001968/// \brief Cast a base object to a member's actual type.
1969///
1970/// Logically this happens in three phases:
1971///
1972/// * First we cast from the base type to the naming class.
1973/// The naming class is the class into which we were looking
1974/// when we found the member; it's the qualifier type if a
1975/// qualifier was provided, and otherwise it's the base type.
1976///
1977/// * Next we cast from the naming class to the declaring class.
1978/// If the member we found was brought into a class's scope by
1979/// a using declaration, this is that class; otherwise it's
1980/// the class declaring the member.
1981///
1982/// * Finally we cast from the declaring class to the "true"
1983/// declaring class of the member. This conversion does not
1984/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001985ExprResult
1986Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001987 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001988 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001989 NamedDecl *Member) {
1990 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1991 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001992 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001993
Douglas Gregor5fccd362010-03-03 23:55:11 +00001994 QualType DestRecordType;
1995 QualType DestType;
1996 QualType FromRecordType;
1997 QualType FromType = From->getType();
1998 bool PointerConversions = false;
1999 if (isa<FieldDecl>(Member)) {
2000 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002001
Douglas Gregor5fccd362010-03-03 23:55:11 +00002002 if (FromType->getAs<PointerType>()) {
2003 DestType = Context.getPointerType(DestRecordType);
2004 FromRecordType = FromType->getPointeeType();
2005 PointerConversions = true;
2006 } else {
2007 DestType = DestRecordType;
2008 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002009 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002010 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2011 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002012 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002013
Douglas Gregor5fccd362010-03-03 23:55:11 +00002014 DestType = Method->getThisType(Context);
2015 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002016
Douglas Gregor5fccd362010-03-03 23:55:11 +00002017 if (FromType->getAs<PointerType>()) {
2018 FromRecordType = FromType->getPointeeType();
2019 PointerConversions = true;
2020 } else {
2021 FromRecordType = FromType;
2022 DestType = DestRecordType;
2023 }
2024 } else {
2025 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002026 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002027 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002028
Douglas Gregor5fccd362010-03-03 23:55:11 +00002029 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002030 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002031
Douglas Gregor5fccd362010-03-03 23:55:11 +00002032 // If the unqualified types are the same, no conversion is necessary.
2033 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002034 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002035
John McCall6bb80172010-03-30 21:47:33 +00002036 SourceRange FromRange = From->getSourceRange();
2037 SourceLocation FromLoc = FromRange.getBegin();
2038
John McCall5baba9d2010-08-25 10:28:54 +00002039 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002040
Douglas Gregor5fccd362010-03-03 23:55:11 +00002041 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002042 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002043 // class name.
2044 //
2045 // If the member was a qualified name and the qualified referred to a
2046 // specific base subobject type, we'll cast to that intermediate type
2047 // first and then to the object in which the member is declared. That allows
2048 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2049 //
2050 // class Base { public: int x; };
2051 // class Derived1 : public Base { };
2052 // class Derived2 : public Base { };
2053 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2054 //
2055 // void VeryDerived::f() {
2056 // x = 17; // error: ambiguous base subobjects
2057 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2058 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002060 QualType QType = QualType(Qualifier->getAsType(), 0);
2061 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2062 assert(QType->isRecordType() && "lookup done with non-record type");
2063
2064 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2065
2066 // In C++98, the qualifier type doesn't actually have to be a base
2067 // type of the object type, in which case we just ignore it.
2068 // Otherwise build the appropriate casts.
2069 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002070 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002071 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002072 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002073 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002074
Douglas Gregor5fccd362010-03-03 23:55:11 +00002075 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002076 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002077 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2078 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002079
2080 FromType = QType;
2081 FromRecordType = QRecordType;
2082
2083 // If the qualifier type was the same as the destination type,
2084 // we're done.
2085 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002086 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002087 }
2088 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002089
John McCall6bb80172010-03-30 21:47:33 +00002090 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002091
John McCall6bb80172010-03-30 21:47:33 +00002092 // If we actually found the member through a using declaration, cast
2093 // down to the using declaration's type.
2094 //
2095 // Pointer equality is fine here because only one declaration of a
2096 // class ever has member declarations.
2097 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2098 assert(isa<UsingShadowDecl>(FoundDecl));
2099 QualType URecordType = Context.getTypeDeclType(
2100 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2101
2102 // We only need to do this if the naming-class to declaring-class
2103 // conversion is non-trivial.
2104 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2105 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002107 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002108 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002109 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002110
John McCall6bb80172010-03-30 21:47:33 +00002111 QualType UType = URecordType;
2112 if (PointerConversions)
2113 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002114 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2115 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002116 FromType = UType;
2117 FromRecordType = URecordType;
2118 }
2119
2120 // We don't do access control for the conversion from the
2121 // declaring class to the true declaring class.
2122 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002123 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002124
John McCallf871d0c2010-08-07 06:22:56 +00002125 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002126 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2127 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002128 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002129 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002130
John Wiegley429bb272011-04-08 18:41:53 +00002131 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2132 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002133}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002134
John McCallf7a1a742009-11-24 19:00:30 +00002135bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002136 const LookupResult &R,
2137 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002138 // Only when used directly as the postfix-expression of a call.
2139 if (!HasTrailingLParen)
2140 return false;
2141
2142 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002143 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002144 return false;
2145
2146 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002147 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002148 return false;
2149
2150 // Turn off ADL when we find certain kinds of declarations during
2151 // normal lookup:
2152 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2153 NamedDecl *D = *I;
2154
2155 // C++0x [basic.lookup.argdep]p3:
2156 // -- a declaration of a class member
2157 // Since using decls preserve this property, we check this on the
2158 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002159 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002160 return false;
2161
2162 // C++0x [basic.lookup.argdep]p3:
2163 // -- a block-scope function declaration that is not a
2164 // using-declaration
2165 // NOTE: we also trigger this for function templates (in fact, we
2166 // don't check the decl type at all, since all other decl types
2167 // turn off ADL anyway).
2168 if (isa<UsingShadowDecl>(D))
2169 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2170 else if (D->getDeclContext()->isFunctionOrMethod())
2171 return false;
2172
2173 // C++0x [basic.lookup.argdep]p3:
2174 // -- a declaration that is neither a function or a function
2175 // template
2176 // And also for builtin functions.
2177 if (isa<FunctionDecl>(D)) {
2178 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2179
2180 // But also builtin functions.
2181 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2182 return false;
2183 } else if (!isa<FunctionTemplateDecl>(D))
2184 return false;
2185 }
2186
2187 return true;
2188}
2189
2190
John McCallba135432009-11-21 08:51:07 +00002191/// Diagnoses obvious problems with the use of the given declaration
2192/// as an expression. This is only actually called for lookups that
2193/// were not overloaded, and it doesn't promise that the declaration
2194/// will in fact be used.
2195static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002196 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002197 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2198 return true;
2199 }
2200
2201 if (isa<ObjCInterfaceDecl>(D)) {
2202 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2203 return true;
2204 }
2205
2206 if (isa<NamespaceDecl>(D)) {
2207 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2208 return true;
2209 }
2210
2211 return false;
2212}
2213
John McCall60d7b3a2010-08-24 06:29:42 +00002214ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002215Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002216 LookupResult &R,
2217 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002218 // If this is a single, fully-resolved result and we don't need ADL,
2219 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002220 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002221 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2222 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002223
2224 // We only need to check the declaration if there's exactly one
2225 // result, because in the overloaded case the results can only be
2226 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002227 if (R.isSingleResult() &&
2228 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002229 return ExprError();
2230
John McCallc373d482010-01-27 01:50:18 +00002231 // Otherwise, just build an unresolved lookup expression. Suppress
2232 // any lookup-related diagnostics; we'll hash these out later, when
2233 // we've picked a target.
2234 R.suppressDiagnostics();
2235
John McCallba135432009-11-21 08:51:07 +00002236 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002237 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002238 SS.getWithLocInContext(Context),
2239 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002240 NeedsADL, R.isOverloadedResult(),
2241 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002242
2243 return Owned(ULE);
2244}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002245
John McCallba135432009-11-21 08:51:07 +00002246/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002247ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002248Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002249 const DeclarationNameInfo &NameInfo,
2250 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002251 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002252 assert(!isa<FunctionTemplateDecl>(D) &&
2253 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002254
Abramo Bagnara25777432010-08-11 22:01:17 +00002255 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002256 if (CheckDeclInExpr(*this, Loc, D))
2257 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002258
Douglas Gregor9af2f522009-12-01 16:58:18 +00002259 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2260 // Specifically diagnose references to class templates that are missing
2261 // a template argument list.
2262 Diag(Loc, diag::err_template_decl_ref)
2263 << Template << SS.getRange();
2264 Diag(Template->getLocation(), diag::note_template_decl_here);
2265 return ExprError();
2266 }
2267
2268 // Make sure that we're referring to a value.
2269 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2270 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002271 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002272 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002273 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002274 return ExprError();
2275 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002276
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002277 // Check whether this declaration can be used. Note that we suppress
2278 // this check when we're going to perform argument-dependent lookup
2279 // on this function name, because this might not be the function
2280 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002281 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002282 return ExprError();
2283
Steve Naroffdd972f22008-09-05 22:11:13 +00002284 // Only create DeclRefExpr's for valid Decl's.
2285 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002286 return ExprError();
2287
John McCall5808ce42011-02-03 08:15:49 +00002288 // Handle members of anonymous structs and unions. If we got here,
2289 // and the reference is to a class member indirect field, then this
2290 // must be the subject of a pointer-to-member expression.
2291 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2292 if (!indirectField->isCXXClassMember())
2293 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2294 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002295
Chris Lattner639e2d32008-10-20 05:16:36 +00002296 // If the identifier reference is inside a block, and it refers to a value
2297 // that is outside the block, create a BlockDeclRefExpr instead of a
2298 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2299 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002300 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002301 // We do not do this for things like enum constants, global variables, etc,
2302 // as they do not get snapshotted.
2303 //
John McCall6b5a61b2011-02-07 10:33:21 +00002304 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002305 case CR_Error:
2306 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002307
John McCall469a1eb2011-02-02 13:00:07 +00002308 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002309 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2310 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2311
2312 case CR_CaptureByRef:
2313 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2314 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002315
2316 case CR_NoCapture: {
2317 // If this reference is not in a block or if the referenced
2318 // variable is within the block, create a normal DeclRefExpr.
2319
2320 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002321 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002322
2323 switch (D->getKind()) {
2324 // Ignore all the non-ValueDecl kinds.
2325#define ABSTRACT_DECL(kind)
2326#define VALUE(type, base)
2327#define DECL(type, base) \
2328 case Decl::type:
2329#include "clang/AST/DeclNodes.inc"
2330 llvm_unreachable("invalid value decl kind");
2331 return ExprError();
2332
2333 // These shouldn't make it here.
2334 case Decl::ObjCAtDefsField:
2335 case Decl::ObjCIvar:
2336 llvm_unreachable("forming non-member reference to ivar?");
2337 return ExprError();
2338
2339 // Enum constants are always r-values and never references.
2340 // Unresolved using declarations are dependent.
2341 case Decl::EnumConstant:
2342 case Decl::UnresolvedUsingValue:
2343 valueKind = VK_RValue;
2344 break;
2345
2346 // Fields and indirect fields that got here must be for
2347 // pointer-to-member expressions; we just call them l-values for
2348 // internal consistency, because this subexpression doesn't really
2349 // exist in the high-level semantics.
2350 case Decl::Field:
2351 case Decl::IndirectField:
2352 assert(getLangOptions().CPlusPlus &&
2353 "building reference to field in C?");
2354
2355 // These can't have reference type in well-formed programs, but
2356 // for internal consistency we do this anyway.
2357 type = type.getNonReferenceType();
2358 valueKind = VK_LValue;
2359 break;
2360
2361 // Non-type template parameters are either l-values or r-values
2362 // depending on the type.
2363 case Decl::NonTypeTemplateParm: {
2364 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2365 type = reftype->getPointeeType();
2366 valueKind = VK_LValue; // even if the parameter is an r-value reference
2367 break;
2368 }
2369
2370 // For non-references, we need to strip qualifiers just in case
2371 // the template parameter was declared as 'const int' or whatever.
2372 valueKind = VK_RValue;
2373 type = type.getUnqualifiedType();
2374 break;
2375 }
2376
2377 case Decl::Var:
2378 // In C, "extern void blah;" is valid and is an r-value.
2379 if (!getLangOptions().CPlusPlus &&
2380 !type.hasQualifiers() &&
2381 type->isVoidType()) {
2382 valueKind = VK_RValue;
2383 break;
2384 }
2385 // fallthrough
2386
2387 case Decl::ImplicitParam:
2388 case Decl::ParmVar:
2389 // These are always l-values.
2390 valueKind = VK_LValue;
2391 type = type.getNonReferenceType();
2392 break;
2393
2394 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002395 const FunctionType *fty = type->castAs<FunctionType>();
2396
2397 // If we're referring to a function with an __unknown_anytype
2398 // result type, make the entire expression __unknown_anytype.
2399 if (fty->getResultType() == Context.UnknownAnyTy) {
2400 type = Context.UnknownAnyTy;
2401 valueKind = VK_RValue;
2402 break;
2403 }
2404
John McCall76a40212011-02-09 01:13:10 +00002405 // Functions are l-values in C++.
2406 if (getLangOptions().CPlusPlus) {
2407 valueKind = VK_LValue;
2408 break;
2409 }
2410
2411 // C99 DR 316 says that, if a function type comes from a
2412 // function definition (without a prototype), that type is only
2413 // used for checking compatibility. Therefore, when referencing
2414 // the function, we pretend that we don't have the full function
2415 // type.
John McCall755d8492011-04-12 00:42:48 +00002416 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2417 isa<FunctionProtoType>(fty))
2418 type = Context.getFunctionNoProtoType(fty->getResultType(),
2419 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002420
2421 // Functions are r-values in C.
2422 valueKind = VK_RValue;
2423 break;
2424 }
2425
2426 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002427 // If we're referring to a method with an __unknown_anytype
2428 // result type, make the entire expression __unknown_anytype.
2429 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002430 if (const FunctionProtoType *proto
2431 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002432 if (proto->getResultType() == Context.UnknownAnyTy) {
2433 type = Context.UnknownAnyTy;
2434 valueKind = VK_RValue;
2435 break;
2436 }
2437
John McCall76a40212011-02-09 01:13:10 +00002438 // C++ methods are l-values if static, r-values if non-static.
2439 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2440 valueKind = VK_LValue;
2441 break;
2442 }
2443 // fallthrough
2444
2445 case Decl::CXXConversion:
2446 case Decl::CXXDestructor:
2447 case Decl::CXXConstructor:
2448 valueKind = VK_RValue;
2449 break;
2450 }
2451
2452 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2453 }
2454
John McCall469a1eb2011-02-02 13:00:07 +00002455 }
John McCallf89e55a2010-11-18 06:31:45 +00002456
John McCall6b5a61b2011-02-07 10:33:21 +00002457 llvm_unreachable("unknown capture result");
2458 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002459}
2460
John McCall755d8492011-04-12 00:42:48 +00002461ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002462 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002463
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002465 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002466 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2467 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2468 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002470
Chris Lattnerfa28b302008-01-12 08:14:25 +00002471 // Pre-defined identifiers are of type char[x], where x is the length of the
2472 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Anders Carlsson3a082d82009-09-08 18:24:21 +00002474 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002475 if (!currentDecl && getCurBlock())
2476 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002477 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002478 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002479 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002480 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002481
Anders Carlsson773f3972009-09-11 01:22:35 +00002482 QualType ResTy;
2483 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2484 ResTy = Context.DependentTy;
2485 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002486 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002487
Anders Carlsson773f3972009-09-11 01:22:35 +00002488 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002489 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002490 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2491 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002492 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002493}
2494
John McCall60d7b3a2010-08-24 06:29:42 +00002495ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002497 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002498 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002499 if (Invalid)
2500 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002501
Benjamin Kramerddeea562010-02-27 13:44:12 +00002502 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002503 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002505 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002506
Chris Lattnere8337df2009-12-30 21:19:39 +00002507 QualType Ty;
2508 if (!getLangOptions().CPlusPlus)
2509 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2510 else if (Literal.isWide())
2511 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002512 else if (Literal.isUTF16())
2513 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2514 else if (Literal.isUTF32())
2515 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002516 else if (Literal.isMultiChar())
2517 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002518 else
2519 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002520
Douglas Gregor5cee1192011-07-27 05:40:30 +00002521 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2522 if (Literal.isWide())
2523 Kind = CharacterLiteral::Wide;
2524 else if (Literal.isUTF16())
2525 Kind = CharacterLiteral::UTF16;
2526 else if (Literal.isUTF32())
2527 Kind = CharacterLiteral::UTF32;
2528
2529 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2530 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002531}
2532
John McCall60d7b3a2010-08-24 06:29:42 +00002533ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002534 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2536 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002537 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002538 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002539 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002540 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 }
Ted Kremenek28396602009-01-13 23:19:12 +00002542
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002544 // Add padding so that NumericLiteralParser can overread by one character.
2545 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002547
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002549 bool Invalid = false;
2550 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2551 if (Invalid)
2552 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002553
Mike Stump1eb44332009-09-09 15:08:12 +00002554 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 Tok.getLocation(), PP);
2556 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002557 return ExprError();
2558
Chris Lattner5d661452007-08-26 03:42:43 +00002559 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002560
Chris Lattner5d661452007-08-26 03:42:43 +00002561 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002562 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002563 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002564 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002565 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002566 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002567 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002568 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002569
2570 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2571
John McCall94c939d2009-12-24 09:08:04 +00002572 using llvm::APFloat;
2573 APFloat Val(Format);
2574
2575 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002576
2577 // Overflow is always an error, but underflow is only an error if
2578 // we underflowed to zero (APFloat reports denormals as underflow).
2579 if ((result & APFloat::opOverflow) ||
2580 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002581 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002582 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002583 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002584 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002585 APFloat::getLargest(Format).toString(buffer);
2586 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002587 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002588 APFloat::getSmallest(Format).toString(buffer);
2589 }
2590
2591 Diag(Tok.getLocation(), diagnostic)
2592 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002593 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002594 }
2595
2596 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002597 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002598
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002599 if (Ty == Context.DoubleTy) {
2600 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002601 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002602 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2603 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002604 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002605 }
2606 }
Chris Lattner5d661452007-08-26 03:42:43 +00002607 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002608 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002609 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002610 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002611
Neil Boothb9449512007-08-29 22:00:19 +00002612 // long long is a C99 feature.
2613 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002614 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002615 Diag(Tok.getLocation(), diag::ext_longlong);
2616
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002618 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 if (Literal.GetIntegerValue(ResultVal)) {
2621 // If this value didn't fit into uintmax_t, warn and force to ull.
2622 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002623 Ty = Context.UnsignedLongLongTy;
2624 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002625 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 } else {
2627 // If this value fits into a ULL, try to figure out what else it fits into
2628 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2631 // be an unsigned int.
2632 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2633
2634 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002635 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002636 if (!Literal.isLong && !Literal.isLongLong) {
2637 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002638 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002639
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 // Does it fit in a unsigned int?
2641 if (ResultVal.isIntN(IntSize)) {
2642 // Does it fit in a signed int?
2643 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002644 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002646 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002647 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002650
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002652 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002653 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002654
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 // Does it fit in a unsigned long?
2656 if (ResultVal.isIntN(LongSize)) {
2657 // Does it fit in a signed long?
2658 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002659 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002661 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002662 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002664 }
2665
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002667 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002668 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 // Does it fit in a unsigned long long?
2671 if (ResultVal.isIntN(LongLongSize)) {
2672 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002673 // To be compatible with MSVC, hex integer literals ending with the
2674 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002675 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2676 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002677 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002679 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002680 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 }
2682 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002683
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 // If we still couldn't decide a type, we probably have something that
2685 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002686 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002688 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002689 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002691
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002692 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002693 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002695 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002697
Chris Lattner5d661452007-08-26 03:42:43 +00002698 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2699 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002700 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002701 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002702
2703 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002704}
2705
John McCall60d7b3a2010-08-24 06:29:42 +00002706ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002707 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002708 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002709 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002710}
2711
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002712static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2713 SourceLocation Loc,
2714 SourceRange ArgRange) {
2715 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2716 // scalar or vector data type argument..."
2717 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2718 // type (C99 6.2.5p18) or void.
2719 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2720 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2721 << T << ArgRange;
2722 return true;
2723 }
2724
2725 assert((T->isVoidType() || !T->isIncompleteType()) &&
2726 "Scalar types should always be complete");
2727 return false;
2728}
2729
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002730static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2731 SourceLocation Loc,
2732 SourceRange ArgRange,
2733 UnaryExprOrTypeTrait TraitKind) {
2734 // C99 6.5.3.4p1:
2735 if (T->isFunctionType()) {
2736 // alignof(function) is allowed as an extension.
2737 if (TraitKind == UETT_SizeOf)
2738 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2739 return false;
2740 }
2741
2742 // Allow sizeof(void)/alignof(void) as an extension.
2743 if (T->isVoidType()) {
2744 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2745 return false;
2746 }
2747
2748 return true;
2749}
2750
2751static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2752 SourceLocation Loc,
2753 SourceRange ArgRange,
2754 UnaryExprOrTypeTrait TraitKind) {
2755 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2756 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2757 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2758 << T << (TraitKind == UETT_SizeOf)
2759 << ArgRange;
2760 return true;
2761 }
2762
2763 return false;
2764}
2765
Chandler Carruth9d342d02011-05-26 08:53:10 +00002766/// \brief Check the constrains on expression operands to unary type expression
2767/// and type traits.
2768///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002769/// Completes any types necessary and validates the constraints on the operand
2770/// expression. The logic mostly mirrors the type-based overload, but may modify
2771/// the expression as it completes the type for that expression through template
2772/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002773bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2774 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002775 QualType ExprTy = Op->getType();
2776
2777 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2778 // the result is the size of the referenced type."
2779 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2780 // result shall be the alignment of the referenced type."
2781 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2782 ExprTy = Ref->getPointeeType();
2783
2784 if (ExprKind == UETT_VecStep)
2785 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2786 Op->getSourceRange());
2787
2788 // Whitelist some types as extensions
2789 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2790 Op->getSourceRange(), ExprKind))
2791 return false;
2792
2793 if (RequireCompleteExprType(Op,
2794 PDiag(diag::err_sizeof_alignof_incomplete_type)
2795 << ExprKind << Op->getSourceRange(),
2796 std::make_pair(SourceLocation(), PDiag(0))))
2797 return true;
2798
2799 // Completeing the expression's type may have changed it.
2800 ExprTy = Op->getType();
2801 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2802 ExprTy = Ref->getPointeeType();
2803
2804 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2805 Op->getSourceRange(), ExprKind))
2806 return true;
2807
Nico Webercf739922011-06-15 02:47:03 +00002808 if (ExprKind == UETT_SizeOf) {
2809 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2810 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2811 QualType OType = PVD->getOriginalType();
2812 QualType Type = PVD->getType();
2813 if (Type->isPointerType() && OType->isArrayType()) {
2814 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2815 << Type << OType;
2816 Diag(PVD->getLocation(), diag::note_declared_at);
2817 }
2818 }
2819 }
2820 }
2821
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002822 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002823}
2824
2825/// \brief Check the constraints on operands to unary expression and type
2826/// traits.
2827///
2828/// This will complete any types necessary, and validate the various constraints
2829/// on those operands.
2830///
Reid Spencer5f016e22007-07-11 17:01:13 +00002831/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002832/// C99 6.3.2.1p[2-4] all state:
2833/// Except when it is the operand of the sizeof operator ...
2834///
2835/// C++ [expr.sizeof]p4
2836/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2837/// standard conversions are not applied to the operand of sizeof.
2838///
2839/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002840bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2841 SourceLocation OpLoc,
2842 SourceRange ExprRange,
2843 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002844 if (exprType->isDependentType())
2845 return false;
2846
Sebastian Redl5d484e82009-11-23 17:18:46 +00002847 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2848 // the result is the size of the referenced type."
2849 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2850 // result shall be the alignment of the referenced type."
2851 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2852 exprType = Ref->getPointeeType();
2853
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002854 if (ExprKind == UETT_VecStep)
2855 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002856
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002857 // Whitelist some types as extensions
2858 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2859 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002860 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Chris Lattner1efaa952009-04-24 00:30:45 +00002862 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002863 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002864 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002865 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002867 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2868 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002869 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Chris Lattner1efaa952009-04-24 00:30:45 +00002871 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002872}
2873
Chandler Carruth9d342d02011-05-26 08:53:10 +00002874static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002875 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002876
Mike Stump1eb44332009-09-09 15:08:12 +00002877 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002878 if (isa<DeclRefExpr>(E))
2879 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002880
2881 // Cannot know anything else if the expression is dependent.
2882 if (E->isTypeDependent())
2883 return false;
2884
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002885 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002886 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2887 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002888 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002889 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002890
2891 // Alignment of a field access is always okay, so long as it isn't a
2892 // bit-field.
2893 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002894 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002895 return false;
2896
Chandler Carruth9d342d02011-05-26 08:53:10 +00002897 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002898}
2899
Chandler Carruth9d342d02011-05-26 08:53:10 +00002900bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002901 E = E->IgnoreParens();
2902
2903 // Cannot know anything else if the expression is dependent.
2904 if (E->isTypeDependent())
2905 return false;
2906
Chandler Carruth9d342d02011-05-26 08:53:10 +00002907 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002908}
2909
Douglas Gregorba498172009-03-13 21:01:28 +00002910/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002911ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002912Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2913 SourceLocation OpLoc,
2914 UnaryExprOrTypeTrait ExprKind,
2915 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002916 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002917 return ExprError();
2918
John McCalla93c9342009-12-07 02:54:59 +00002919 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002920
Douglas Gregorba498172009-03-13 21:01:28 +00002921 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002922 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002923 return ExprError();
2924
2925 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002926 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2927 Context.getSizeType(),
2928 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002929}
2930
2931/// \brief Build a sizeof or alignof expression given an expression
2932/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002933ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002934Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2935 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002936 ExprResult PE = CheckPlaceholderExpr(E);
2937 if (PE.isInvalid())
2938 return ExprError();
2939
2940 E = PE.get();
2941
Douglas Gregorba498172009-03-13 21:01:28 +00002942 // Verify that the operand is valid.
2943 bool isInvalid = false;
2944 if (E->isTypeDependent()) {
2945 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002946 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002947 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002948 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002949 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002950 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002951 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002952 isInvalid = true;
2953 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002954 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002955 }
2956
2957 if (isInvalid)
2958 return ExprError();
2959
2960 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002961 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002962 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002963 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002964}
2965
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002966/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2967/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002968/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002969ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002970Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2971 UnaryExprOrTypeTrait ExprKind, bool isType,
2972 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002973 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002974 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002975
Sebastian Redl05189992008-11-11 17:56:53 +00002976 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002977 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002978 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002979 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002980 }
Sebastian Redl05189992008-11-11 17:56:53 +00002981
Douglas Gregorba498172009-03-13 21:01:28 +00002982 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002983 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002984 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002985}
2986
John Wiegley429bb272011-04-08 18:41:53 +00002987static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002988 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002989 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002990 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002991
John McCallf6a16482010-12-04 03:47:34 +00002992 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002993 if (V.get()->getObjectKind() != OK_Ordinary) {
2994 V = S.DefaultLvalueConversion(V.take());
2995 if (V.isInvalid())
2996 return QualType();
2997 }
John McCallf6a16482010-12-04 03:47:34 +00002998
Chris Lattnercc26ed72007-08-26 05:39:26 +00002999 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003000 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003001 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Chris Lattnercc26ed72007-08-26 05:39:26 +00003003 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003004 if (V.get()->getType()->isArithmeticType())
3005 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003006
John McCall2cd11fe2010-10-12 02:09:17 +00003007 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003008 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003009 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003010 if (PR.get() != V.get()) {
3011 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003012 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003013 }
3014
Chris Lattnercc26ed72007-08-26 05:39:26 +00003015 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003016 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003017 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003018 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003019}
3020
3021
Reid Spencer5f016e22007-07-11 17:01:13 +00003022
John McCall60d7b3a2010-08-24 06:29:42 +00003023ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003024Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003025 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003026 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 switch (Kind) {
3028 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003029 case tok::plusplus: Opc = UO_PostInc; break;
3030 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003032
John McCall9ae2f072010-08-23 23:25:46 +00003033 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003034}
3035
John McCall60d7b3a2010-08-24 06:29:42 +00003036ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003037Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3038 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003039 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003040 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003041 if (Result.isInvalid()) return ExprError();
3042 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003043
John McCall9ae2f072010-08-23 23:25:46 +00003044 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Douglas Gregor337c6b92008-11-19 17:17:41 +00003046 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003047 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003048 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003049 Context.DependentTy,
3050 VK_LValue, OK_Ordinary,
3051 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003052 }
3053
Mike Stump1eb44332009-09-09 15:08:12 +00003054 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003055 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003056 LHSExp->getType()->isEnumeralType() ||
3057 RHSExp->getType()->isRecordType() ||
3058 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003059 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003060 }
3061
John McCall9ae2f072010-08-23 23:25:46 +00003062 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003063}
3064
3065
John McCall60d7b3a2010-08-24 06:29:42 +00003066ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003067Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3068 Expr *Idx, SourceLocation RLoc) {
3069 Expr *LHSExp = Base;
3070 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003071
Chris Lattner12d9ff62007-07-16 00:14:47 +00003072 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003073 if (!LHSExp->getType()->getAs<VectorType>()) {
3074 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3075 if (Result.isInvalid())
3076 return ExprError();
3077 LHSExp = Result.take();
3078 }
3079 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3080 if (Result.isInvalid())
3081 return ExprError();
3082 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003083
Chris Lattner12d9ff62007-07-16 00:14:47 +00003084 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003085 ExprValueKind VK = VK_LValue;
3086 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003087
Reid Spencer5f016e22007-07-11 17:01:13 +00003088 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003089 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003090 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003091 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003092 Expr *BaseExpr, *IndexExpr;
3093 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003094 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3095 BaseExpr = LHSExp;
3096 IndexExpr = RHSExp;
3097 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003098 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003099 BaseExpr = LHSExp;
3100 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003101 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003102 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003103 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003104 BaseExpr = RHSExp;
3105 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003106 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003107 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003108 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003109 BaseExpr = LHSExp;
3110 IndexExpr = RHSExp;
3111 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003112 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003113 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003114 // Handle the uncommon case of "123[Ptr]".
3115 BaseExpr = RHSExp;
3116 IndexExpr = LHSExp;
3117 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003118 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003119 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003120 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003121 VK = LHSExp->getValueKind();
3122 if (VK != VK_RValue)
3123 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003124
Chris Lattner12d9ff62007-07-16 00:14:47 +00003125 // FIXME: need to deal with const...
3126 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003127 } else if (LHSTy->isArrayType()) {
3128 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003129 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003130 // wasn't promoted because of the C90 rule that doesn't
3131 // allow promoting non-lvalue arrays. Warn, then
3132 // force the promotion here.
3133 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3134 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003135 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3136 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003137 LHSTy = LHSExp->getType();
3138
3139 BaseExpr = LHSExp;
3140 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003141 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003142 } else if (RHSTy->isArrayType()) {
3143 // Same as previous, except for 123[f().a] case
3144 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3145 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003146 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3147 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003148 RHSTy = RHSExp->getType();
3149
3150 BaseExpr = RHSExp;
3151 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003152 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003154 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3155 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003156 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003158 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003159 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3160 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003161
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003162 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003163 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3164 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003165 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3166
Douglas Gregore7450f52009-03-24 19:52:54 +00003167 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003168 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3169 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003170 // incomplete types are not object types.
3171 if (ResultType->isFunctionType()) {
3172 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3173 << ResultType << BaseExpr->getSourceRange();
3174 return ExprError();
3175 }
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Abramo Bagnara46358452010-09-13 06:50:07 +00003177 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3178 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003179 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3180 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003181
3182 // C forbids expressions of unqualified void type from being l-values.
3183 // See IsCForbiddenLValueType.
3184 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003185 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003186 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003187 PDiag(diag::err_subscript_incomplete_type)
3188 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003189 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Chris Lattner1efaa952009-04-24 00:30:45 +00003191 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003192 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003193 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3194 << ResultType << BaseExpr->getSourceRange();
3195 return ExprError();
3196 }
Mike Stump1eb44332009-09-09 15:08:12 +00003197
John McCall09431682010-11-18 19:01:18 +00003198 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003199 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003200
Mike Stumpeed9cac2009-02-19 03:04:26 +00003201 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003202 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003203}
3204
John McCall60d7b3a2010-08-24 06:29:42 +00003205ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003206 FunctionDecl *FD,
3207 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003208 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003209 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003210 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003211 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003212 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003213 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003214 return ExprError();
3215 }
3216
3217 if (Param->hasUninstantiatedDefaultArg()) {
3218 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003219
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003220 // Instantiate the expression.
3221 MultiLevelTemplateArgumentList ArgList
3222 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003223
Nico Weber08e41a62010-11-29 18:19:25 +00003224 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003225 = ArgList.getInnermost();
3226 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3227 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003228
Nico Weber08e41a62010-11-29 18:19:25 +00003229 ExprResult Result;
3230 {
3231 // C++ [dcl.fct.default]p5:
3232 // The names in the [default argument] expression are bound, and
3233 // the semantic constraints are checked, at the point where the
3234 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003235 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003236 Result = SubstExpr(UninstExpr, ArgList);
3237 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003238 if (Result.isInvalid())
3239 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003241 // Check the expression as an initializer for the parameter.
3242 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003243 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003244 InitializationKind Kind
3245 = InitializationKind::CreateCopy(Param->getLocation(),
3246 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3247 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003248
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003249 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3250 Result = InitSeq.Perform(*this, Entity, Kind,
3251 MultiExprArg(*this, &ResultE, 1));
3252 if (Result.isInvalid())
3253 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003254
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003255 // Build the default argument expression.
3256 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3257 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003258 }
3259
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003260 // If the default expression creates temporaries, we need to
3261 // push them to the current stack of expression temporaries so they'll
3262 // be properly destroyed.
3263 // FIXME: We should really be rebuilding the default argument with new
3264 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003265 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3266 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3267 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3268 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3269 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003270 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003271 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003272
3273 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003274 // Just mark all of the declarations in this potentially-evaluated expression
3275 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003276 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003277 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003278}
3279
Douglas Gregor88a35142008-12-22 05:46:06 +00003280/// ConvertArgumentsForCall - Converts the arguments specified in
3281/// Args/NumArgs to the parameter types of the function FDecl with
3282/// function prototype Proto. Call is the call expression itself, and
3283/// Fn is the function expression. For a C++ member function, this
3284/// routine does not attempt to convert the object argument. Returns
3285/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003286bool
3287Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003288 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003289 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003290 Expr **Args, unsigned NumArgs,
3291 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003292 // Bail out early if calling a builtin with custom typechecking.
3293 // We don't need to do this in the
3294 if (FDecl)
3295 if (unsigned ID = FDecl->getBuiltinID())
3296 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3297 return false;
3298
Mike Stumpeed9cac2009-02-19 03:04:26 +00003299 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003300 // assignment, to the types of the corresponding parameter, ...
3301 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003302 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003303
Douglas Gregor88a35142008-12-22 05:46:06 +00003304 // If too few arguments are available (and we don't have default
3305 // arguments for the remaining parameters), don't make the call.
3306 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003307 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3308 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003309 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003310 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003311
3312 // Emit the location of the prototype.
3313 if (FDecl && !FDecl->getBuiltinID())
3314 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3315 << FDecl;
3316
3317 return true;
3318 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003319 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003320 }
3321
3322 // If too many are passed and not variadic, error on the extras and drop
3323 // them.
3324 if (NumArgs > NumArgsInProto) {
3325 if (!Proto->isVariadic()) {
3326 Diag(Args[NumArgsInProto]->getLocStart(),
3327 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003328 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003329 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003330 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3331 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003332
3333 // Emit the location of the prototype.
3334 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003335 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3336 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003337
Douglas Gregor88a35142008-12-22 05:46:06 +00003338 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003339 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003340 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003341 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003342 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003343 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003344 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003345 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3346 if (Fn->getType()->isBlockPointerType())
3347 CallType = VariadicBlock; // Block
3348 else if (isa<MemberExpr>(Fn))
3349 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003350 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003351 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003352 if (Invalid)
3353 return true;
3354 unsigned TotalNumArgs = AllArgs.size();
3355 for (unsigned i = 0; i < TotalNumArgs; ++i)
3356 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003357
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003358 return false;
3359}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003360
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003361bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3362 FunctionDecl *FDecl,
3363 const FunctionProtoType *Proto,
3364 unsigned FirstProtoArg,
3365 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003366 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003367 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003368 unsigned NumArgsInProto = Proto->getNumArgs();
3369 unsigned NumArgsToCheck = NumArgs;
3370 bool Invalid = false;
3371 if (NumArgs != NumArgsInProto)
3372 // Use default arguments for missing arguments
3373 NumArgsToCheck = NumArgsInProto;
3374 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003375 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003377 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003378
Douglas Gregor88a35142008-12-22 05:46:06 +00003379 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003380 if (ArgIx < NumArgs) {
3381 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003382
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003383 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3384 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003385 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003386 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003387 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003388
Douglas Gregora188ff22009-12-22 16:09:06 +00003389 // Pass the argument
3390 ParmVarDecl *Param = 0;
3391 if (FDecl && i < FDecl->getNumParams())
3392 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003393
Douglas Gregora188ff22009-12-22 16:09:06 +00003394 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003395 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003396 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3397 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003398 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003399 SourceLocation(),
3400 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003401 if (ArgE.isInvalid())
3402 return true;
3403
3404 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003405 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003406 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003407
John McCall60d7b3a2010-08-24 06:29:42 +00003408 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003409 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003410 if (ArgExpr.isInvalid())
3411 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003412
Anders Carlsson56c5e332009-08-25 03:49:14 +00003413 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003414 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003415
3416 // Check for array bounds violations for each argument to the call. This
3417 // check only triggers warnings when the argument isn't a more complex Expr
3418 // with its own checking, such as a BinaryOperator.
3419 CheckArrayAccess(Arg);
3420
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003421 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003422 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003423
Douglas Gregor88a35142008-12-22 05:46:06 +00003424 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003425 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003426
3427 // Assume that extern "C" functions with variadic arguments that
3428 // return __unknown_anytype aren't *really* variadic.
3429 if (Proto->getResultType() == Context.UnknownAnyTy &&
3430 FDecl && FDecl->isExternC()) {
3431 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3432 ExprResult arg;
3433 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3434 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3435 else
3436 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3437 Invalid |= arg.isInvalid();
3438 AllArgs.push_back(arg.take());
3439 }
3440
3441 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3442 } else {
3443 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003444 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3445 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003446 Invalid |= Arg.isInvalid();
3447 AllArgs.push_back(Arg.take());
3448 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003449 }
3450 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003451 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003452}
3453
John McCall755d8492011-04-12 00:42:48 +00003454/// Given a function expression of unknown-any type, try to rebuild it
3455/// to have a function type.
3456static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3457
Steve Narofff69936d2007-09-16 03:34:24 +00003458/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003459/// This provides the location of the left/right parens and a list of comma
3460/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003461ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003462Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003463 MultiExprArg args, SourceLocation RParenLoc,
3464 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003465 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003466
3467 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003468 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003469 if (Result.isInvalid()) return ExprError();
3470 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003471
John McCall9ae2f072010-08-23 23:25:46 +00003472 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Douglas Gregor88a35142008-12-22 05:46:06 +00003474 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003475 // If this is a pseudo-destructor expression, build the call immediately.
3476 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3477 if (NumArgs > 0) {
3478 // Pseudo-destructor calls should not have any arguments.
3479 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003480 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003481 SourceRange(Args[0]->getLocStart(),
3482 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Douglas Gregora71d8192009-09-04 17:36:40 +00003484 NumArgs = 0;
3485 }
Mike Stump1eb44332009-09-09 15:08:12 +00003486
Douglas Gregora71d8192009-09-04 17:36:40 +00003487 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003488 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003489 }
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Douglas Gregor17330012009-02-04 15:01:18 +00003491 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003492 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003493 // FIXME: Will need to cache the results of name lookup (including ADL) in
3494 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003495 bool Dependent = false;
3496 if (Fn->isTypeDependent())
3497 Dependent = true;
3498 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3499 Dependent = true;
3500
Peter Collingbournee08ce652011-02-09 21:07:24 +00003501 if (Dependent) {
3502 if (ExecConfig) {
3503 return Owned(new (Context) CUDAKernelCallExpr(
3504 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3505 Context.DependentTy, VK_RValue, RParenLoc));
3506 } else {
3507 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3508 Context.DependentTy, VK_RValue,
3509 RParenLoc));
3510 }
3511 }
Douglas Gregor17330012009-02-04 15:01:18 +00003512
3513 // Determine whether this is a call to an object (C++ [over.call.object]).
3514 if (Fn->getType()->isRecordType())
3515 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003516 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003517
John McCall755d8492011-04-12 00:42:48 +00003518 if (Fn->getType() == Context.UnknownAnyTy) {
3519 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3520 if (result.isInvalid()) return ExprError();
3521 Fn = result.take();
3522 }
3523
John McCall864c0412011-04-26 20:42:42 +00003524 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003525 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003526 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003527 }
John McCall864c0412011-04-26 20:42:42 +00003528 }
John McCall129e2df2009-11-30 22:42:35 +00003529
John McCall864c0412011-04-26 20:42:42 +00003530 // Check for overloaded calls. This can happen even in C due to extensions.
3531 if (Fn->getType() == Context.OverloadTy) {
3532 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3533
3534 // We aren't supposed to apply this logic if there's an '&' involved.
3535 if (!find.IsAddressOfOperand) {
3536 OverloadExpr *ovl = find.Expression;
3537 if (isa<UnresolvedLookupExpr>(ovl)) {
3538 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3539 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3540 RParenLoc, ExecConfig);
3541 } else {
John McCallaa81e162009-12-01 22:10:20 +00003542 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003543 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003544 }
3545 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003546 }
3547
Douglas Gregorfa047642009-02-04 00:32:51 +00003548 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003549
Eli Friedmanefa42f72009-12-26 03:35:45 +00003550 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003551
John McCall3b4294e2009-12-16 12:17:52 +00003552 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003553 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3554 if (UnOp->getOpcode() == UO_AddrOf)
3555 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3556
John McCall3b4294e2009-12-16 12:17:52 +00003557 if (isa<DeclRefExpr>(NakedFn))
3558 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003559 else if (isa<MemberExpr>(NakedFn))
3560 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003561
Peter Collingbournee08ce652011-02-09 21:07:24 +00003562 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3563 ExecConfig);
3564}
3565
3566ExprResult
3567Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3568 MultiExprArg execConfig, SourceLocation GGGLoc) {
3569 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3570 if (!ConfigDecl)
3571 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3572 << "cudaConfigureCall");
3573 QualType ConfigQTy = ConfigDecl->getType();
3574
3575 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3576 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3577
3578 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003579}
3580
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003581/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3582///
3583/// __builtin_astype( value, dst type )
3584///
3585ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3586 SourceLocation BuiltinLoc,
3587 SourceLocation RParenLoc) {
3588 ExprValueKind VK = VK_RValue;
3589 ExprObjectKind OK = OK_Ordinary;
3590 QualType DstTy = GetTypeFromParser(destty);
3591 QualType SrcTy = expr->getType();
3592 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3593 return ExprError(Diag(BuiltinLoc,
3594 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003595 << DstTy
3596 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003597 << expr->getSourceRange());
Richard Trieu67e29332011-08-02 04:35:43 +00003598 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3599 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003600}
3601
John McCall3b4294e2009-12-16 12:17:52 +00003602/// BuildResolvedCallExpr - Build a call to a resolved expression,
3603/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003604/// unary-convert to an expression of function-pointer or
3605/// block-pointer type.
3606///
3607/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003608ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003609Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3610 SourceLocation LParenLoc,
3611 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003612 SourceLocation RParenLoc,
3613 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003614 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3615
Chris Lattner04421082008-04-08 04:40:51 +00003616 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003617 ExprResult Result = UsualUnaryConversions(Fn);
3618 if (Result.isInvalid())
3619 return ExprError();
3620 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003621
Chris Lattner925e60d2007-12-28 05:29:59 +00003622 // Make the call expr early, before semantic checks. This guarantees cleanup
3623 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003624 CallExpr *TheCall;
3625 if (Config) {
3626 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3627 cast<CallExpr>(Config),
3628 Args, NumArgs,
3629 Context.BoolTy,
3630 VK_RValue,
3631 RParenLoc);
3632 } else {
3633 TheCall = new (Context) CallExpr(Context, Fn,
3634 Args, NumArgs,
3635 Context.BoolTy,
3636 VK_RValue,
3637 RParenLoc);
3638 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003639
John McCall8e10f3b2011-02-26 05:39:39 +00003640 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3641
3642 // Bail out early if calling a builtin with custom typechecking.
3643 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3644 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3645
John McCall1de4d4e2011-04-07 08:22:57 +00003646 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003647 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003648 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003649 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3650 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003651 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003652 if (FuncT == 0)
3653 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3654 << Fn->getType() << Fn->getSourceRange());
3655 } else if (const BlockPointerType *BPT =
3656 Fn->getType()->getAs<BlockPointerType>()) {
3657 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3658 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003659 // Handle calls to expressions of unknown-any type.
3660 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003661 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003662 if (rewrite.isInvalid()) return ExprError();
3663 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003664 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003665 goto retry;
3666 }
3667
Sebastian Redl0eb23302009-01-19 00:08:26 +00003668 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3669 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003670 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003671
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003672 if (getLangOptions().CUDA) {
3673 if (Config) {
3674 // CUDA: Kernel calls must be to global functions
3675 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3676 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3677 << FDecl->getName() << Fn->getSourceRange());
3678
3679 // CUDA: Kernel function must have 'void' return type
3680 if (!FuncT->getResultType()->isVoidType())
3681 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3682 << Fn->getType() << Fn->getSourceRange());
3683 }
3684 }
3685
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003686 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003687 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003688 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003689 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003690 return ExprError();
3691
Chris Lattner925e60d2007-12-28 05:29:59 +00003692 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003693 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003694 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003695
Douglas Gregor72564e72009-02-26 23:50:07 +00003696 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003697 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003698 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003699 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003700 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003701 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003702
Douglas Gregor74734d52009-04-02 15:37:10 +00003703 if (FDecl) {
3704 // Check if we have too few/too many template arguments, based
3705 // on our knowledge of the function definition.
3706 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003707 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003708 const FunctionProtoType *Proto
3709 = Def->getType()->getAs<FunctionProtoType>();
3710 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003711 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3712 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003713 }
Douglas Gregor46542412010-10-25 20:39:23 +00003714
3715 // If the function we're calling isn't a function prototype, but we have
3716 // a function prototype from a prior declaratiom, use that prototype.
3717 if (!FDecl->hasPrototype())
3718 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003719 }
3720
Steve Naroffb291ab62007-08-28 23:30:39 +00003721 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003722 for (unsigned i = 0; i != NumArgs; i++) {
3723 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003724
3725 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003726 InitializedEntity Entity
3727 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003728 Proto->getArgType(i),
3729 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003730 ExprResult ArgE = PerformCopyInitialization(Entity,
3731 SourceLocation(),
3732 Owned(Arg));
3733 if (ArgE.isInvalid())
3734 return true;
3735
3736 Arg = ArgE.takeAs<Expr>();
3737
3738 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003739 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3740
3741 if (ArgE.isInvalid())
3742 return true;
3743
3744 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003745 }
3746
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003747 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3748 Arg->getType(),
3749 PDiag(diag::err_call_incomplete_argument)
3750 << Arg->getSourceRange()))
3751 return ExprError();
3752
Chris Lattner925e60d2007-12-28 05:29:59 +00003753 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003755 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003756
Douglas Gregor88a35142008-12-22 05:46:06 +00003757 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3758 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003759 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3760 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003761
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003762 // Check for sentinels
3763 if (NDecl)
3764 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Chris Lattner59907c42007-08-10 20:18:51 +00003766 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003767 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003768 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003769 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003770
John McCall8e10f3b2011-02-26 05:39:39 +00003771 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003772 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003773 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003774 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003775 return ExprError();
3776 }
Chris Lattner59907c42007-08-10 20:18:51 +00003777
John McCall9ae2f072010-08-23 23:25:46 +00003778 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003779}
3780
John McCall60d7b3a2010-08-24 06:29:42 +00003781ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003782Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003783 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003784 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003785 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003786 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003787
3788 TypeSourceInfo *TInfo;
3789 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3790 if (!TInfo)
3791 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3792
John McCall9ae2f072010-08-23 23:25:46 +00003793 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003794}
3795
John McCall60d7b3a2010-08-24 06:29:42 +00003796ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003797Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003798 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003799 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003800
Eli Friedman6223c222008-05-20 05:22:08 +00003801 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003802 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3803 PDiag(diag::err_illegal_decl_array_incomplete_type)
3804 << SourceRange(LParenLoc,
3805 literalExpr->getSourceRange().getEnd())))
3806 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003807 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003808 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3809 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003810 } else if (!literalType->isDependentType() &&
3811 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003812 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003813 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003814 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003815 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003816
Douglas Gregor99a2e602009-12-16 01:38:02 +00003817 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003818 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003819 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003820 = InitializationKind::CreateCStyleCast(LParenLoc,
3821 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003822 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003823 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003824 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003825 &literalType);
3826 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003827 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003828 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003829
Chris Lattner371f2582008-12-04 23:50:19 +00003830 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003831 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003832 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003833 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003834 }
Eli Friedman08544622009-12-22 02:35:53 +00003835
John McCallf89e55a2010-11-18 06:31:45 +00003836 // In C, compound literals are l-values for some reason.
3837 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3838
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003839 return MaybeBindToTemporary(
3840 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3841 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003842}
3843
John McCall60d7b3a2010-08-24 06:29:42 +00003844ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003845Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003846 SourceLocation RBraceLoc) {
3847 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003848 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003849
Steve Naroff08d92e42007-09-15 18:49:24 +00003850 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003851 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003852
Ted Kremenek709210f2010-04-13 23:39:13 +00003853 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3854 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003855 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003856 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003857}
3858
John McCallf3ea8cf2010-11-14 08:17:51 +00003859/// Prepares for a scalar cast, performing all the necessary stages
3860/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003861static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003862 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3863 // Also, callers should have filtered out the invalid cases with
3864 // pointers. Everything else should be possible.
3865
John Wiegley429bb272011-04-08 18:41:53 +00003866 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003867 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003868 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003869
John McCalldaa8e4e2010-11-15 09:13:47 +00003870 switch (SrcTy->getScalarTypeKind()) {
3871 case Type::STK_MemberPointer:
3872 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003873
John McCalldaa8e4e2010-11-15 09:13:47 +00003874 case Type::STK_Pointer:
3875 switch (DestTy->getScalarTypeKind()) {
3876 case Type::STK_Pointer:
3877 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003878 CK_AnyPointerToObjCPointerCast :
3879 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003880 case Type::STK_Bool:
3881 return CK_PointerToBoolean;
3882 case Type::STK_Integral:
3883 return CK_PointerToIntegral;
3884 case Type::STK_Floating:
3885 case Type::STK_FloatingComplex:
3886 case Type::STK_IntegralComplex:
3887 case Type::STK_MemberPointer:
3888 llvm_unreachable("illegal cast from pointer");
3889 }
3890 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003891
John McCalldaa8e4e2010-11-15 09:13:47 +00003892 case Type::STK_Bool: // casting from bool is like casting from an integer
3893 case Type::STK_Integral:
3894 switch (DestTy->getScalarTypeKind()) {
3895 case Type::STK_Pointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003896 if (Src.get()->isNullPointerConstant(S.Context,
3897 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003898 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003899 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003900 case Type::STK_Bool:
3901 return CK_IntegralToBoolean;
3902 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003903 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003904 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003905 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003906 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003907 Src = S.ImpCastExprToType(Src.take(),
3908 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003909 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003910 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003911 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003912 Src = S.ImpCastExprToType(Src.take(),
3913 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003914 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003915 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003916 case Type::STK_MemberPointer:
3917 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003918 }
3919 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003920
John McCalldaa8e4e2010-11-15 09:13:47 +00003921 case Type::STK_Floating:
3922 switch (DestTy->getScalarTypeKind()) {
3923 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003924 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003925 case Type::STK_Bool:
3926 return CK_FloatingToBoolean;
3927 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003928 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003929 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003930 Src = S.ImpCastExprToType(Src.take(),
3931 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003932 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003933 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003934 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003935 Src = S.ImpCastExprToType(Src.take(),
3936 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003937 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003938 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003939 case Type::STK_Pointer:
3940 llvm_unreachable("valid float->pointer cast?");
3941 case Type::STK_MemberPointer:
3942 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003943 }
3944 break;
3945
John McCalldaa8e4e2010-11-15 09:13:47 +00003946 case Type::STK_FloatingComplex:
3947 switch (DestTy->getScalarTypeKind()) {
3948 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003949 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003950 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003951 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003952 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003953 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003954 if (S.Context.hasSameType(ET, DestTy))
3955 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003956 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003957 return CK_FloatingCast;
3958 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003959 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003960 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003961 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003962 Src = S.ImpCastExprToType(Src.take(),
3963 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003964 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003965 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003966 case Type::STK_Pointer:
3967 llvm_unreachable("valid complex float->pointer cast?");
3968 case Type::STK_MemberPointer:
3969 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003970 }
3971 break;
3972
John McCalldaa8e4e2010-11-15 09:13:47 +00003973 case Type::STK_IntegralComplex:
3974 switch (DestTy->getScalarTypeKind()) {
3975 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003976 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003977 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003978 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003979 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003980 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003981 if (S.Context.hasSameType(ET, DestTy))
3982 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003983 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003984 return CK_IntegralCast;
3985 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003986 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003987 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003988 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003989 Src = S.ImpCastExprToType(Src.take(),
3990 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003991 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003992 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003993 case Type::STK_Pointer:
3994 llvm_unreachable("valid complex int->pointer cast?");
3995 case Type::STK_MemberPointer:
3996 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003997 }
3998 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003999 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004000
John McCallf3ea8cf2010-11-14 08:17:51 +00004001 llvm_unreachable("Unhandled scalar cast");
4002 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004003}
4004
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004005/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00004006ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
4007 QualType castType, Expr *castExpr,
4008 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00004009 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00004010 if (castExpr->getType() == Context.UnknownAnyTy)
4011 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
4012
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004013 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004014 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00004015 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004016 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004017 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004018
John McCallfb8721c2011-04-10 19:13:55 +00004019 assert(!castExpr->getType()->isPlaceholderType());
4020
John McCallf89e55a2010-11-18 06:31:45 +00004021 // We only support r-value casts in C.
4022 VK = VK_RValue;
4023
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004024 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4025 // type needs to be scalar.
4026 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004027 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00004028 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4029 if (castExprRes.isInvalid())
4030 return ExprError();
4031 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004032
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004033 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004034 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00004035 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004036 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004037
John Wiegley429bb272011-04-08 18:41:53 +00004038 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4039 if (castExprRes.isInvalid())
4040 return ExprError();
4041 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004042
Eli Friedman8d438082010-07-17 20:43:49 +00004043 if (RequireCompleteType(TyR.getBegin(), castType,
4044 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004045 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004046
Anders Carlssonebeaf202009-10-16 02:35:04 +00004047 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004048 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004049 (castType->isStructureType() || castType->isUnionType())) {
4050 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004051 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004052 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4053 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004054 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00004055 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004056 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004057
Anders Carlssonc3516322009-10-16 02:48:28 +00004058 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004059 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004060 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004061 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004062 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004063 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004064 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004065 castExpr->getType()) &&
4066 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004067 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4068 << castExpr->getSourceRange();
4069 break;
4070 }
4071 }
John Wiegley429bb272011-04-08 18:41:53 +00004072 if (Field == FieldEnd) {
4073 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004074 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004075 return ExprError();
4076 }
John McCall2de56d12010-08-25 11:45:40 +00004077 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00004078 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004079 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004080
Anders Carlssonc3516322009-10-16 02:48:28 +00004081 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00004082 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00004083 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004084 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004085 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004086
John McCallf3ea8cf2010-11-14 08:17:51 +00004087 // The type we're casting to is known to be a scalar or vector.
4088
4089 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004090 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004091 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004092 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004093 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004094 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004095 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004096 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004097
4098 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004099 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004100
Anton Yartsevd06fea82011-03-27 09:32:40 +00004101 if (castType->isVectorType()) {
4102 if (castType->getAs<VectorType>()->getVectorKind() ==
4103 VectorType::AltiVecVector &&
4104 (castExpr->getType()->isIntegerType() ||
4105 castExpr->getType()->isFloatingType())) {
4106 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004107 return Owned(castExpr);
4108 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4109 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004110 } else
John Wiegley429bb272011-04-08 18:41:53 +00004111 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004112 }
John Wiegley429bb272011-04-08 18:41:53 +00004113 if (castExpr->getType()->isVectorType()) {
4114 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4115 return ExprError();
4116 else
4117 return Owned(castExpr);
4118 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004119
John McCallf3ea8cf2010-11-14 08:17:51 +00004120 // The source and target types are both scalars, i.e.
4121 // - arithmetic types (fundamental, enum, and complex)
4122 // - all kinds of pointers
4123 // Note that member pointers were filtered out with C++, above.
4124
John Wiegley429bb272011-04-08 18:41:53 +00004125 if (isa<ObjCSelectorExpr>(castExpr)) {
4126 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4127 return ExprError();
4128 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004129
John McCallf3ea8cf2010-11-14 08:17:51 +00004130 // If either type is a pointer, the other type has to be either an
4131 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004132 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004133 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004134 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004135 castExprType->isArithmeticType()) {
4136 Diag(castExpr->getLocStart(),
4137 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004138 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004139 return ExprError();
4140 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004141 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004142 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4143 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004144 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004145 return ExprError();
4146 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004147 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004148
John McCallf85e1932011-06-15 23:02:42 +00004149 if (getLangOptions().ObjCAutoRefCount) {
4150 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4151 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4152 castType, castExpr, CCK_CStyleCast);
4153
4154 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4155 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4156 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4157 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4158 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4159 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4160 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4161 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004162 diag::err_typecheck_incompatible_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004163 << castExprType << castType << AA_Casting
4164 << castExpr->getSourceRange();
4165
4166 return ExprError();
4167 }
4168 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004169 }
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004170 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4171 Diag(castExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004172 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004173 << castExprType << castType
4174 << castExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004175 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004176 }
4177 }
4178
John Wiegley429bb272011-04-08 18:41:53 +00004179 castExprRes = Owned(castExpr);
4180 Kind = PrepareScalarCast(*this, castExprRes, castType);
4181 if (castExprRes.isInvalid())
4182 return ExprError();
4183 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004184
John McCallf3ea8cf2010-11-14 08:17:51 +00004185 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004186 CheckCastAlign(castExpr, castType, TyR);
4187
John Wiegley429bb272011-04-08 18:41:53 +00004188 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004189}
4190
Anders Carlssonc3516322009-10-16 02:48:28 +00004191bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004192 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004193 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004194
Anders Carlssona64db8f2007-11-27 05:51:55 +00004195 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004196 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004197 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004198 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004199 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004200 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004201 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004202 } else
4203 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004204 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004205 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004206
John McCall2de56d12010-08-25 11:45:40 +00004207 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004208 return false;
4209}
4210
John Wiegley429bb272011-04-08 18:41:53 +00004211ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4212 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004213 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004214
Anders Carlsson16a89042009-10-16 05:23:41 +00004215 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004216
Nate Begeman9b10da62009-06-27 22:05:55 +00004217 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4218 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004219 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004220 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4221 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004222 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004223 return ExprError();
4224 }
John McCall2de56d12010-08-25 11:45:40 +00004225 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004226 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004227 }
4228
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004229 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004230 // conversion will take place first from scalar to elt type, and then
4231 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004232 if (SrcTy->isPointerType())
4233 return Diag(R.getBegin(),
4234 diag::err_invalid_conversion_between_vector_and_scalar)
4235 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004236
4237 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004238 ExprResult CastExprRes = Owned(CastExpr);
4239 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4240 if (CastExprRes.isInvalid())
4241 return ExprError();
4242 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004243
John McCall2de56d12010-08-25 11:45:40 +00004244 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004245 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004246}
4247
John McCall60d7b3a2010-08-24 06:29:42 +00004248ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004249Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4250 Declarator &D, ParsedType &Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004251 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004252 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004253 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004254
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004255 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4256 if (D.isInvalidType())
4257 return ExprError();
4258
4259 if (getLangOptions().CPlusPlus) {
4260 // Check that there are no default arguments (C++ only).
4261 CheckExtraCXXDefaultArguments(D);
4262 }
4263
4264 QualType castType = castTInfo->getType();
4265 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004267 bool isVectorLiteral = false;
4268
4269 // Check for an altivec or OpenCL literal,
4270 // i.e. all the elements are integer constants.
4271 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4272 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4273 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4274 if (PLE && PLE->getNumExprs() == 0) {
4275 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4276 return ExprError();
4277 }
4278 if (PE || PLE->getNumExprs() == 1) {
4279 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4280 if (!E->getType()->isVectorType())
4281 isVectorLiteral = true;
4282 }
4283 else
4284 isVectorLiteral = true;
4285 }
4286
4287 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4288 // then handle it as such.
4289 if (isVectorLiteral)
4290 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4291
Nate Begeman2ef13e52009-08-10 23:49:36 +00004292 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004293 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4294 // sequence of BinOp comma operators.
4295 if (isa<ParenListExpr>(castExpr)) {
4296 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4297 if (Result.isInvalid()) return ExprError();
4298 castExpr = Result.take();
4299 }
John McCallb042fdf2010-01-15 18:56:44 +00004300
John McCall9ae2f072010-08-23 23:25:46 +00004301 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004302}
4303
John McCall60d7b3a2010-08-24 06:29:42 +00004304ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004305Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004306 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004307 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004308 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004309 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004310 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004311 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4312 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004313 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004314 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004315 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004316
Richard Trieu67e29332011-08-02 04:35:43 +00004317 return Owned(CStyleCastExpr::Create(
4318 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4319 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004320}
4321
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004322ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4323 SourceLocation RParenLoc, Expr *E,
4324 TypeSourceInfo *TInfo) {
4325 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4326 "Expected paren or paren list expression");
4327
4328 Expr **exprs;
4329 unsigned numExprs;
4330 Expr *subExpr;
4331 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4332 exprs = PE->getExprs();
4333 numExprs = PE->getNumExprs();
4334 } else {
4335 subExpr = cast<ParenExpr>(E)->getSubExpr();
4336 exprs = &subExpr;
4337 numExprs = 1;
4338 }
4339
4340 QualType Ty = TInfo->getType();
4341 assert(Ty->isVectorType() && "Expected vector type");
4342
Chris Lattner5f9e2722011-07-23 10:55:15 +00004343 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004344 const VectorType *VTy = Ty->getAs<VectorType>();
4345 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4346
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004347 // '(...)' form of vector initialization in AltiVec: the number of
4348 // initializers must be one or must match the size of the vector.
4349 // If a single value is specified in the initializer then it will be
4350 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004351 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004352 // The number of initializers must be one or must match the size of the
4353 // vector. If a single value is specified in the initializer then it will
4354 // be replicated to all the components of the vector
4355 if (numExprs == 1) {
4356 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4357 ExprResult Literal = Owned(exprs[0]);
4358 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4359 PrepareScalarCast(*this, Literal, ElemTy));
4360 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4361 }
4362 else if (numExprs < numElems) {
4363 Diag(E->getExprLoc(),
4364 diag::err_incorrect_number_of_vector_initializers);
4365 return ExprError();
4366 }
4367 else
4368 for (unsigned i = 0, e = numExprs; i != e; ++i)
4369 initExprs.push_back(exprs[i]);
4370 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004371 else {
4372 // For OpenCL, when the number of initializers is a single value,
4373 // it will be replicated to all components of the vector.
4374 if (getLangOptions().OpenCL &&
4375 VTy->getVectorKind() == VectorType::GenericVector &&
4376 numExprs == 1) {
4377 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4378 ExprResult Literal = Owned(exprs[0]);
4379 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4380 PrepareScalarCast(*this, Literal, ElemTy));
4381 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4382 }
4383
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004384 for (unsigned i = 0, e = numExprs; i != e; ++i)
4385 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004386 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004387 // FIXME: This means that pretty-printing the final AST will produce curly
4388 // braces instead of the original commas.
4389 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4390 &initExprs[0],
4391 initExprs.size(), RParenLoc);
4392 initE->setType(Ty);
4393 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4394}
4395
Nate Begeman2ef13e52009-08-10 23:49:36 +00004396/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4397/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004398ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004399Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004400 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4401 if (!E)
4402 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004403
John McCall60d7b3a2010-08-24 06:29:42 +00004404 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004405
Nate Begeman2ef13e52009-08-10 23:49:36 +00004406 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004407 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4408 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004409
John McCall9ae2f072010-08-23 23:25:46 +00004410 if (Result.isInvalid()) return ExprError();
4411
4412 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004413}
4414
John McCall60d7b3a2010-08-24 06:29:42 +00004415ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004416 SourceLocation R,
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004417 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004418 unsigned nexprs = Val.size();
4419 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004420 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4421 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004422 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004423 expr = new (Context) ParenExpr(L, R, exprs[0]);
4424 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004425 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4426 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004427 return Owned(expr);
4428}
4429
Chandler Carruth82214a82011-02-18 23:54:50 +00004430/// \brief Emit a specialized diagnostic when one expression is a null pointer
4431/// constant and the other is not a pointer.
4432bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4433 SourceLocation QuestionLoc) {
4434 Expr *NullExpr = LHS;
4435 Expr *NonPointerExpr = RHS;
4436 Expr::NullPointerConstantKind NullKind =
4437 NullExpr->isNullPointerConstant(Context,
4438 Expr::NPC_ValueDependentIsNotNull);
4439
4440 if (NullKind == Expr::NPCK_NotNull) {
4441 NullExpr = RHS;
4442 NonPointerExpr = LHS;
4443 NullKind =
4444 NullExpr->isNullPointerConstant(Context,
4445 Expr::NPC_ValueDependentIsNotNull);
4446 }
4447
4448 if (NullKind == Expr::NPCK_NotNull)
4449 return false;
4450
4451 if (NullKind == Expr::NPCK_ZeroInteger) {
4452 // In this case, check to make sure that we got here from a "NULL"
4453 // string in the source code.
4454 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004455 SourceLocation loc = NullExpr->getExprLoc();
4456 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004457 return false;
4458 }
4459
4460 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4461 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4462 << NonPointerExpr->getType() << DiagType
4463 << NonPointerExpr->getSourceRange();
4464 return true;
4465}
4466
Sebastian Redl28507842009-02-26 14:39:58 +00004467/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4468/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004469/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004470QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4471 ExprResult &RHS, ExprValueKind &VK,
4472 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004473 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004474
John McCallfb8721c2011-04-10 19:13:55 +00004475 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004476 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004477 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004478
John McCallfb8721c2011-04-10 19:13:55 +00004479 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004480 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004481 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004482
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004483 // C++ is sufficiently different to merit its own checker.
4484 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004485 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004486
4487 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004488 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004489
John Wiegley429bb272011-04-08 18:41:53 +00004490 Cond = UsualUnaryConversions(Cond.take());
4491 if (Cond.isInvalid())
4492 return QualType();
4493 LHS = UsualUnaryConversions(LHS.take());
4494 if (LHS.isInvalid())
4495 return QualType();
4496 RHS = UsualUnaryConversions(RHS.take());
4497 if (RHS.isInvalid())
4498 return QualType();
4499
4500 QualType CondTy = Cond.get()->getType();
4501 QualType LHSTy = LHS.get()->getType();
4502 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004503
Reid Spencer5f016e22007-07-11 17:01:13 +00004504 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004505 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00004506 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4507 // Throw an error if its not either.
4508 if (getLangOptions().OpenCL) {
4509 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004510 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00004511 diag::err_typecheck_cond_expect_scalar_or_vector)
4512 << CondTy;
4513 return QualType();
4514 }
4515 }
4516 else {
John Wiegley429bb272011-04-08 18:41:53 +00004517 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004518 << CondTy;
4519 return QualType();
4520 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004521 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004522
Chris Lattner70d67a92008-01-06 22:42:25 +00004523 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004524 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004525 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004526
Nate Begeman6155d732010-09-20 22:41:17 +00004527 // OpenCL: If the condition is a vector, and both operands are scalar,
4528 // attempt to implicity convert them to the vector type to act like the
4529 // built in select.
4530 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4531 // Both operands should be of scalar type.
4532 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004533 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004534 << CondTy;
4535 return QualType();
4536 }
4537 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004538 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004539 << CondTy;
4540 return QualType();
4541 }
4542 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00004543 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4544 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00004545 }
4546
Chris Lattner70d67a92008-01-06 22:42:25 +00004547 // If both operands have arithmetic type, do the usual arithmetic conversions
4548 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004549 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4550 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004551 if (LHS.isInvalid() || RHS.isInvalid())
4552 return QualType();
4553 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004554 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004555
Chris Lattner70d67a92008-01-06 22:42:25 +00004556 // If both operands are the same structure or union type, the result is that
4557 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004558 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4559 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004560 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004561 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004562 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004563 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004564 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004565 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004566
Chris Lattner70d67a92008-01-06 22:42:25 +00004567 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004568 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004569 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4570 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004571 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4572 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004573 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004574 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4575 << LHS.get()->getSourceRange();
4576 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4577 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004578 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004579 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004580 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4581 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004582 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004583 RHS.get()->isNullPointerConstant(Context,
4584 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004585 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00004586 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004587 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004588 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004589 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004590 LHS.get()->isNullPointerConstant(Context,
4591 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00004592 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004593 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004594 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004595
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004596 // All objective-c pointer type analysis is done here.
4597 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4598 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004599 if (LHS.isInvalid() || RHS.isInvalid())
4600 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004601 if (!compositeType.isNull())
4602 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004603
4604
Steve Naroff7154a772009-07-01 14:36:47 +00004605 // Handle block pointer types.
4606 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4607 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4608 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4609 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004610 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4611 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004612 return destType;
4613 }
4614 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004615 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4616 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004617 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004618 }
Steve Naroff7154a772009-07-01 14:36:47 +00004619 // We have 2 block pointer types.
4620 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4621 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004622 return LHSTy;
4623 }
Steve Naroff7154a772009-07-01 14:36:47 +00004624 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004625 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4626 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004627
Steve Naroff7154a772009-07-01 14:36:47 +00004628 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4629 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004630 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004631 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4632 << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004633 // In this situation, we assume void* type. No especially good
4634 // reason, but this is what gcc does, and we do have to pick
4635 // to get a consistent AST.
4636 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004637 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4638 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004639 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004640 }
Steve Naroff7154a772009-07-01 14:36:47 +00004641 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004642 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4643 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004644 return LHSTy;
4645 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004646
Steve Naroff7154a772009-07-01 14:36:47 +00004647 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4648 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4649 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004650 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4651 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004652
4653 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4654 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4655 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004656 QualType destPointee
4657 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004658 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004659 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004660 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004661 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004662 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004663 return destType;
4664 }
4665 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004666 QualType destPointee
4667 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004668 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004669 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004670 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004671 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004672 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004673 return destType;
4674 }
4675
4676 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4677 // Two identical pointer types are always compatible.
4678 return LHSTy;
4679 }
4680 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4681 rhptee.getUnqualifiedType())) {
4682 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004683 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4684 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004685 // In this situation, we assume void* type. No especially good
4686 // reason, but this is what gcc does, and we do have to pick
4687 // to get a consistent AST.
4688 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004689 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4690 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004691 return incompatTy;
4692 }
4693 // The pointer types are compatible.
4694 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4695 // differently qualified versions of compatible types, the result type is
4696 // a pointer to an appropriately qualified version of the *composite*
4697 // type.
4698 // FIXME: Need to calculate the composite type.
4699 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00004700 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4701 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004702 return LHSTy;
4703 }
Mike Stump1eb44332009-09-09 15:08:12 +00004704
John McCall404cd162010-11-13 01:35:44 +00004705 // GCC compatibility: soften pointer/integer mismatch. Note that
4706 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00004707 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4708 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004709 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4710 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004711 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004712 return RHSTy;
4713 }
4714 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4715 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004716 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4717 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004718 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004719 return LHSTy;
4720 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004721
Chandler Carruth82214a82011-02-18 23:54:50 +00004722 // Emit a better diagnostic if one of the expressions is a null pointer
4723 // constant and the other is not a pointer type. In this case, the user most
4724 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004725 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004726 return QualType();
4727
Chris Lattner70d67a92008-01-06 22:42:25 +00004728 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004729 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004730 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4731 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004732 return QualType();
4733}
4734
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004735/// FindCompositeObjCPointerType - Helper method to find composite type of
4736/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004737QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004738 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004739 QualType LHSTy = LHS.get()->getType();
4740 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004741
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004742 // Handle things like Class and struct objc_class*. Here we case the result
4743 // to the pseudo-builtin, because that will be implicitly cast back to the
4744 // redefinition type if an attempt is made to access its fields.
4745 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004746 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004747 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004748 return LHSTy;
4749 }
4750 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004751 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004752 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004753 return RHSTy;
4754 }
4755 // And the same for struct objc_object* / id
4756 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004757 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004758 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004759 return LHSTy;
4760 }
4761 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004762 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004763 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004764 return RHSTy;
4765 }
4766 // And the same for struct objc_selector* / SEL
4767 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004768 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004769 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004770 return LHSTy;
4771 }
4772 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004773 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004774 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004775 return RHSTy;
4776 }
4777 // Check constraints for Objective-C object pointers types.
4778 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004779
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004780 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4781 // Two identical object pointer types are always compatible.
4782 return LHSTy;
4783 }
4784 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4785 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4786 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004787
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004788 // If both operands are interfaces and either operand can be
4789 // assigned to the other, use that type as the composite
4790 // type. This allows
4791 // xxx ? (A*) a : (B*) b
4792 // where B is a subclass of A.
4793 //
4794 // Additionally, as for assignment, if either type is 'id'
4795 // allow silent coercion. Finally, if the types are
4796 // incompatible then make sure to use 'id' as the composite
4797 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004798
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004799 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4800 // It could return the composite type.
4801 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4802 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4803 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4804 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4805 } else if ((LHSTy->isObjCQualifiedIdType() ||
4806 RHSTy->isObjCQualifiedIdType()) &&
4807 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4808 // Need to handle "id<xx>" explicitly.
4809 // GCC allows qualified id and any Objective-C type to devolve to
4810 // id. Currently localizing to here until clear this should be
4811 // part of ObjCQualifiedIdTypesAreCompatible.
4812 compositeType = Context.getObjCIdType();
4813 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4814 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004815 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004816 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4817 ;
4818 else {
4819 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4820 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004821 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004822 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004823 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4824 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004825 return incompatTy;
4826 }
4827 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004828 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4829 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004830 return compositeType;
4831 }
4832 // Check Objective-C object pointer types and 'void *'
4833 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4834 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4835 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4836 QualType destPointee
4837 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4838 QualType destType = Context.getPointerType(destPointee);
4839 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004840 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004841 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004842 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004843 return destType;
4844 }
4845 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4846 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4847 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4848 QualType destPointee
4849 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4850 QualType destType = Context.getPointerType(destPointee);
4851 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004852 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004853 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004854 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004855 return destType;
4856 }
4857 return QualType();
4858}
4859
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004860/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004861/// ParenRange in parentheses.
4862static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004863 const PartialDiagnostic &Note,
4864 SourceRange ParenRange) {
4865 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4866 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4867 EndLoc.isValid()) {
4868 Self.Diag(Loc, Note)
4869 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4870 << FixItHint::CreateInsertion(EndLoc, ")");
4871 } else {
4872 // We can't display the parentheses, so just show the bare note.
4873 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004874 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004875}
4876
4877static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4878 return Opc >= BO_Mul && Opc <= BO_Shr;
4879}
4880
Hans Wennborg2f072b42011-06-09 17:06:51 +00004881/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4882/// expression, either using a built-in or overloaded operator,
4883/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4884static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4885 Expr **RHS) {
4886 E = E->IgnoreParenImpCasts();
4887 E = E->IgnoreConversionOperator();
4888 E = E->IgnoreParenImpCasts();
4889
4890 // Built-in binary operator.
4891 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4892 if (IsArithmeticOp(OP->getOpcode())) {
4893 *Opcode = OP->getOpcode();
4894 *RHS = OP->getRHS();
4895 return true;
4896 }
4897 }
4898
4899 // Overloaded operator.
4900 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4901 if (Call->getNumArgs() != 2)
4902 return false;
4903
4904 // Make sure this is really a binary operator that is safe to pass into
4905 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4906 OverloadedOperatorKind OO = Call->getOperator();
4907 if (OO < OO_Plus || OO > OO_Arrow)
4908 return false;
4909
4910 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4911 if (IsArithmeticOp(OpKind)) {
4912 *Opcode = OpKind;
4913 *RHS = Call->getArg(1);
4914 return true;
4915 }
4916 }
4917
4918 return false;
4919}
4920
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004921static bool IsLogicOp(BinaryOperatorKind Opc) {
4922 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4923}
4924
Hans Wennborg2f072b42011-06-09 17:06:51 +00004925/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4926/// or is a logical expression such as (x==y) which has int type, but is
4927/// commonly interpreted as boolean.
4928static bool ExprLooksBoolean(Expr *E) {
4929 E = E->IgnoreParenImpCasts();
4930
4931 if (E->getType()->isBooleanType())
4932 return true;
4933 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4934 return IsLogicOp(OP->getOpcode());
4935 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4936 return OP->getOpcode() == UO_LNot;
4937
4938 return false;
4939}
4940
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004941/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4942/// and binary operator are mixed in a way that suggests the programmer assumed
4943/// the conditional operator has higher precedence, for example:
4944/// "int x = a + someBinaryCondition ? 1 : 2".
4945static void DiagnoseConditionalPrecedence(Sema &Self,
4946 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004947 Expr *Condition,
4948 Expr *LHS,
4949 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004950 BinaryOperatorKind CondOpcode;
4951 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004952
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004953 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004954 return;
4955 if (!ExprLooksBoolean(CondRHS))
4956 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004957
Hans Wennborg2f072b42011-06-09 17:06:51 +00004958 // The condition is an arithmetic binary expression, with a right-
4959 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004960
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004961 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004962 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004963 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004964
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004965 SuggestParentheses(Self, OpLoc,
4966 Self.PDiag(diag::note_precedence_conditional_silence)
4967 << BinaryOperator::getOpcodeStr(CondOpcode),
4968 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004969
4970 SuggestParentheses(Self, OpLoc,
4971 Self.PDiag(diag::note_precedence_conditional_first),
4972 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004973}
4974
Steve Narofff69936d2007-09-16 03:34:24 +00004975/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004976/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004977ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004978 SourceLocation ColonLoc,
4979 Expr *CondExpr, Expr *LHSExpr,
4980 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004981 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4982 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004983 OpaqueValueExpr *opaqueValue = 0;
4984 Expr *commonExpr = 0;
4985 if (LHSExpr == 0) {
4986 commonExpr = CondExpr;
4987
4988 // We usually want to apply unary conversions *before* saving, except
4989 // in the special case of a C++ l-value conditional.
4990 if (!(getLangOptions().CPlusPlus
4991 && !commonExpr->isTypeDependent()
4992 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4993 && commonExpr->isGLValue()
4994 && commonExpr->isOrdinaryOrBitFieldObject()
4995 && RHSExpr->isOrdinaryOrBitFieldObject()
4996 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004997 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4998 if (commonRes.isInvalid())
4999 return ExprError();
5000 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005001 }
5002
5003 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5004 commonExpr->getType(),
5005 commonExpr->getValueKind(),
5006 commonExpr->getObjectKind());
5007 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005008 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005009
John McCallf89e55a2010-11-18 06:31:45 +00005010 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005011 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005012 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5013 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005014 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005015 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5016 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005017 return ExprError();
5018
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005019 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5020 RHS.get());
5021
John McCall56ca35d2011-02-17 10:25:35 +00005022 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005023 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5024 LHS.take(), ColonLoc,
5025 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005026
5027 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005028 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005029 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5030 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005031}
5032
John McCalle4be87e2011-01-31 23:13:11 +00005033// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005034// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005035// routine is it effectively iqnores the qualifiers on the top level pointee.
5036// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5037// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005038static Sema::AssignConvertType
5039checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5040 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5041 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005042
Reid Spencer5f016e22007-07-11 17:01:13 +00005043 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005044 const Type *lhptee, *rhptee;
5045 Qualifiers lhq, rhq;
5046 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5047 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005048
John McCalle4be87e2011-01-31 23:13:11 +00005049 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005050
5051 // C99 6.5.16.1p1: This following citation is common to constraints
5052 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5053 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005054 Qualifiers lq;
5055
John McCallf85e1932011-06-15 23:02:42 +00005056 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5057 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5058 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5059 // Ignore lifetime for further calculation.
5060 lhq.removeObjCLifetime();
5061 rhq.removeObjCLifetime();
5062 }
5063
John McCall86c05f32011-02-01 00:10:29 +00005064 if (!lhq.compatiblyIncludes(rhq)) {
5065 // Treat address-space mismatches as fatal. TODO: address subspaces
5066 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5067 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5068
John McCallf85e1932011-06-15 23:02:42 +00005069 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005070 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005071 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5072 .compatiblyIncludes(
5073 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005074 && (lhptee->isVoidType() || rhptee->isVoidType()))
5075 ; // keep old
5076
John McCallf85e1932011-06-15 23:02:42 +00005077 // Treat lifetime mismatches as fatal.
5078 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5079 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5080
John McCall86c05f32011-02-01 00:10:29 +00005081 // For GCC compatibility, other qualifier mismatches are treated
5082 // as still compatible in C.
5083 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5084 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005085
Mike Stumpeed9cac2009-02-19 03:04:26 +00005086 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5087 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005088 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005089 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005090 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005091 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005092
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005093 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005094 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005095 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005096 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005097
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005098 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005099 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005100 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005101
5102 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005103 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005104 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005105 }
John McCall86c05f32011-02-01 00:10:29 +00005106
Mike Stumpeed9cac2009-02-19 03:04:26 +00005107 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005108 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005109 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5110 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005111 // Check if the pointee types are compatible ignoring the sign.
5112 // We explicitly check for char so that we catch "char" vs
5113 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005114 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005115 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005116 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005117 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005118
Chris Lattner6a2b9262009-10-17 20:33:28 +00005119 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005120 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005121 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005122 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005123
John McCall86c05f32011-02-01 00:10:29 +00005124 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005125 // Types are compatible ignoring the sign. Qualifier incompatibility
5126 // takes priority over sign incompatibility because the sign
5127 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005128 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005129 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005130
John McCalle4be87e2011-01-31 23:13:11 +00005131 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005132 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005133
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005134 // If we are a multi-level pointer, it's possible that our issue is simply
5135 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5136 // the eventual target type is the same and the pointers have the same
5137 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005138 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005139 do {
John McCall86c05f32011-02-01 00:10:29 +00005140 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5141 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005142 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005143
John McCall86c05f32011-02-01 00:10:29 +00005144 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005145 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005146 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005147
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005148 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005149 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005150 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005151 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005152}
5153
John McCalle4be87e2011-01-31 23:13:11 +00005154/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005155/// block pointer types are compatible or whether a block and normal pointer
5156/// are compatible. It is more restrict than comparing two function pointer
5157// types.
John McCalle4be87e2011-01-31 23:13:11 +00005158static Sema::AssignConvertType
5159checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5160 QualType rhsType) {
5161 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5162 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5163
Steve Naroff1c7d0672008-09-04 15:10:53 +00005164 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005165
Steve Naroff1c7d0672008-09-04 15:10:53 +00005166 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005167 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5168 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005169
John McCalle4be87e2011-01-31 23:13:11 +00005170 // In C++, the types have to match exactly.
5171 if (S.getLangOptions().CPlusPlus)
5172 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005173
John McCalle4be87e2011-01-31 23:13:11 +00005174 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005175
Steve Naroff1c7d0672008-09-04 15:10:53 +00005176 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005177 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5178 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005179
John McCalle4be87e2011-01-31 23:13:11 +00005180 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5181 return Sema::IncompatibleBlockPointer;
5182
Steve Naroff1c7d0672008-09-04 15:10:53 +00005183 return ConvTy;
5184}
5185
John McCalle4be87e2011-01-31 23:13:11 +00005186/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005187/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005188static Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005189checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5190 QualType rhsType) {
John McCalle4be87e2011-01-31 23:13:11 +00005191 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5192 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5193
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005194 if (lhsType->isObjCBuiltinType()) {
5195 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005196 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5197 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005198 return Sema::IncompatiblePointer;
5199 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005200 }
5201 if (rhsType->isObjCBuiltinType()) {
5202 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005203 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5204 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005205 return Sema::IncompatiblePointer;
5206 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005207 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005208 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005209 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005210 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005211 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005212
John McCalle4be87e2011-01-31 23:13:11 +00005213 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5214 return Sema::CompatiblePointerDiscardsQualifiers;
5215
5216 if (S.Context.typesAreCompatible(lhsType, rhsType))
5217 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005218 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005219 return Sema::IncompatibleObjCQualifiedId;
5220 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005221}
5222
John McCall1c23e912010-11-16 02:32:08 +00005223Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005224Sema::CheckAssignmentConstraints(SourceLocation Loc,
5225 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005226 // Fake up an opaque expression. We don't actually care about what
5227 // cast operations are required, so if CheckAssignmentConstraints
5228 // adds casts to this they'll be wasted, but fortunately that doesn't
5229 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005230 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005231 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005232 CastKind K = CK_Invalid;
5233
5234 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5235}
5236
Mike Stumpeed9cac2009-02-19 03:04:26 +00005237/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5238/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005239/// pointers. Here are some objectionable examples that GCC considers warnings:
5240///
5241/// int a, *pint;
5242/// short *pshort;
5243/// struct foo *pfoo;
5244///
5245/// pint = pshort; // warning: assignment from incompatible pointer type
5246/// a = pint; // warning: assignment makes integer from pointer without a cast
5247/// pint = a; // warning: assignment makes pointer from integer without a cast
5248/// pint = pfoo; // warning: assignment from incompatible pointer type
5249///
5250/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005251/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005252///
John McCalldaa8e4e2010-11-15 09:13:47 +00005253/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005254Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005255Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005256 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005257 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005258 QualType origLhsType = lhsType;
John McCall1c23e912010-11-16 02:32:08 +00005259
Chris Lattnerfc144e22008-01-04 23:18:45 +00005260 // Get canonical types. We're not formatting these types, just comparing
5261 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005262 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5263 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005264
John McCallb6cfa242011-01-31 22:28:28 +00005265 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005266 if (lhsType == rhsType) {
5267 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005268 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005269 }
5270
Douglas Gregor9d293df2008-10-28 00:22:11 +00005271 // If the left-hand side is a reference type, then we are in a
5272 // (rare!) case where we've allowed the use of references in C,
5273 // e.g., as a parameter type in a built-in function. In this case,
5274 // just make sure that the type referenced is compatible with the
5275 // right-hand side type. The caller is responsible for adjusting
5276 // lhsType so that the resulting expression does not have reference
5277 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005278 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005279 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5280 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005281 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005282 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005283 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005284 }
John McCallb6cfa242011-01-31 22:28:28 +00005285
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005286 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5287 // to the same ExtVector type.
5288 if (lhsType->isExtVectorType()) {
5289 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005290 return Incompatible;
5291 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005292 // CK_VectorSplat does T -> vector T, so first cast to the
5293 // element type.
5294 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5295 if (elType != rhsType) {
5296 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005297 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005298 }
5299 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005300 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005301 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
John McCallb6cfa242011-01-31 22:28:28 +00005304 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005305 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005306 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005307 // Allow assignments of an AltiVec vector type to an equivalent GCC
5308 // vector type and vice versa
5309 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5310 Kind = CK_BitCast;
5311 return Compatible;
5312 }
5313
Douglas Gregor255210e2010-08-06 10:14:59 +00005314 // If we are allowing lax vector conversions, and LHS and RHS are both
5315 // vectors, the total size only needs to be the same. This is a bitcast;
5316 // no bits are changed but the result type is different.
5317 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005318 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005319 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005320 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005321 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005322 }
5323 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005324 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005325
John McCallb6cfa242011-01-31 22:28:28 +00005326 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005327 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005328 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005329 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005330 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005331 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005332
John McCallb6cfa242011-01-31 22:28:28 +00005333 // Conversions to normal pointers.
5334 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5335 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005336 if (isa<PointerType>(rhsType)) {
5337 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005338 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005339 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005340
John McCallb6cfa242011-01-31 22:28:28 +00005341 // int -> T*
5342 if (rhsType->isIntegerType()) {
5343 Kind = CK_IntegralToPointer; // FIXME: null?
5344 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005345 }
John McCallb6cfa242011-01-31 22:28:28 +00005346
5347 // C pointers are not compatible with ObjC object pointers,
5348 // with two exceptions:
5349 if (isa<ObjCObjectPointerType>(rhsType)) {
5350 // - conversions to void*
5351 if (lhsPointer->getPointeeType()->isVoidType()) {
5352 Kind = CK_AnyPointerToObjCPointerCast;
5353 return Compatible;
5354 }
5355
5356 // - conversions from 'Class' to the redefinition type
5357 if (rhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005358 Context.hasSameType(lhsType,
5359 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005360 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005361 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 }
Steve Naroffb4406862008-09-29 18:10:17 +00005363
John McCallb6cfa242011-01-31 22:28:28 +00005364 Kind = CK_BitCast;
5365 return IncompatiblePointer;
5366 }
5367
5368 // U^ -> void*
5369 if (rhsType->getAs<BlockPointerType>()) {
5370 if (lhsPointer->getPointeeType()->isVoidType()) {
5371 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005372 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005373 }
Steve Naroffb4406862008-09-29 18:10:17 +00005374 }
John McCallb6cfa242011-01-31 22:28:28 +00005375
Steve Naroff1c7d0672008-09-04 15:10:53 +00005376 return Incompatible;
5377 }
5378
John McCallb6cfa242011-01-31 22:28:28 +00005379 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005380 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005381 // U^ -> T^
5382 if (rhsType->isBlockPointerType()) {
5383 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005384 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005385 }
5386
5387 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005388 if (rhsType->isIntegerType()) {
5389 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005390 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005391 }
5392
John McCallb6cfa242011-01-31 22:28:28 +00005393 // id -> T^
5394 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5395 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005396 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005397 }
Steve Naroffb4406862008-09-29 18:10:17 +00005398
John McCallb6cfa242011-01-31 22:28:28 +00005399 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005400 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005401 if (RHSPT->getPointeeType()->isVoidType()) {
5402 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005403 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005404 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005405
Chris Lattnerfc144e22008-01-04 23:18:45 +00005406 return Incompatible;
5407 }
5408
John McCallb6cfa242011-01-31 22:28:28 +00005409 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005410 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005411 // A* -> B*
5412 if (rhsType->isObjCObjectPointerType()) {
5413 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005414 Sema::AssignConvertType result =
5415 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5416 if (getLangOptions().ObjCAutoRefCount &&
5417 result == Compatible &&
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005418 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5419 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005420 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005421 }
5422
5423 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005424 if (rhsType->isIntegerType()) {
5425 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005426 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005427 }
5428
John McCallb6cfa242011-01-31 22:28:28 +00005429 // In general, C pointers are not compatible with ObjC object pointers,
5430 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005431 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005432 // - conversions from 'void*'
5433 if (rhsType->isVoidPointerType()) {
5434 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005435 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005436 }
5437
5438 // - conversions to 'Class' from its redefinition type
5439 if (lhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005440 Context.hasSameType(rhsType,
5441 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005442 Kind = CK_BitCast;
5443 return Compatible;
5444 }
5445
5446 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005447 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005448 }
John McCallb6cfa242011-01-31 22:28:28 +00005449
5450 // T^ -> A*
5451 if (rhsType->isBlockPointerType()) {
5452 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005453 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005454 }
5455
Steve Naroff14108da2009-07-10 23:34:53 +00005456 return Incompatible;
5457 }
John McCallb6cfa242011-01-31 22:28:28 +00005458
5459 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005460 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005461 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005462 if (lhsType == Context.BoolTy) {
5463 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005464 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005465 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005466
John McCallb6cfa242011-01-31 22:28:28 +00005467 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005468 if (lhsType->isIntegerType()) {
5469 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005470 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005471 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005472
Chris Lattnerfc144e22008-01-04 23:18:45 +00005473 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005474 }
John McCallb6cfa242011-01-31 22:28:28 +00005475
5476 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005477 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005478 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005479 if (lhsType == Context.BoolTy) {
5480 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005481 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005482 }
Steve Naroff14108da2009-07-10 23:34:53 +00005483
John McCallb6cfa242011-01-31 22:28:28 +00005484 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005485 if (lhsType->isIntegerType()) {
5486 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005487 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005488 }
5489
Steve Naroff14108da2009-07-10 23:34:53 +00005490 return Incompatible;
5491 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005492
John McCallb6cfa242011-01-31 22:28:28 +00005493 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005494 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005495 if (Context.typesAreCompatible(lhsType, rhsType)) {
5496 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005497 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005498 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005499 }
John McCallb6cfa242011-01-31 22:28:28 +00005500
Reid Spencer5f016e22007-07-11 17:01:13 +00005501 return Incompatible;
5502}
5503
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005504/// \brief Constructs a transparent union from an expression that is
5505/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005506static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5507 ExprResult &EResult, QualType UnionType,
5508 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005509 // Build an initializer list that designates the appropriate member
5510 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005511 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005512 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005513 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005514 SourceLocation());
5515 Initializer->setType(UnionType);
5516 Initializer->setInitializedFieldInUnion(Field);
5517
5518 // Build a compound literal constructing a value of the transparent
5519 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005520 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005521 EResult = S.Owned(
5522 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5523 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005524}
5525
5526Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005527Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5528 ExprResult &rExpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005529 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005530
Mike Stump1eb44332009-09-09 15:08:12 +00005531 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005532 // transparent_union GCC extension.
5533 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005534 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005535 return Incompatible;
5536
5537 // The field to initialize within the transparent union.
5538 RecordDecl *UD = UT->getDecl();
5539 FieldDecl *InitField = 0;
5540 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005541 for (RecordDecl::field_iterator it = UD->field_begin(),
5542 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005543 it != itend; ++it) {
5544 if (it->getType()->isPointerType()) {
5545 // If the transparent union contains a pointer type, we allow:
5546 // 1) void pointer
5547 // 2) null pointer constant
5548 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005549 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005550 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005551 InitField = *it;
5552 break;
5553 }
Mike Stump1eb44332009-09-09 15:08:12 +00005554
John Wiegley429bb272011-04-08 18:41:53 +00005555 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005556 Expr::NPC_ValueDependentIsNull)) {
Richard Trieu67e29332011-08-02 04:35:43 +00005557 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5558 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005559 InitField = *it;
5560 break;
5561 }
5562 }
5563
John McCalldaa8e4e2010-11-15 09:13:47 +00005564 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005565 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005566 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005567 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005568 InitField = *it;
5569 break;
5570 }
5571 }
5572
5573 if (!InitField)
5574 return Incompatible;
5575
John Wiegley429bb272011-04-08 18:41:53 +00005576 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005577 return Compatible;
5578}
5579
Chris Lattner5cf216b2008-01-04 18:04:52 +00005580Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005581Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005582 if (getLangOptions().CPlusPlus) {
5583 if (!lhsType->isRecordType()) {
5584 // C++ 5.17p3: If the left operand is not of class type, the
5585 // expression is implicitly converted (C++ 4) to the
5586 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005587 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5588 lhsType.getUnqualifiedType(),
5589 AA_Assigning);
5590 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005591 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005592 Sema::AssignConvertType result = Compatible;
5593 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieu67e29332011-08-02 04:35:43 +00005594 !CheckObjCARCUnavailableWeakConversion(lhsType,
5595 rExpr.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005596 result = IncompatibleObjCWeakRef;
John Wiegley429bb272011-04-08 18:41:53 +00005597 rExpr = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005598 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005599 }
5600
5601 // FIXME: Currently, we fall through and treat C++ classes like C
5602 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005603 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005604
Steve Naroff529a4ad2007-11-27 17:58:44 +00005605 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5606 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005607 if ((lhsType->isPointerType() ||
5608 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005609 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005610 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005611 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005612 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005613 return Compatible;
5614 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005615
Chris Lattner943140e2007-10-16 02:55:40 +00005616 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005617 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005618 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005619 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005620 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005621 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005622 if (!lhsType->isReferenceType()) {
5623 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5624 if (rExpr.isInvalid())
5625 return Incompatible;
5626 }
Steve Narofff1120de2007-08-24 22:33:52 +00005627
John McCalldaa8e4e2010-11-15 09:13:47 +00005628 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005629 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005630 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005631
Steve Narofff1120de2007-08-24 22:33:52 +00005632 // C99 6.5.16.1p2: The value of the right operand is converted to the
5633 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005634 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5635 // so that we can use references in built-in functions even in C.
5636 // The getNonReferenceType() call makes sure that the resulting expression
5637 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005638 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieu67e29332011-08-02 04:35:43 +00005639 rExpr = ImpCastExprToType(rExpr.take(),
5640 lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005641 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005642}
5643
Richard Trieu67e29332011-08-02 04:35:43 +00005644QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5645 ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005646 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005647 << lex.get()->getType() << rex.get()->getType()
5648 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005649 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005650}
5651
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005652QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5653 SourceLocation Loc, bool isCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005654 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005655 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005656 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005657 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005658 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005659 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005660
Nate Begemanbe2341d2008-07-14 18:02:46 +00005661 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005662 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005663 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005664
Douglas Gregor255210e2010-08-06 10:14:59 +00005665 // Handle the case of equivalent AltiVec and GCC vector types
5666 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5667 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005668 if (lhsType->isExtVectorType()) {
5669 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5670 return lhsType;
5671 }
5672
5673 if (!isCompAssign)
5674 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005675 return rhsType;
5676 }
5677
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005678 if (getLangOptions().LaxVectorConversions &&
5679 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5680 // If we are allowing lax vector conversions, and LHS and RHS are both
5681 // vectors, the total size only needs to be the same. This is a
5682 // bitcast; no bits are changed but the result type is different.
5683 // FIXME: Should we really be allowing this?
5684 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5685 return lhsType;
5686 }
5687
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005688 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5689 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5690 bool swapped = false;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005691 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005692 swapped = true;
5693 std::swap(rex, lex);
5694 std::swap(rhsType, lhsType);
5695 }
Mike Stump1eb44332009-09-09 15:08:12 +00005696
Nate Begemandde25982009-06-28 19:12:57 +00005697 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005698 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005699 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005700 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005701 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5702 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005703 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005704 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005705 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005706 if (swapped) std::swap(rex, lex);
5707 return lhsType;
5708 }
5709 }
5710 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5711 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005712 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5713 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005714 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005715 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005716 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005717 if (swapped) std::swap(rex, lex);
5718 return lhsType;
5719 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005720 }
5721 }
Mike Stump1eb44332009-09-09 15:08:12 +00005722
Nate Begemandde25982009-06-28 19:12:57 +00005723 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005724 if (swapped) std::swap(rex, lex);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005725 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005726 << lex.get()->getType() << rex.get()->getType()
5727 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005728 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005729}
5730
Richard Trieu67e29332011-08-02 04:35:43 +00005731QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5732 SourceLocation Loc,
5733 bool isCompAssign, bool isDiv) {
5734 if (lex.get()->getType()->isVectorType() ||
5735 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005736 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005737
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005738 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005739 if (lex.isInvalid() || rex.isInvalid())
5740 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005741
John Wiegley429bb272011-04-08 18:41:53 +00005742 if (!lex.get()->getType()->isArithmeticType() ||
5743 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005744 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005745
Chris Lattner7ef655a2010-01-12 21:23:57 +00005746 // Check for division by zero.
5747 if (isDiv &&
Richard Trieu67e29332011-08-02 04:35:43 +00005748 rex.get()->isNullPointerConstant(Context,
5749 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005750 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieu67e29332011-08-02 04:35:43 +00005751 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005752
Chris Lattner7ef655a2010-01-12 21:23:57 +00005753 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005754}
5755
Chris Lattner7ef655a2010-01-12 21:23:57 +00005756QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005757 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00005758 if (lex.get()->getType()->isVectorType() ||
5759 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005760 if (lex.get()->getType()->hasIntegerRepresentation() &&
5761 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005762 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005763 return InvalidOperands(Loc, lex, rex);
5764 }
Steve Naroff90045e82007-07-13 23:32:42 +00005765
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005766 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005767 if (lex.isInvalid() || rex.isInvalid())
5768 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769
Richard Trieu67e29332011-08-02 04:35:43 +00005770 if (!lex.get()->getType()->isIntegerType() ||
5771 !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005772 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005773
Chris Lattner7ef655a2010-01-12 21:23:57 +00005774 // Check for remainder by zero.
Richard Trieu67e29332011-08-02 04:35:43 +00005775 if (rex.get()->isNullPointerConstant(Context,
5776 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005777 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5778 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005779
Chris Lattner7ef655a2010-01-12 21:23:57 +00005780 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005781}
5782
Chandler Carruth13b21be2011-06-27 08:02:19 +00005783/// \brief Diagnose invalid arithmetic on two void pointers.
5784static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5785 Expr *LHS, Expr *RHS) {
5786 S.Diag(Loc, S.getLangOptions().CPlusPlus
5787 ? diag::err_typecheck_pointer_arith_void_type
5788 : diag::ext_gnu_void_ptr)
5789 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5790}
5791
5792/// \brief Diagnose invalid arithmetic on a void pointer.
5793static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5794 Expr *Pointer) {
5795 S.Diag(Loc, S.getLangOptions().CPlusPlus
5796 ? diag::err_typecheck_pointer_arith_void_type
5797 : diag::ext_gnu_void_ptr)
5798 << 0 /* one pointer */ << Pointer->getSourceRange();
5799}
5800
5801/// \brief Diagnose invalid arithmetic on two function pointers.
5802static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5803 Expr *LHS, Expr *RHS) {
5804 assert(LHS->getType()->isAnyPointerType());
5805 assert(RHS->getType()->isAnyPointerType());
5806 S.Diag(Loc, S.getLangOptions().CPlusPlus
5807 ? diag::err_typecheck_pointer_arith_function_type
5808 : diag::ext_gnu_ptr_func_arith)
5809 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5810 // We only show the second type if it differs from the first.
5811 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5812 RHS->getType())
5813 << RHS->getType()->getPointeeType()
5814 << LHS->getSourceRange() << RHS->getSourceRange();
5815}
5816
5817/// \brief Diagnose invalid arithmetic on a function pointer.
5818static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5819 Expr *Pointer) {
5820 assert(Pointer->getType()->isAnyPointerType());
5821 S.Diag(Loc, S.getLangOptions().CPlusPlus
5822 ? diag::err_typecheck_pointer_arith_function_type
5823 : diag::ext_gnu_ptr_func_arith)
5824 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5825 << 0 /* one pointer, so only one type */
5826 << Pointer->getSourceRange();
5827}
5828
5829/// \brief Check the validity of an arithmetic pointer operand.
5830///
5831/// If the operand has pointer type, this code will check for pointer types
5832/// which are invalid in arithmetic operations. These will be diagnosed
5833/// appropriately, including whether or not the use is supported as an
5834/// extension.
5835///
5836/// \returns True when the operand is valid to use (even if as an extension).
5837static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5838 Expr *Operand) {
5839 if (!Operand->getType()->isAnyPointerType()) return true;
5840
5841 QualType PointeeTy = Operand->getType()->getPointeeType();
5842 if (PointeeTy->isVoidType()) {
5843 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5844 return !S.getLangOptions().CPlusPlus;
5845 }
5846 if (PointeeTy->isFunctionType()) {
5847 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5848 return !S.getLangOptions().CPlusPlus;
5849 }
5850
5851 if ((Operand->getType()->isPointerType() &&
5852 !Operand->getType()->isDependentType()) ||
5853 Operand->getType()->isObjCObjectPointerType()) {
5854 QualType PointeeTy = Operand->getType()->getPointeeType();
5855 if (S.RequireCompleteType(
5856 Loc, PointeeTy,
5857 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5858 << PointeeTy << Operand->getSourceRange()))
5859 return false;
5860 }
5861
5862 return true;
5863}
5864
5865/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5866/// operands.
5867///
5868/// This routine will diagnose any invalid arithmetic on pointer operands much
5869/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5870/// for emitting a single diagnostic even for operations where both LHS and RHS
5871/// are (potentially problematic) pointers.
5872///
5873/// \returns True when the operand is valid to use (even if as an extension).
5874static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5875 Expr *LHS, Expr *RHS) {
5876 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5877 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5878 if (!isLHSPointer && !isRHSPointer) return true;
5879
5880 QualType LHSPointeeTy, RHSPointeeTy;
5881 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5882 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5883
5884 // Check for arithmetic on pointers to incomplete types.
5885 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5886 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5887 if (isLHSVoidPtr || isRHSVoidPtr) {
5888 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5889 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5890 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5891
5892 return !S.getLangOptions().CPlusPlus;
5893 }
5894
5895 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5896 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5897 if (isLHSFuncPtr || isRHSFuncPtr) {
5898 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5899 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5900 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5901
5902 return !S.getLangOptions().CPlusPlus;
5903 }
5904
5905 Expr *Operands[] = { LHS, RHS };
5906 for (unsigned i = 0; i < 2; ++i) {
5907 Expr *Operand = Operands[i];
5908 if ((Operand->getType()->isPointerType() &&
5909 !Operand->getType()->isDependentType()) ||
5910 Operand->getType()->isObjCObjectPointerType()) {
5911 QualType PointeeTy = Operand->getType()->getPointeeType();
5912 if (S.RequireCompleteType(
5913 Loc, PointeeTy,
5914 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5915 << PointeeTy << Operand->getSourceRange()))
5916 return false;
5917 }
5918 }
5919 return true;
5920}
5921
Chris Lattner7ef655a2010-01-12 21:23:57 +00005922QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005923 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu67e29332011-08-02 04:35:43 +00005924 if (lex.get()->getType()->isVectorType() ||
5925 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005926 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005927 if (CompLHSTy) *CompLHSTy = compType;
5928 return compType;
5929 }
Steve Naroff49b45262007-07-13 16:58:59 +00005930
Eli Friedmanab3a8522009-03-28 01:22:36 +00005931 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005932 if (lex.isInvalid() || rex.isInvalid())
5933 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005934
Reid Spencer5f016e22007-07-11 17:01:13 +00005935 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005936 if (lex.get()->getType()->isArithmeticType() &&
5937 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005938 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005939 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005940 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005941
Eli Friedmand72d16e2008-05-18 18:08:51 +00005942 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005943 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005944 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005945 std::swap(PExp, IExp);
5946
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005947 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005948 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005949 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5950 return QualType();
5951
Steve Naroff760e3c42009-07-13 21:20:41 +00005952 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005953
Chris Lattnerb5f15622009-04-24 23:50:08 +00005954 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005955 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005956 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5957 << PointeeTy << PExp->getSourceRange();
5958 return QualType();
5959 }
Mike Stump1eb44332009-09-09 15:08:12 +00005960
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005961 // Check array bounds for pointer arithemtic
5962 CheckArrayAccess(PExp, IExp);
5963
Eli Friedmanab3a8522009-03-28 01:22:36 +00005964 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005965 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005966 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005967 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005968 if (LHSTy->isPromotableIntegerType())
5969 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005970 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005971 *CompLHSTy = LHSTy;
5972 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005973 return PExp->getType();
5974 }
5975 }
5976
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005977 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005978}
5979
Chris Lattnereca7be62008-04-07 05:30:13 +00005980// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005981QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieu67e29332011-08-02 04:35:43 +00005982 SourceLocation Loc,
5983 QualType* CompLHSTy) {
5984 if (lex.get()->getType()->isVectorType() ||
5985 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005986 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005987 if (CompLHSTy) *CompLHSTy = compType;
5988 return compType;
5989 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005990
Eli Friedmanab3a8522009-03-28 01:22:36 +00005991 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005992 if (lex.isInvalid() || rex.isInvalid())
5993 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005994
Chris Lattner6e4ab612007-12-09 21:53:25 +00005995 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005996
Chris Lattner6e4ab612007-12-09 21:53:25 +00005997 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005998 if (lex.get()->getType()->isArithmeticType() &&
5999 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006000 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006001 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006002 }
Mike Stump1eb44332009-09-09 15:08:12 +00006003
Chris Lattner6e4ab612007-12-09 21:53:25 +00006004 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006005 if (lex.get()->getType()->isAnyPointerType()) {
6006 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006007
Chris Lattnerb5f15622009-04-24 23:50:08 +00006008 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006009 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006010 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00006011 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006012 return QualType();
6013 }
Mike Stump1eb44332009-09-09 15:08:12 +00006014
Chris Lattner6e4ab612007-12-09 21:53:25 +00006015 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00006016 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00006017 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6018 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006019
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006020 Expr *IExpr = rex.get()->IgnoreParenCasts();
6021 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6022 OK_Ordinary, IExpr->getExprLoc());
6023 // Check array bounds for pointer arithemtic
6024 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6025
John Wiegley429bb272011-04-08 18:41:53 +00006026 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6027 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006028 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006029
Chris Lattner6e4ab612007-12-09 21:53:25 +00006030 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006031 if (const PointerType *RHSPTy
6032 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006033 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006034
Eli Friedman88d936b2009-05-16 13:54:38 +00006035 if (getLangOptions().CPlusPlus) {
6036 // Pointee types must be the same: C++ [expr.add]
6037 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6038 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006039 << lex.get()->getType() << rex.get()->getType()
6040 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006041 return QualType();
6042 }
6043 } else {
6044 // Pointee types must be compatible C99 6.5.6p3
6045 if (!Context.typesAreCompatible(
6046 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6047 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6048 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006049 << lex.get()->getType() << rex.get()->getType()
6050 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006051 return QualType();
6052 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006053 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006054
Chandler Carruth13b21be2011-06-27 08:02:19 +00006055 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6056 lex.get(), rex.get()))
6057 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006058
John Wiegley429bb272011-04-08 18:41:53 +00006059 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006060 return Context.getPointerDiffType();
6061 }
6062 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006063
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006064 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006065}
6066
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006067static bool isScopedEnumerationType(QualType T) {
6068 if (const EnumType *ET = dyn_cast<EnumType>(T))
6069 return ET->getDecl()->isScoped();
6070 return false;
6071}
6072
John Wiegley429bb272011-04-08 18:41:53 +00006073static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006074 SourceLocation Loc, unsigned Opc,
6075 QualType LHSTy) {
6076 llvm::APSInt Right;
6077 // Check right/shifter operand
Richard Trieu67e29332011-08-02 04:35:43 +00006078 if (rex.get()->isValueDependent() ||
6079 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006080 return;
6081
6082 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006083 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006084 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006085 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006086 return;
6087 }
6088 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006089 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006090 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006091 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006092 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006093 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006094 return;
6095 }
6096 if (Opc != BO_Shl)
6097 return;
6098
6099 // When left shifting an ICE which is signed, we can check for overflow which
6100 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6101 // integers have defined behavior modulo one more than the maximum value
6102 // representable in the result type, so never warn for those.
6103 llvm::APSInt Left;
Richard Trieu67e29332011-08-02 04:35:43 +00006104 if (lex.get()->isValueDependent() ||
6105 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006106 LHSTy->hasUnsignedIntegerRepresentation())
6107 return;
6108 llvm::APInt ResultBits =
6109 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6110 if (LeftBits.uge(ResultBits))
6111 return;
6112 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6113 Result = Result.shl(Right);
6114
Ted Kremenekfa821382011-06-15 00:54:52 +00006115 // Print the bit representation of the signed integer as an unsigned
6116 // hexadecimal number.
6117 llvm::SmallString<40> HexResult;
6118 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6119
Chandler Carruth21206d52011-02-23 23:34:11 +00006120 // If we are only missing a sign bit, this is less likely to result in actual
6121 // bugs -- if the result is cast back to an unsigned type, it will have the
6122 // expected value. Thus we place this behind a different warning that can be
6123 // turned off separately if needed.
6124 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006125 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6126 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006127 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006128 return;
6129 }
6130
6131 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00006132 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieu67e29332011-08-02 04:35:43 +00006133 << Left.getBitWidth() << lex.get()->getSourceRange()
6134 << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006135}
6136
Chris Lattnereca7be62008-04-07 05:30:13 +00006137// C99 6.5.7
Richard Trieu67e29332011-08-02 04:35:43 +00006138QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6139 SourceLocation Loc, unsigned Opc,
6140 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006141 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00006142 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6143 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006144 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006145
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006146 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6147 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00006148 if (isScopedEnumerationType(lex.get()->getType()) ||
6149 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006150 return InvalidOperands(Loc, lex, rex);
6151 }
6152
Nate Begeman2207d792009-10-25 02:26:48 +00006153 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu67e29332011-08-02 04:35:43 +00006154 if (lex.get()->getType()->isVectorType() ||
6155 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006156 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006157
Chris Lattnerca5eede2007-12-12 05:47:28 +00006158 // Shifts don't perform usual arithmetic conversions, they just do integer
6159 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006160
John McCall1bc80af2010-12-16 19:28:59 +00006161 // For the LHS, do usual unary conversions, but then reset them away
6162 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00006163 ExprResult old_lex = lex;
6164 lex = UsualUnaryConversions(lex.take());
6165 if (lex.isInvalid())
6166 return QualType();
6167 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00006168 if (isCompAssign) lex = old_lex;
6169
6170 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00006171 rex = UsualUnaryConversions(rex.take());
6172 if (rex.isInvalid())
6173 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006174
Ryan Flynnd0439682009-08-07 16:20:20 +00006175 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006176 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006177
Chris Lattnerca5eede2007-12-12 05:47:28 +00006178 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006179 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006180}
6181
Chandler Carruth99919472010-07-10 12:30:03 +00006182static bool IsWithinTemplateSpecialization(Decl *D) {
6183 if (DeclContext *DC = D->getDeclContext()) {
6184 if (isa<ClassTemplateSpecializationDecl>(DC))
6185 return true;
6186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6187 return FD->isFunctionTemplateSpecialization();
6188 }
6189 return false;
6190}
6191
Douglas Gregor0c6db942009-05-04 06:07:12 +00006192// C99 6.5.8, C++ [expr.rel]
Richard Trieu67e29332011-08-02 04:35:43 +00006193QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6194 SourceLocation Loc, unsigned OpaqueOpc,
6195 bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006196 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006197
Chris Lattner02dd4b12009-12-05 05:40:13 +00006198 // Handle vector comparisons separately.
Richard Trieu67e29332011-08-02 04:35:43 +00006199 if (lex.get()->getType()->isVectorType() ||
6200 rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006201 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006202
John Wiegley429bb272011-04-08 18:41:53 +00006203 QualType lType = lex.get()->getType();
6204 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006205
John Wiegley429bb272011-04-08 18:41:53 +00006206 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6207 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006208 QualType LHSStrippedType = LHSStripped->getType();
6209 QualType RHSStrippedType = RHSStripped->getType();
6210
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006211
6212
Chandler Carruth543cb652011-02-17 08:37:06 +00006213 // Two different enums will raise a warning when compared.
6214 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6215 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6216 if (LHSEnumType->getDecl()->getIdentifier() &&
6217 RHSEnumType->getDecl()->getIdentifier() &&
6218 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6219 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6220 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00006221 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00006222 }
6223 }
6224 }
6225
Douglas Gregor8eee1192010-06-22 22:12:46 +00006226 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006227 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00006228 !lex.get()->getLocStart().isMacroID() &&
6229 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006230 // For non-floating point types, check for self-comparisons of the form
6231 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6232 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006233 //
6234 // NOTE: Don't warn about comparison expressions resulting from macro
6235 // expansion. Also don't warn about comparisons which are only self
6236 // comparisons within a template specialization. The warnings should catch
6237 // obvious cases in the definition of the template anyways. The idea is to
6238 // warn when the typed comparison operator will always evaluate to the same
6239 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006240 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006241 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006242 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006243 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006244 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006245 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006246 << (Opc == BO_EQ
6247 || Opc == BO_LE
6248 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006249 } else if (lType->isArrayType() && rType->isArrayType() &&
6250 !DRL->getDecl()->getType()->isReferenceType() &&
6251 !DRR->getDecl()->getType()->isReferenceType()) {
6252 // what is it always going to eval to?
6253 char always_evals_to;
6254 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006255 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006256 always_evals_to = 0; // false
6257 break;
John McCall2de56d12010-08-25 11:45:40 +00006258 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006259 always_evals_to = 1; // true
6260 break;
6261 default:
6262 // best we can say is 'a constant'
6263 always_evals_to = 2; // e.g. array1 <= array2
6264 break;
6265 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006266 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006267 << 1 // array
6268 << always_evals_to);
6269 }
6270 }
Chandler Carruth99919472010-07-10 12:30:03 +00006271 }
Mike Stump1eb44332009-09-09 15:08:12 +00006272
Chris Lattner55660a72009-03-08 19:39:53 +00006273 if (isa<CastExpr>(LHSStripped))
6274 LHSStripped = LHSStripped->IgnoreParenCasts();
6275 if (isa<CastExpr>(RHSStripped))
6276 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Chris Lattner55660a72009-03-08 19:39:53 +00006278 // Warn about comparisons against a string constant (unless the other
6279 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006280 Expr *literalString = 0;
6281 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006282 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006283 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006284 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006285 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006286 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006287 } else if ((isa<StringLiteral>(RHSStripped) ||
6288 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006289 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006290 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006291 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006292 literalStringStripped = RHSStripped;
6293 }
6294
6295 if (literalString) {
6296 std::string resultComparison;
6297 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006298 case BO_LT: resultComparison = ") < 0"; break;
6299 case BO_GT: resultComparison = ") > 0"; break;
6300 case BO_LE: resultComparison = ") <= 0"; break;
6301 case BO_GE: resultComparison = ") >= 0"; break;
6302 case BO_EQ: resultComparison = ") == 0"; break;
6303 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006304 default: assert(false && "Invalid comparison operator");
6305 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006306
Ted Kremenek351ba912011-02-23 01:52:04 +00006307 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006308 PDiag(diag::warn_stringcompare)
6309 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006310 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006311 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006312 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006313
Douglas Gregord64fdd02010-06-08 19:50:34 +00006314 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieu67e29332011-08-02 04:35:43 +00006315 if (lex.get()->getType()->isArithmeticType() &&
6316 rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006317 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006318 if (lex.isInvalid() || rex.isInvalid())
6319 return QualType();
6320 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006321 else {
John Wiegley429bb272011-04-08 18:41:53 +00006322 lex = UsualUnaryConversions(lex.take());
6323 if (lex.isInvalid())
6324 return QualType();
6325
6326 rex = UsualUnaryConversions(rex.take());
6327 if (rex.isInvalid())
6328 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006329 }
6330
John Wiegley429bb272011-04-08 18:41:53 +00006331 lType = lex.get()->getType();
6332 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006333
Douglas Gregor447b69e2008-11-19 03:25:36 +00006334 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006335 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006336
Chris Lattnera5937dd2007-08-26 01:18:55 +00006337 if (isRelational) {
6338 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006339 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006340 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006341 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006342 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006343 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006344
Chris Lattnera5937dd2007-08-26 01:18:55 +00006345 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006346 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006347 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006348
John Wiegley429bb272011-04-08 18:41:53 +00006349 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006350 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006351 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006352 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006353
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006354 // All of the following pointer-related warnings are GCC extensions, except
6355 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006356 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006357 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006358 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006359 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006360 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006361
Douglas Gregor0c6db942009-05-04 06:07:12 +00006362 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006363 if (LCanPointeeTy == RCanPointeeTy)
6364 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006365 if (!isRelational &&
6366 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6367 // Valid unless comparison between non-null pointer and function pointer
6368 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006369 // In a SFINAE context, we treat this as a hard error to maintain
6370 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006371 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6372 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006373 Diag(Loc,
6374 isSFINAEContext()?
6375 diag::err_typecheck_comparison_of_fptr_to_void
6376 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006377 << lType << rType << lex.get()->getSourceRange()
6378 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006379
6380 if (isSFINAEContext())
6381 return QualType();
6382
John Wiegley429bb272011-04-08 18:41:53 +00006383 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006384 return ResultTy;
6385 }
6386 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006387
Douglas Gregor0c6db942009-05-04 06:07:12 +00006388 // C++ [expr.rel]p2:
6389 // [...] Pointer conversions (4.10) and qualification
6390 // conversions (4.4) are performed on pointer operands (or on
6391 // a pointer operand and a null pointer constant) to bring
6392 // them to their composite pointer type. [...]
6393 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006394 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006395 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006396 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006397 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006398 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006399 if (T.isNull()) {
6400 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006401 << lType << rType << lex.get()->getSourceRange()
6402 << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006403 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006404 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006405 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006406 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006407 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006408 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006409 }
6410
John Wiegley429bb272011-04-08 18:41:53 +00006411 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6412 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006413 return ResultTy;
6414 }
Eli Friedman3075e762009-08-23 00:27:47 +00006415 // C99 6.5.9p2 and C99 6.5.8p2
6416 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6417 RCanPointeeTy.getUnqualifiedType())) {
6418 // Valid unless a relational comparison of function pointers
6419 if (isRelational && LCanPointeeTy->isFunctionType()) {
6420 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006421 << lType << rType << lex.get()->getSourceRange()
6422 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006423 }
6424 } else if (!isRelational &&
6425 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6426 // Valid unless comparison between non-null pointer and function pointer
6427 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6428 && !LHSIsNull && !RHSIsNull) {
6429 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006430 << lType << rType << lex.get()->getSourceRange()
6431 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006432 }
6433 } else {
6434 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006435 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006436 << lType << rType << lex.get()->getSourceRange()
6437 << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006438 }
John McCall34d6f932011-03-11 04:25:25 +00006439 if (LCanPointeeTy != RCanPointeeTy) {
6440 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006441 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006442 else
John Wiegley429bb272011-04-08 18:41:53 +00006443 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006444 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006445 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006446 }
Mike Stump1eb44332009-09-09 15:08:12 +00006447
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006448 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006449 // Comparison of nullptr_t with itself.
6450 if (lType->isNullPtrType() && rType->isNullPtrType())
6451 return ResultTy;
6452
Mike Stump1eb44332009-09-09 15:08:12 +00006453 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006454 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006455 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006456 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006457 (!isRelational &&
6458 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006459 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006460 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006461 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006462 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006463 return ResultTy;
6464 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006465 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006466 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006467 (!isRelational &&
6468 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006469 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006470 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006471 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006472 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006473 return ResultTy;
6474 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006475
6476 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006477 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006478 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6479 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006480 // In addition, pointers to members can be compared, or a pointer to
6481 // member and a null pointer constant. Pointer to member conversions
6482 // (4.11) and qualification conversions (4.4) are performed to bring
6483 // them to a common type. If one operand is a null pointer constant,
6484 // the common type is the type of the other operand. Otherwise, the
6485 // common type is a pointer to member type similar (4.4) to the type
6486 // of one of the operands, with a cv-qualification signature (4.4)
6487 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006488 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006489 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006490 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006491 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006492 if (T.isNull()) {
6493 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006494 << lType << rType << lex.get()->getSourceRange()
6495 << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006496 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006497 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006498 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006499 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006500 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006501 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006502 }
Mike Stump1eb44332009-09-09 15:08:12 +00006503
John Wiegley429bb272011-04-08 18:41:53 +00006504 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6505 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006506 return ResultTy;
6507 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006508
6509 // Handle scoped enumeration types specifically, since they don't promote
6510 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006511 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieu67e29332011-08-02 04:35:43 +00006512 Context.hasSameUnqualifiedType(lex.get()->getType(),
6513 rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006514 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006515 }
Mike Stump1eb44332009-09-09 15:08:12 +00006516
Steve Naroff1c7d0672008-09-04 15:10:53 +00006517 // Handle block pointer types.
Richard Trieu67e29332011-08-02 04:35:43 +00006518 if (!isRelational && lType->isBlockPointerType() &&
6519 rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006520 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6521 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006522
Steve Naroff1c7d0672008-09-04 15:10:53 +00006523 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006524 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006525 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006526 << lType << rType << lex.get()->getSourceRange()
6527 << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006528 }
John Wiegley429bb272011-04-08 18:41:53 +00006529 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006530 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006531 }
John Wiegley429bb272011-04-08 18:41:53 +00006532
Steve Naroff59f53942008-09-28 01:11:11 +00006533 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006534 if (!isRelational
6535 && ((lType->isBlockPointerType() && rType->isPointerType())
6536 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006537 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006538 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006539 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006540 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006541 ->getPointeeType()->isVoidType())))
6542 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006543 << lType << rType << lex.get()->getSourceRange()
6544 << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006545 }
John McCall34d6f932011-03-11 04:25:25 +00006546 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006547 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006548 else
John Wiegley429bb272011-04-08 18:41:53 +00006549 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006550 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006551 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006552
John McCall34d6f932011-03-11 04:25:25 +00006553 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6554 const PointerType *LPT = lType->getAs<PointerType>();
6555 const PointerType *RPT = rType->getAs<PointerType>();
6556 if (LPT || RPT) {
6557 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6558 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006559
Steve Naroffa8069f12008-11-17 19:49:16 +00006560 if (!LPtrToVoid && !RPtrToVoid &&
6561 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006562 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006563 << lType << rType << lex.get()->getSourceRange()
6564 << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006565 }
John McCall34d6f932011-03-11 04:25:25 +00006566 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006567 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006568 else
John Wiegley429bb272011-04-08 18:41:53 +00006569 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006570 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006571 }
Steve Naroff14108da2009-07-10 23:34:53 +00006572 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006573 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006574 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006575 << lType << rType << lex.get()->getSourceRange()
6576 << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00006577 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006578 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006579 else
John Wiegley429bb272011-04-08 18:41:53 +00006580 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006581 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006582 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006583 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006584 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6585 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006586 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006587 bool isError = false;
6588 if ((LHSIsNull && lType->isIntegerType()) ||
6589 (RHSIsNull && rType->isIntegerType())) {
6590 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006591 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006592 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006593 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006594 else if (getLangOptions().CPlusPlus) {
6595 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6596 isError = true;
6597 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006598 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006599
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006600 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006601 Diag(Loc, DiagID)
Richard Trieu67e29332011-08-02 04:35:43 +00006602 << lType << rType << lex.get()->getSourceRange()
6603 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006604 if (isError)
6605 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006606 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006607
6608 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006609 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006610 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006611 else
John Wiegley429bb272011-04-08 18:41:53 +00006612 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006613 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006614 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006615 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006616
Steve Naroff39218df2008-09-04 16:56:14 +00006617 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006618 if (!isRelational && RHSIsNull
6619 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006620 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006621 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006622 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006623 if (!isRelational && LHSIsNull
6624 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006625 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006626 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006627 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006628
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006629 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006630}
6631
Nate Begemanbe2341d2008-07-14 18:02:46 +00006632/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006633/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006634/// like a scalar comparison, a vector comparison produces a vector of integer
6635/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006636QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006637 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006638 bool isRelational) {
6639 // Check to make sure we're operating on vectors of the same type and width,
6640 // Allowing one side to be a scalar of element type.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006641 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006642 if (vType.isNull())
6643 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006644
John Wiegley429bb272011-04-08 18:41:53 +00006645 QualType lType = lex.get()->getType();
6646 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006647
Anton Yartsev7870b132011-03-27 15:36:07 +00006648 // If AltiVec, the comparison results in a numeric type, i.e.
6649 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006650 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006651 return Context.getLogicalOperationType();
6652
Nate Begemanbe2341d2008-07-14 18:02:46 +00006653 // For non-floating point types, check for self-comparisons of the form
6654 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6655 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006656 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006657 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6658 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006659 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006660 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006661 PDiag(diag::warn_comparison_always)
6662 << 0 // self-
6663 << 2 // "a constant"
6664 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006665 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006666
Nate Begemanbe2341d2008-07-14 18:02:46 +00006667 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006668 if (!isRelational && lType->hasFloatingRepresentation()) {
6669 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006670 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006671 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006672
Nate Begemanbe2341d2008-07-14 18:02:46 +00006673 // Return the type for the comparison, which is the same as vector type for
6674 // integer vectors, or an integer type of identical size and number of
6675 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006676 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006677 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006678
John McCall183700f2009-09-21 23:43:11 +00006679 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006680 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006681 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006682 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006683 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006684 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6685
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006687 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006688 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6689}
6690
Reid Spencer5f016e22007-07-11 17:01:13 +00006691inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006692 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00006693 if (lex.get()->getType()->isVectorType() ||
6694 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006695 if (lex.get()->getType()->hasIntegerRepresentation() &&
6696 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006697 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006698
6699 return InvalidOperands(Loc, lex, rex);
6700 }
Steve Naroff90045e82007-07-13 23:32:42 +00006701
John Wiegley429bb272011-04-08 18:41:53 +00006702 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieu67e29332011-08-02 04:35:43 +00006703 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6704 isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006705 if (lexResult.isInvalid() || rexResult.isInvalid())
6706 return QualType();
6707 lex = lexResult.take();
6708 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006709
John Wiegley429bb272011-04-08 18:41:53 +00006710 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6711 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006712 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006713 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006714}
6715
6716inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006717 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006718
6719 // Diagnose cases where the user write a logical and/or but probably meant a
6720 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6721 // is a constant.
Richard Trieu67e29332011-08-02 04:35:43 +00006722 if (lex.get()->getType()->isIntegerType() &&
6723 !lex.get()->getType()->isBooleanType() &&
John Wiegley429bb272011-04-08 18:41:53 +00006724 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006725 // Don't warn in macros or template instantiations.
6726 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006727 // If the RHS can be constant folded, and if it constant folds to something
6728 // that isn't 0 or 1 (which indicate a potential logical operation that
6729 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006730 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006731 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006732 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6733 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6734 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6735 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6736 << rex.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006737 << (Opc == BO_LAnd ? "&&" : "||");
6738 // Suggest replacing the logical operator with the bitwise version
6739 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6740 << (Opc == BO_LAnd ? "&" : "|")
6741 << FixItHint::CreateReplacement(SourceRange(
6742 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6743 getLangOptions())),
6744 Opc == BO_LAnd ? "&" : "|");
6745 if (Opc == BO_LAnd)
6746 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6747 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6748 << FixItHint::CreateRemoval(
6749 SourceRange(
6750 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6751 0, getSourceManager(),
6752 getLangOptions()),
6753 rex.get()->getLocEnd()));
6754 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006755 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006756
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006757 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006758 lex = UsualUnaryConversions(lex.take());
6759 if (lex.isInvalid())
6760 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006761
John Wiegley429bb272011-04-08 18:41:53 +00006762 rex = UsualUnaryConversions(rex.take());
6763 if (rex.isInvalid())
6764 return QualType();
6765
Richard Trieu67e29332011-08-02 04:35:43 +00006766 if (!lex.get()->getType()->isScalarType() ||
6767 !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006768 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006769
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006770 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006771 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006772
John McCall75f7c0f2010-06-04 00:29:51 +00006773 // The following is safe because we only use this method for
6774 // non-overloadable operands.
6775
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006776 // C++ [expr.log.and]p1
6777 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006778 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006779 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6780 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006781 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006782 lex = move(lexRes);
6783
6784 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6785 if (rexRes.isInvalid())
6786 return InvalidOperands(Loc, lex, rex);
6787 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006788
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006789 // C++ [expr.log.and]p2
6790 // C++ [expr.log.or]p2
6791 // The result is a bool.
6792 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006793}
6794
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006795/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6796/// is a read-only property; return true if so. A readonly property expression
6797/// depends on various declarations and thus must be treated specially.
6798///
Mike Stump1eb44332009-09-09 15:08:12 +00006799static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006800 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6801 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006802 if (PropExpr->isImplicitProperty()) return false;
6803
6804 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6805 QualType BaseType = PropExpr->isSuperReceiver() ?
6806 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006807 PropExpr->getBase()->getType();
6808
John McCall12f78a62010-12-02 01:19:52 +00006809 if (const ObjCObjectPointerType *OPT =
6810 BaseType->getAsObjCInterfacePointerType())
6811 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6812 if (S.isPropertyReadonly(PDecl, IFace))
6813 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006814 }
6815 return false;
6816}
6817
Fariborz Jahanian14086762011-03-28 23:47:18 +00006818static bool IsConstProperty(Expr *E, Sema &S) {
6819 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6820 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6821 if (PropExpr->isImplicitProperty()) return false;
6822
6823 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6824 QualType T = PDecl->getType();
6825 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006826 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006827 CanQualType CT = S.Context.getCanonicalType(T);
6828 return CT.isConstQualified();
6829 }
6830 return false;
6831}
6832
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006833static bool IsReadonlyMessage(Expr *E, Sema &S) {
6834 if (E->getStmtClass() != Expr::MemberExprClass)
6835 return false;
6836 const MemberExpr *ME = cast<MemberExpr>(E);
6837 NamedDecl *Member = ME->getMemberDecl();
6838 if (isa<FieldDecl>(Member)) {
6839 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6840 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6841 return false;
6842 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6843 }
6844 return false;
6845}
6846
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006847/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6848/// emit an error and return true. If so, return false.
6849static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006850 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006851 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006852 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006853 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6854 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006855 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6856 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006857 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6858 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006859 if (IsLV == Expr::MLV_Valid)
6860 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006861
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006862 unsigned Diag = 0;
6863 bool NeedType = false;
6864 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006865 case Expr::MLV_ConstQualified:
6866 Diag = diag::err_typecheck_assign_const;
6867
John McCall7acddac2011-06-17 06:42:21 +00006868 // In ARC, use some specialized diagnostics for occasions where we
6869 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006870 if (S.getLangOptions().ObjCAutoRefCount) {
6871 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6872 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6873 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6874
John McCall7acddac2011-06-17 06:42:21 +00006875 // Use the normal diagnostic if it's pseudo-__strong but the
6876 // user actually wrote 'const'.
6877 if (var->isARCPseudoStrong() &&
6878 (!var->getTypeSourceInfo() ||
6879 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6880 // There are two pseudo-strong cases:
6881 // - self
John McCallf85e1932011-06-15 23:02:42 +00006882 ObjCMethodDecl *method = S.getCurMethodDecl();
6883 if (method && var == method->getSelfDecl())
6884 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006885
6886 // - fast enumeration variables
6887 else
John McCallf85e1932011-06-15 23:02:42 +00006888 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006889
John McCallf85e1932011-06-15 23:02:42 +00006890 SourceRange Assign;
6891 if (Loc != OrigLoc)
6892 Assign = SourceRange(OrigLoc, OrigLoc);
6893 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6894 // We need to preserve the AST regardless, so migration tool
6895 // can do its job.
6896 return false;
6897 }
6898 }
6899 }
6900
6901 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006903 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6904 NeedType = true;
6905 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006906 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006907 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6908 NeedType = true;
6909 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006910 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006911 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6912 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006913 case Expr::MLV_Valid:
6914 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006915 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006916 case Expr::MLV_MemberFunction:
6917 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006918 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6919 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006920 case Expr::MLV_IncompleteType:
6921 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006922 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006923 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006924 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006925 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006926 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6927 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006928 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006929 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6930 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006931 case Expr::MLV_ReadonlyProperty:
6932 Diag = diag::error_readonly_property_assignment;
6933 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006934 case Expr::MLV_NoSetterProperty:
6935 Diag = diag::error_nosetter_property_assignment;
6936 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006937 case Expr::MLV_InvalidMessageExpression:
6938 Diag = diag::error_readonly_message_assignment;
6939 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006940 case Expr::MLV_SubObjCPropertySetting:
6941 Diag = diag::error_no_subobject_property_setting;
6942 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006943 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006944
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006945 SourceRange Assign;
6946 if (Loc != OrigLoc)
6947 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006948 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006949 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006950 else
Mike Stump1eb44332009-09-09 15:08:12 +00006951 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006952 return true;
6953}
6954
6955
6956
6957// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006958QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006959 SourceLocation Loc,
6960 QualType CompoundType) {
6961 // Verify that LHS is a modifiable lvalue, and emit error if not.
6962 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006963 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006964
6965 QualType LHSType = LHS->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00006966 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6967 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006968 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006969 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006970 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006971 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00006972 if (LHS->getObjectKind() == OK_ObjCProperty) {
6973 ExprResult LHSResult = Owned(LHS);
6974 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6975 if (LHSResult.isInvalid())
6976 return QualType();
6977 LHS = LHSResult.take();
6978 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006979 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00006980 if (RHS.isInvalid())
6981 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006982 // Special case of NSObject attributes on c-style pointer types.
6983 if (ConvTy == IncompatiblePointer &&
6984 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006985 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006986 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006987 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006988 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006989
John McCallf89e55a2010-11-18 06:31:45 +00006990 if (ConvTy == Compatible &&
6991 getLangOptions().ObjCNonFragileABI &&
6992 LHSType->isObjCObjectType())
6993 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6994 << LHSType;
6995
Chris Lattner2c156472008-08-21 18:04:13 +00006996 // If the RHS is a unary plus or minus, check to see if they = and + are
6997 // right next to each other. If so, the user may have typo'd "x =+ 4"
6998 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00006999 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007000 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7001 RHSCheck = ICE->getSubExpr();
7002 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007003 if ((UO->getOpcode() == UO_Plus ||
7004 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007005 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007006 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007007 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7008 // And there is a space or other character before the subexpr of the
7009 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007010 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7011 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007012 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007013 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007014 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007015 }
Chris Lattner2c156472008-08-21 18:04:13 +00007016 }
John McCallf85e1932011-06-15 23:02:42 +00007017
7018 if (ConvTy == Compatible) {
7019 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7020 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007021 else if (getLangOptions().ObjCAutoRefCount)
7022 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007023 }
Chris Lattner2c156472008-08-21 18:04:13 +00007024 } else {
7025 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007026 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007027 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007028
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007029 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007030 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007031 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007032
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007033 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007034
Reid Spencer5f016e22007-07-11 17:01:13 +00007035 // C99 6.5.16p3: The type of an assignment expression is the type of the
7036 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007037 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007038 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7039 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007040 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007041 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007042 return (getLangOptions().CPlusPlus
7043 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007044}
7045
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007046// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007047static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007048 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007049 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007050
John McCallfb8721c2011-04-10 19:13:55 +00007051 LHS = S.CheckPlaceholderExpr(LHS.take());
7052 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007053 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007054 return QualType();
7055
John McCallcf2e5062010-10-12 07:14:40 +00007056 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7057 // operands, but not unary promotions.
7058 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007059
John McCallf6a16482010-12-04 03:47:34 +00007060 // So we treat the LHS as a ignored value, and in C++ we allow the
7061 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007062 LHS = S.IgnoredValueConversions(LHS.take());
7063 if (LHS.isInvalid())
7064 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007065
7066 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007067 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7068 if (RHS.isInvalid())
7069 return QualType();
7070 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007071 S.RequireCompleteType(Loc, RHS.get()->getType(),
7072 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007073 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007074
John Wiegley429bb272011-04-08 18:41:53 +00007075 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007076}
7077
Steve Naroff49b45262007-07-13 16:58:59 +00007078/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7079/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007080static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7081 ExprValueKind &VK,
7082 SourceLocation OpLoc,
7083 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007084 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007085 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007086
Chris Lattner3528d352008-11-21 07:05:48 +00007087 QualType ResType = Op->getType();
7088 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007089
John McCall09431682010-11-18 19:01:18 +00007090 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007091 // Decrement of bool is not allowed.
7092 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007093 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007094 return QualType();
7095 }
7096 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007097 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007098 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007099 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007100 } else if (ResType->isAnyPointerType()) {
7101 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007102
Chris Lattner3528d352008-11-21 07:05:48 +00007103 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007104 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007105 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007106
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007107 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007108 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7109 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007110 << PointeeTy << Op->getSourceRange();
7111 return QualType();
7112 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007113 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007114 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007115 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007116 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007117 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007118 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007119 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007120 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7121 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007122 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7123 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007124 } else {
John McCall09431682010-11-18 19:01:18 +00007125 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007126 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007127 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007128 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007129 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007130 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007131 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007132 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007133 // In C++, a prefix increment is the same type as the operand. Otherwise
7134 // (in C or with postfix), the increment is the unqualified type of the
7135 // operand.
John McCall09431682010-11-18 19:01:18 +00007136 if (isPrefix && S.getLangOptions().CPlusPlus) {
7137 VK = VK_LValue;
7138 return ResType;
7139 } else {
7140 VK = VK_RValue;
7141 return ResType.getUnqualifiedType();
7142 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007143}
7144
John Wiegley429bb272011-04-08 18:41:53 +00007145ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007146 assert(E->getValueKind() == VK_LValue &&
7147 E->getObjectKind() == OK_ObjCProperty);
7148 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7149
Douglas Gregor926df6c2011-06-11 01:09:30 +00007150 QualType T = E->getType();
7151 QualType ReceiverType;
7152 if (PRE->isObjectReceiver())
7153 ReceiverType = PRE->getBase()->getType();
7154 else if (PRE->isSuperReceiver())
7155 ReceiverType = PRE->getSuperReceiverType();
7156 else
7157 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7158
John McCallf6a16482010-12-04 03:47:34 +00007159 ExprValueKind VK = VK_RValue;
7160 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007161 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007162 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007163 T = getMessageSendResultType(ReceiverType, GetterMethod,
7164 PRE->isClassReceiver(),
7165 PRE->isSuperReceiver());
7166 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007167 }
7168 else {
7169 Diag(PRE->getLocation(), diag::err_getter_not_found)
7170 << PRE->getBase()->getType();
7171 }
John McCallf6a16482010-12-04 03:47:34 +00007172 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007173
7174 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007175 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007176
7177 ExprResult Result = MaybeBindToTemporary(E);
7178 if (!Result.isInvalid())
7179 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007180
7181 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007182}
7183
Richard Trieu67e29332011-08-02 04:35:43 +00007184void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7185 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007186 assert(LHS.get()->getValueKind() == VK_LValue &&
7187 LHS.get()->getObjectKind() == OK_ObjCProperty);
7188 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007189
John McCallf85e1932011-06-15 23:02:42 +00007190 bool Consumed = false;
7191
John Wiegley429bb272011-04-08 18:41:53 +00007192 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007193 // If using property-dot syntax notation for assignment, and there is a
7194 // setter, RHS expression is being passed to the setter argument. So,
7195 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007196 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007197 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7198 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007199 Consumed = (getLangOptions().ObjCAutoRefCount &&
7200 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007201
7202 // Otherwise, if the getter returns an l-value, just call that.
7203 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007204 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007205 ExprValueKind VK = Expr::getValueKindForType(Result);
7206 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007207 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7208 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007209 return;
John McCall12f78a62010-12-02 01:19:52 +00007210 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007211 }
John McCallf85e1932011-06-15 23:02:42 +00007212 } else if (getLangOptions().ObjCAutoRefCount) {
7213 const ObjCMethodDecl *setter
7214 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7215 if (setter) {
7216 ObjCMethodDecl::param_iterator P = setter->param_begin();
7217 LHSTy = (*P)->getType();
7218 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7219 }
John McCallf6a16482010-12-04 03:47:34 +00007220 }
7221
John McCallf85e1932011-06-15 23:02:42 +00007222 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7223 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007224 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007225 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007226 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007227 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007228 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007229 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7230 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7231 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007232 }
7233}
7234
7235
Anders Carlsson369dee42008-02-01 07:15:58 +00007236/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007237/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007238/// where the declaration is needed for type checking. We only need to
7239/// handle cases when the expression references a function designator
7240/// or is an lvalue. Here are some examples:
7241/// - &(x) => x
7242/// - &*****f => f for f a function designator.
7243/// - &s.xx => s
7244/// - &s.zz[1].yy -> s, if zz is an array
7245/// - *(x + 1) -> x, if x is an array
7246/// - &"123"[2] -> 0
7247/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007248static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007249 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007250 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007251 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007252 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007253 // If this is an arrow operator, the address is an offset from
7254 // the base's value, so the object the base refers to is
7255 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007256 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007257 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007258 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007259 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007260 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007261 // FIXME: This code shouldn't be necessary! We should catch the implicit
7262 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007263 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7264 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7265 if (ICE->getSubExpr()->getType()->isArrayType())
7266 return getPrimaryDecl(ICE->getSubExpr());
7267 }
7268 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007269 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007270 case Stmt::UnaryOperatorClass: {
7271 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007272
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007273 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007274 case UO_Real:
7275 case UO_Imag:
7276 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007277 return getPrimaryDecl(UO->getSubExpr());
7278 default:
7279 return 0;
7280 }
7281 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007282 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007283 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007284 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007285 // If the result of an implicit cast is an l-value, we care about
7286 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007287 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007288 default:
7289 return 0;
7290 }
7291}
7292
7293/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007294/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007295/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007296/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007297/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007298/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007299/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007300static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7301 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007302 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007303 return S.Context.DependentTy;
7304 if (OrigOp->getType() == S.Context.OverloadTy)
7305 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007306 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7307 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007308 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7309 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7310 << OrigOp->getSourceRange();
7311 return QualType();
7312 }
John McCall9c72c602010-08-27 09:08:28 +00007313
John McCall755d8492011-04-12 00:42:48 +00007314 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007315
John McCall9c72c602010-08-27 09:08:28 +00007316 // Make sure to ignore parentheses in subsequent checks
7317 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007318
John McCall09431682010-11-18 19:01:18 +00007319 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007320 // Implement C99-only parts of addressof rules.
7321 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007322 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007323 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7324 // (assuming the deref expression is valid).
7325 return uOp->getSubExpr()->getType();
7326 }
7327 // Technically, there should be a check for array subscript
7328 // expressions here, but the result of one is always an lvalue anyway.
7329 }
John McCall5808ce42011-02-03 08:15:49 +00007330 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007331 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007332
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007333 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007334 bool sfinae = S.isSFINAEContext();
7335 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7336 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007337 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007338 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007339 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007340 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007341 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007342 } else if (lval == Expr::LV_MemberFunction) {
7343 // If it's an instance method, make a member pointer.
7344 // The expression must have exactly the form &A::foo.
7345
7346 // If the underlying expression isn't a decl ref, give up.
7347 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007348 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007349 << OrigOp->getSourceRange();
7350 return QualType();
7351 }
7352 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7353 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7354
7355 // The id-expression was parenthesized.
7356 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007357 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007358 << OrigOp->getSourceRange();
7359
7360 // The method was named without a qualifier.
7361 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007362 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007363 << op->getSourceRange();
7364 }
7365
John McCall09431682010-11-18 19:01:18 +00007366 return S.Context.getMemberPointerType(op->getType(),
7367 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007368 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007369 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007370 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007371 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007372 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007373 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007374 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007375 return QualType();
7376 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007377 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007378 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007379 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007380 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007381 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007382 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007383 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007384 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007385 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007386 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007387 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007388 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007389 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007390 << "property expression" << op->getSourceRange();
7391 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007392 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007393 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007394 // with the register storage-class specifier.
7395 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007396 // in C++ it is not error to take address of a register
7397 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007398 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007399 !S.getLangOptions().CPlusPlus) {
7400 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007401 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007402 return QualType();
7403 }
John McCallba135432009-11-21 08:51:07 +00007404 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007405 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007406 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007407 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007408 // Could be a pointer to member, though, if there is an explicit
7409 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007410 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007411 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007412 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007413 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007414 S.Diag(OpLoc,
7415 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007416 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007417 return QualType();
7418 }
Mike Stump1eb44332009-09-09 15:08:12 +00007419
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007420 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7421 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007422 return S.Context.getMemberPointerType(op->getType(),
7423 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007424 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007425 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007426 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007427 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007428 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007429
Eli Friedman441cf102009-05-16 23:27:50 +00007430 if (lval == Expr::LV_IncompleteVoidType) {
7431 // Taking the address of a void variable is technically illegal, but we
7432 // allow it in cases which are otherwise valid.
7433 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007434 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007435 }
7436
Reid Spencer5f016e22007-07-11 17:01:13 +00007437 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007438 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007439 return S.Context.getObjCObjectPointerType(op->getType());
7440 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007441}
7442
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007443/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007444static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7445 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007446 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007447 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007448
John Wiegley429bb272011-04-08 18:41:53 +00007449 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7450 if (ConvResult.isInvalid())
7451 return QualType();
7452 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007453 QualType OpTy = Op->getType();
7454 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007455
7456 if (isa<CXXReinterpretCastExpr>(Op)) {
7457 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7458 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7459 Op->getSourceRange());
7460 }
7461
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007462 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7463 // is an incomplete type or void. It would be possible to warn about
7464 // dereferencing a void pointer, but it's completely well-defined, and such a
7465 // warning is unlikely to catch any mistakes.
7466 if (const PointerType *PT = OpTy->getAs<PointerType>())
7467 Result = PT->getPointeeType();
7468 else if (const ObjCObjectPointerType *OPT =
7469 OpTy->getAs<ObjCObjectPointerType>())
7470 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007471 else {
John McCallfb8721c2011-04-10 19:13:55 +00007472 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007473 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007474 if (PR.take() != Op)
7475 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007476 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007477
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007478 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007479 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007480 << OpTy << Op->getSourceRange();
7481 return QualType();
7482 }
John McCall09431682010-11-18 19:01:18 +00007483
7484 // Dereferences are usually l-values...
7485 VK = VK_LValue;
7486
7487 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007488 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007489 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007490
7491 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007492}
7493
John McCall2de56d12010-08-25 11:45:40 +00007494static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007495 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007496 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007497 switch (Kind) {
7498 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007499 case tok::periodstar: Opc = BO_PtrMemD; break;
7500 case tok::arrowstar: Opc = BO_PtrMemI; break;
7501 case tok::star: Opc = BO_Mul; break;
7502 case tok::slash: Opc = BO_Div; break;
7503 case tok::percent: Opc = BO_Rem; break;
7504 case tok::plus: Opc = BO_Add; break;
7505 case tok::minus: Opc = BO_Sub; break;
7506 case tok::lessless: Opc = BO_Shl; break;
7507 case tok::greatergreater: Opc = BO_Shr; break;
7508 case tok::lessequal: Opc = BO_LE; break;
7509 case tok::less: Opc = BO_LT; break;
7510 case tok::greaterequal: Opc = BO_GE; break;
7511 case tok::greater: Opc = BO_GT; break;
7512 case tok::exclaimequal: Opc = BO_NE; break;
7513 case tok::equalequal: Opc = BO_EQ; break;
7514 case tok::amp: Opc = BO_And; break;
7515 case tok::caret: Opc = BO_Xor; break;
7516 case tok::pipe: Opc = BO_Or; break;
7517 case tok::ampamp: Opc = BO_LAnd; break;
7518 case tok::pipepipe: Opc = BO_LOr; break;
7519 case tok::equal: Opc = BO_Assign; break;
7520 case tok::starequal: Opc = BO_MulAssign; break;
7521 case tok::slashequal: Opc = BO_DivAssign; break;
7522 case tok::percentequal: Opc = BO_RemAssign; break;
7523 case tok::plusequal: Opc = BO_AddAssign; break;
7524 case tok::minusequal: Opc = BO_SubAssign; break;
7525 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7526 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7527 case tok::ampequal: Opc = BO_AndAssign; break;
7528 case tok::caretequal: Opc = BO_XorAssign; break;
7529 case tok::pipeequal: Opc = BO_OrAssign; break;
7530 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007531 }
7532 return Opc;
7533}
7534
John McCall2de56d12010-08-25 11:45:40 +00007535static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007536 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007537 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007538 switch (Kind) {
7539 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007540 case tok::plusplus: Opc = UO_PreInc; break;
7541 case tok::minusminus: Opc = UO_PreDec; break;
7542 case tok::amp: Opc = UO_AddrOf; break;
7543 case tok::star: Opc = UO_Deref; break;
7544 case tok::plus: Opc = UO_Plus; break;
7545 case tok::minus: Opc = UO_Minus; break;
7546 case tok::tilde: Opc = UO_Not; break;
7547 case tok::exclaim: Opc = UO_LNot; break;
7548 case tok::kw___real: Opc = UO_Real; break;
7549 case tok::kw___imag: Opc = UO_Imag; break;
7550 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007551 }
7552 return Opc;
7553}
7554
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007555/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7556/// This warning is only emitted for builtin assignment operations. It is also
7557/// suppressed in the event of macro expansions.
7558static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7559 SourceLocation OpLoc) {
7560 if (!S.ActiveTemplateInstantiations.empty())
7561 return;
7562 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7563 return;
7564 lhs = lhs->IgnoreParenImpCasts();
7565 rhs = rhs->IgnoreParenImpCasts();
7566 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7567 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7568 if (!LeftDeclRef || !RightDeclRef ||
7569 LeftDeclRef->getLocation().isMacroID() ||
7570 RightDeclRef->getLocation().isMacroID())
7571 return;
7572 const ValueDecl *LeftDecl =
7573 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7574 const ValueDecl *RightDecl =
7575 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7576 if (LeftDecl != RightDecl)
7577 return;
7578 if (LeftDecl->getType().isVolatileQualified())
7579 return;
7580 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7581 if (RefTy->getPointeeType().isVolatileQualified())
7582 return;
7583
7584 S.Diag(OpLoc, diag::warn_self_assignment)
7585 << LeftDeclRef->getType()
7586 << lhs->getSourceRange() << rhs->getSourceRange();
7587}
7588
Douglas Gregoreaebc752008-11-06 23:29:22 +00007589/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7590/// operator @p Opc at location @c TokLoc. This routine only supports
7591/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007592ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007593 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007594 Expr *lhsExpr, Expr *rhsExpr) {
7595 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007596 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007597 // The following two variables are used for compound assignment operators
7598 QualType CompLHSTy; // Type of LHS after promotions for computation
7599 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007600 ExprValueKind VK = VK_RValue;
7601 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007602
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007603 // Check if a 'foo<int>' involved in a binary op, identifies a single
7604 // function unambiguously (i.e. an lvalue ala 13.4)
7605 // But since an assignment can trigger target based overload, exclude it in
7606 // our blind search. i.e:
7607 // template<class T> void f(); template<class T, class U> void f(U);
7608 // f<int> == 0; // resolve f<int> blindly
7609 // void (*p)(int); p = f<int>; // resolve f<int> using target
7610 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007611 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007612 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007613 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007614
John McCallfb8721c2011-04-10 19:13:55 +00007615 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007616 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007617 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007618 }
7619
Eli Friedmaned3b2562011-06-17 20:52:22 +00007620 // The canonical way to check for a GNU null is with isNullPointerConstant,
7621 // but we use a bit of a hack here for speed; this is a relatively
7622 // hot path, and isNullPointerConstant is slow.
7623 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7624 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu3e95ba92011-06-16 21:36:56 +00007625
7626 // Detect when a NULL constant is used improperly in an expression. These
7627 // are mainly cases where the null pointer is used as an integer instead
7628 // of a pointer.
7629 if (LeftNull || RightNull) {
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007630 // Avoid analyzing cases where the result will either be invalid (and
7631 // diagnosed as such) or entirely valid and not something to warn about.
7632 QualType LeftType = lhs.get()->getType();
7633 QualType RightType = rhs.get()->getType();
7634 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7635 !LeftType->isFunctionType() &&
7636 !RightType->isBlockPointerType() &&
7637 !RightType->isMemberPointerType() &&
7638 !RightType->isFunctionType()) {
7639 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7640 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7641 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7642 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7643 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7644 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7645 // These are the operations that would not make sense with a null pointer
Richard Trieu67e29332011-08-02 04:35:43 +00007646 // pointer no matter what the other expression is.
Chandler Carruth2af68e42011-06-19 09:05:14 +00007647 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007648 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7649 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7650 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7651 Opc == BO_EQ || Opc == BO_NE) {
7652 // These are the operations that would not make sense with a null pointer
7653 // if the other expression the other expression is not a pointer.
7654 if (LeftNull != RightNull &&
7655 !LeftType->isAnyPointerType() &&
7656 !LeftType->canDecayToPointerType() &&
7657 !RightType->isAnyPointerType() &&
7658 !RightType->canDecayToPointerType()) {
Richard Trieu79e610a2011-08-11 22:38:21 +00007659 Diag(OpLoc, diag::warn_null_in_comparison_operation)
7660 << LeftNull /* LHS is NULL */
7661 << (LeftNull ? rhs.get()->getType() : lhs.get()->getType())
7662 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007663 }
Richard Trieu3e95ba92011-06-16 21:36:56 +00007664 }
7665 }
7666 }
7667
Douglas Gregoreaebc752008-11-06 23:29:22 +00007668 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007669 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007670 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007671 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007672 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7673 VK = lhs.get()->getValueKind();
7674 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007675 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007676 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007677 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007678 break;
John McCall2de56d12010-08-25 11:45:40 +00007679 case BO_PtrMemD:
7680 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007681 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007682 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007683 break;
John McCall2de56d12010-08-25 11:45:40 +00007684 case BO_Mul:
7685 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007686 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007687 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007688 break;
John McCall2de56d12010-08-25 11:45:40 +00007689 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007690 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7691 break;
John McCall2de56d12010-08-25 11:45:40 +00007692 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007693 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7694 break;
John McCall2de56d12010-08-25 11:45:40 +00007695 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007696 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7697 break;
John McCall2de56d12010-08-25 11:45:40 +00007698 case BO_Shl:
7699 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007700 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007701 break;
John McCall2de56d12010-08-25 11:45:40 +00007702 case BO_LE:
7703 case BO_LT:
7704 case BO_GE:
7705 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007706 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007707 break;
John McCall2de56d12010-08-25 11:45:40 +00007708 case BO_EQ:
7709 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007710 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007711 break;
John McCall2de56d12010-08-25 11:45:40 +00007712 case BO_And:
7713 case BO_Xor:
7714 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007715 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7716 break;
John McCall2de56d12010-08-25 11:45:40 +00007717 case BO_LAnd:
7718 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007719 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007720 break;
John McCall2de56d12010-08-25 11:45:40 +00007721 case BO_MulAssign:
7722 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007723 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007724 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007725 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007726 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7727 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007728 break;
John McCall2de56d12010-08-25 11:45:40 +00007729 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007730 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7731 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007732 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7733 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007734 break;
John McCall2de56d12010-08-25 11:45:40 +00007735 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007736 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007737 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7738 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007739 break;
John McCall2de56d12010-08-25 11:45:40 +00007740 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007741 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007742 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7743 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007744 break;
John McCall2de56d12010-08-25 11:45:40 +00007745 case BO_ShlAssign:
7746 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007747 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007748 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007749 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7750 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007751 break;
John McCall2de56d12010-08-25 11:45:40 +00007752 case BO_AndAssign:
7753 case BO_XorAssign:
7754 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007755 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7756 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007757 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7758 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007759 break;
John McCall2de56d12010-08-25 11:45:40 +00007760 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007761 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007762 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7763 VK = rhs.get()->getValueKind();
7764 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007765 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007766 break;
7767 }
John Wiegley429bb272011-04-08 18:41:53 +00007768 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007769 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007770
7771 // Check for array bounds violations for both sides of the BinaryOperator
7772 CheckArrayAccess(lhs.get());
7773 CheckArrayAccess(rhs.get());
7774
Eli Friedmanab3a8522009-03-28 01:22:36 +00007775 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007776 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7777 ResultTy, VK, OK, OpLoc));
Richard Trieu67e29332011-08-02 04:35:43 +00007778 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7779 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007780 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007781 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007782 }
John Wiegley429bb272011-04-08 18:41:53 +00007783 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7784 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007785 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007786}
7787
Sebastian Redlaee3c932009-10-27 12:10:02 +00007788/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7789/// operators are mixed in a way that suggests that the programmer forgot that
7790/// comparison operators have higher precedence. The most typical example of
7791/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007792static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007793 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007794 typedef BinaryOperator BinOp;
7795 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7796 rhsopc = static_cast<BinOp::Opcode>(-1);
7797 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007798 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007799 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007800 rhsopc = BO->getOpcode();
7801
7802 // Subs are not binary operators.
7803 if (lhsopc == -1 && rhsopc == -1)
7804 return;
7805
7806 // Bitwise operations are sometimes used as eager logical ops.
7807 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007808 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7809 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007810 return;
7811
Richard Trieu70979d42011-08-10 22:41:34 +00007812 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7813 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7814 if (!isLeftComp && !isRightComp) return;
7815
7816 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7817 : SourceRange(OpLoc, rhs->getLocEnd());
7818 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7819 : BinOp::getOpcodeStr(rhsopc);
7820 SourceRange ParensRange = isLeftComp ?
7821 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7822 rhs->getLocEnd())
7823 : SourceRange(lhs->getLocStart(),
7824 cast<BinOp>(rhs)->getLHS()->getLocStart());
7825
7826 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7827 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7828 SuggestParentheses(Self, OpLoc,
7829 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7830 rhs->getSourceRange());
7831 SuggestParentheses(Self, OpLoc,
7832 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7833 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007834}
7835
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007836/// \brief It accepts a '&' expr that is inside a '|' one.
7837/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7838/// in parentheses.
7839static void
7840EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7841 BinaryOperator *Bop) {
7842 assert(Bop->getOpcode() == BO_And);
7843 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7844 << Bop->getSourceRange() << OpLoc;
7845 SuggestParentheses(Self, Bop->getOperatorLoc(),
7846 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7847 Bop->getSourceRange());
7848}
7849
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007850/// \brief It accepts a '&&' expr that is inside a '||' one.
7851/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7852/// in parentheses.
7853static void
7854EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007855 BinaryOperator *Bop) {
7856 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007857 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7858 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007859 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007860 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007861 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007862}
7863
7864/// \brief Returns true if the given expression can be evaluated as a constant
7865/// 'true'.
7866static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7867 bool Res;
7868 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7869}
7870
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007871/// \brief Returns true if the given expression can be evaluated as a constant
7872/// 'false'.
7873static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7874 bool Res;
7875 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7876}
7877
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007878/// \brief Look for '&&' in the left hand of a '||' expr.
7879static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007880 Expr *OrLHS, Expr *OrRHS) {
7881 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007882 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007883 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7884 if (EvaluatesAsFalse(S, OrRHS))
7885 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007886 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7887 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7888 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7889 } else if (Bop->getOpcode() == BO_LOr) {
7890 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7891 // If it's "a || b && 1 || c" we didn't warn earlier for
7892 // "a || b && 1", but warn now.
7893 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7894 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7895 }
7896 }
7897 }
7898}
7899
7900/// \brief Look for '&&' in the right hand of a '||' expr.
7901static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007902 Expr *OrLHS, Expr *OrRHS) {
7903 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007904 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007905 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7906 if (EvaluatesAsFalse(S, OrLHS))
7907 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007908 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7909 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7910 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007911 }
7912 }
7913}
7914
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007915/// \brief Look for '&' in the left or right hand of a '|' expr.
7916static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7917 Expr *OrArg) {
7918 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7919 if (Bop->getOpcode() == BO_And)
7920 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7921 }
7922}
7923
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007924/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007925/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007926static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007927 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007928 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007929 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007930 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7931
7932 // Diagnose "arg1 & arg2 | arg3"
7933 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7934 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7935 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7936 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007937
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007938 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7939 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007940 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007941 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7942 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007943 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007944}
7945
Reid Spencer5f016e22007-07-11 17:01:13 +00007946// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007947ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007948 tok::TokenKind Kind,
7949 Expr *lhs, Expr *rhs) {
7950 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00007951 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7952 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007953
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007954 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7955 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7956
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007957 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7958}
7959
John McCall60d7b3a2010-08-24 06:29:42 +00007960ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007961 BinaryOperatorKind Opc,
7962 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00007963 if (getLangOptions().CPlusPlus) {
7964 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007965
John McCall01b2e4e2010-12-06 05:26:58 +00007966 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7967 UseBuiltinOperator = false;
7968 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7969 UseBuiltinOperator = true;
7970 } else {
7971 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7972 !rhs->getType()->isOverloadableType();
7973 }
7974
7975 if (!UseBuiltinOperator) {
7976 // Find all of the overloaded operators visible from this
7977 // point. We perform both an operator-name lookup from the local
7978 // scope and an argument-dependent lookup based on the types of
7979 // the arguments.
7980 UnresolvedSet<16> Functions;
7981 OverloadedOperatorKind OverOp
7982 = BinaryOperator::getOverloadedOperator(Opc);
7983 if (S && OverOp != OO_None)
7984 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7985 Functions);
7986
7987 // Build the (potentially-overloaded, potentially-dependent)
7988 // binary operation.
7989 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7990 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007991 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007992
Douglas Gregoreaebc752008-11-06 23:29:22 +00007993 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007994 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00007995}
7996
John McCall60d7b3a2010-08-24 06:29:42 +00007997ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007998 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007999 Expr *InputExpr) {
8000 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008001 ExprValueKind VK = VK_RValue;
8002 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008003 QualType resultType;
8004 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008005 case UO_PreInc:
8006 case UO_PreDec:
8007 case UO_PostInc:
8008 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008009 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008010 Opc == UO_PreInc ||
8011 Opc == UO_PostInc,
8012 Opc == UO_PreInc ||
8013 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008014 break;
John McCall2de56d12010-08-25 11:45:40 +00008015 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008016 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008017 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008018 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008019 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008020 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008021 Input = move(resolved);
8022 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8023 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008024 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008025 }
John McCall2de56d12010-08-25 11:45:40 +00008026 case UO_Plus:
8027 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008028 Input = UsualUnaryConversions(Input.take());
8029 if (Input.isInvalid()) return ExprError();
8030 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008031 if (resultType->isDependentType())
8032 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008033 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8034 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008035 break;
8036 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8037 resultType->isEnumeralType())
8038 break;
8039 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008040 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008041 resultType->isPointerType())
8042 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008043 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008044 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008045 if (Input.isInvalid()) return ExprError();
8046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008047 }
Douglas Gregor74253732008-11-19 15:42:04 +00008048
Sebastian Redl0eb23302009-01-19 00:08:26 +00008049 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008050 << resultType << Input.get()->getSourceRange());
8051
John McCall2de56d12010-08-25 11:45:40 +00008052 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008053 Input = UsualUnaryConversions(Input.take());
8054 if (Input.isInvalid()) return ExprError();
8055 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008056 if (resultType->isDependentType())
8057 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008058 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8059 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8060 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008061 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008062 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008063 else if (resultType->hasIntegerRepresentation())
8064 break;
8065 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008066 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008067 if (Input.isInvalid()) return ExprError();
8068 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008069 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008070 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008071 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008072 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008073 break;
John Wiegley429bb272011-04-08 18:41:53 +00008074
John McCall2de56d12010-08-25 11:45:40 +00008075 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008076 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008077 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8078 if (Input.isInvalid()) return ExprError();
8079 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008080 if (resultType->isDependentType())
8081 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008082 if (resultType->isScalarType()) {
8083 // C99 6.5.3.3p1: ok, fallthrough;
8084 if (Context.getLangOptions().CPlusPlus) {
8085 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8086 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008087 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8088 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008089 }
John McCall2cd11fe2010-10-12 02:09:17 +00008090 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008091 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008092 if (Input.isInvalid()) return ExprError();
8093 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008094 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008095 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008096 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008097 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008098
Reid Spencer5f016e22007-07-11 17:01:13 +00008099 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008100 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008101 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008102 break;
John McCall2de56d12010-08-25 11:45:40 +00008103 case UO_Real:
8104 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008105 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008106 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008107 if (Input.isInvalid()) return ExprError();
8108 if (Input.get()->getValueKind() != VK_RValue &&
8109 Input.get()->getObjectKind() == OK_Ordinary)
8110 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008111 break;
John McCall2de56d12010-08-25 11:45:40 +00008112 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008113 resultType = Input.get()->getType();
8114 VK = Input.get()->getValueKind();
8115 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008116 break;
8117 }
John Wiegley429bb272011-04-08 18:41:53 +00008118 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008119 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008120
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008121 // Check for array bounds violations in the operand of the UnaryOperator,
8122 // except for the '*' and '&' operators that have to be handled specially
8123 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8124 // that are explicitly defined as valid by the standard).
8125 if (Opc != UO_AddrOf && Opc != UO_Deref)
8126 CheckArrayAccess(Input.get());
8127
John Wiegley429bb272011-04-08 18:41:53 +00008128 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008129 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008130}
8131
John McCall60d7b3a2010-08-24 06:29:42 +00008132ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008133 UnaryOperatorKind Opc,
8134 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008135 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008136 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008137 // Find all of the overloaded operators visible from this
8138 // point. We perform both an operator-name lookup from the local
8139 // scope and an argument-dependent lookup based on the types of
8140 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008141 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008142 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008143 if (S && OverOp != OO_None)
8144 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8145 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008146
John McCall9ae2f072010-08-23 23:25:46 +00008147 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008148 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008149
John McCall9ae2f072010-08-23 23:25:46 +00008150 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008151}
8152
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008153// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008154ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008155 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008156 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008157}
8158
Steve Naroff1b273c42007-09-16 14:56:35 +00008159/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008160ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008161 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008162 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008163 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008164 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008165 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008166}
8167
John McCallf85e1932011-06-15 23:02:42 +00008168/// Given the last statement in a statement-expression, check whether
8169/// the result is a producing expression (like a call to an
8170/// ns_returns_retained function) and, if so, rebuild it to hoist the
8171/// release out of the full-expression. Otherwise, return null.
8172/// Cannot fail.
8173static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8174 // Should always be wrapped with one of these.
8175 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8176 if (!cleanups) return 0;
8177
8178 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8179 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8180 return 0;
8181
8182 // Splice out the cast. This shouldn't modify any interesting
8183 // features of the statement.
8184 Expr *producer = cast->getSubExpr();
8185 assert(producer->getType() == cast->getType());
8186 assert(producer->getValueKind() == cast->getValueKind());
8187 cleanups->setSubExpr(producer);
8188 return cleanups;
8189}
8190
John McCall60d7b3a2010-08-24 06:29:42 +00008191ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008192Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008193 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008194 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8195 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8196
Douglas Gregordd8f5692010-03-10 04:54:39 +00008197 bool isFileScope
8198 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008199 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008200 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008201
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008202 // FIXME: there are a variety of strange constraints to enforce here, for
8203 // example, it is not possible to goto into a stmt expression apparently.
8204 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008205
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008206 // If there are sub stmts in the compound stmt, take the type of the last one
8207 // as the type of the stmtexpr.
8208 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008209 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008210 if (!Compound->body_empty()) {
8211 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008212 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008213 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008214 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8215 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008216 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008217 }
John McCallf85e1932011-06-15 23:02:42 +00008218
John Wiegley429bb272011-04-08 18:41:53 +00008219 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008220 // Do function/array conversion on the last expression, but not
8221 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008222 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8223 if (LastExpr.isInvalid())
8224 return ExprError();
8225 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008226
John Wiegley429bb272011-04-08 18:41:53 +00008227 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008228 // In ARC, if the final expression ends in a consume, splice
8229 // the consume out and bind it later. In the alternate case
8230 // (when dealing with a retainable type), the result
8231 // initialization will create a produce. In both cases the
8232 // result will be +1, and we'll need to balance that out with
8233 // a bind.
8234 if (Expr *rebuiltLastStmt
8235 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8236 LastExpr = rebuiltLastStmt;
8237 } else {
8238 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008239 InitializedEntity::InitializeResult(LPLoc,
8240 Ty,
8241 false),
8242 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008243 LastExpr);
8244 }
8245
John Wiegley429bb272011-04-08 18:41:53 +00008246 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008247 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008248 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008249 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008250 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008251 else
John Wiegley429bb272011-04-08 18:41:53 +00008252 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008253 StmtExprMayBindToTemp = true;
8254 }
8255 }
8256 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008257 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008258
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008259 // FIXME: Check that expression type is complete/non-abstract; statement
8260 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008261 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8262 if (StmtExprMayBindToTemp)
8263 return MaybeBindToTemporary(ResStmtExpr);
8264 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008265}
Steve Naroffd34e9152007-08-01 22:05:33 +00008266
John McCall60d7b3a2010-08-24 06:29:42 +00008267ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008268 TypeSourceInfo *TInfo,
8269 OffsetOfComponent *CompPtr,
8270 unsigned NumComponents,
8271 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008272 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008273 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008274 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008275
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008276 // We must have at least one component that refers to the type, and the first
8277 // one is known to be a field designator. Verify that the ArgTy represents
8278 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008279 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008280 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8281 << ArgTy << TypeRange);
8282
8283 // Type must be complete per C99 7.17p3 because a declaring a variable
8284 // with an incomplete type would be ill-formed.
8285 if (!Dependent
8286 && RequireCompleteType(BuiltinLoc, ArgTy,
8287 PDiag(diag::err_offsetof_incomplete_type)
8288 << TypeRange))
8289 return ExprError();
8290
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008291 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8292 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008293 // FIXME: This diagnostic isn't actually visible because the location is in
8294 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008295 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008296 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8297 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008298
8299 bool DidWarnAboutNonPOD = false;
8300 QualType CurrentType = ArgTy;
8301 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008302 SmallVector<OffsetOfNode, 4> Comps;
8303 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008304 for (unsigned i = 0; i != NumComponents; ++i) {
8305 const OffsetOfComponent &OC = CompPtr[i];
8306 if (OC.isBrackets) {
8307 // Offset of an array sub-field. TODO: Should we allow vector elements?
8308 if (!CurrentType->isDependentType()) {
8309 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8310 if(!AT)
8311 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8312 << CurrentType);
8313 CurrentType = AT->getElementType();
8314 } else
8315 CurrentType = Context.DependentTy;
8316
8317 // The expression must be an integral expression.
8318 // FIXME: An integral constant expression?
8319 Expr *Idx = static_cast<Expr*>(OC.U.E);
8320 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8321 !Idx->getType()->isIntegerType())
8322 return ExprError(Diag(Idx->getLocStart(),
8323 diag::err_typecheck_subscript_not_integer)
8324 << Idx->getSourceRange());
8325
8326 // Record this array index.
8327 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8328 Exprs.push_back(Idx);
8329 continue;
8330 }
8331
8332 // Offset of a field.
8333 if (CurrentType->isDependentType()) {
8334 // We have the offset of a field, but we can't look into the dependent
8335 // type. Just record the identifier of the field.
8336 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8337 CurrentType = Context.DependentTy;
8338 continue;
8339 }
8340
8341 // We need to have a complete type to look into.
8342 if (RequireCompleteType(OC.LocStart, CurrentType,
8343 diag::err_offsetof_incomplete_type))
8344 return ExprError();
8345
8346 // Look for the designated field.
8347 const RecordType *RC = CurrentType->getAs<RecordType>();
8348 if (!RC)
8349 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8350 << CurrentType);
8351 RecordDecl *RD = RC->getDecl();
8352
8353 // C++ [lib.support.types]p5:
8354 // The macro offsetof accepts a restricted set of type arguments in this
8355 // International Standard. type shall be a POD structure or a POD union
8356 // (clause 9).
8357 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8358 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008359 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008360 PDiag(diag::warn_offsetof_non_pod_type)
8361 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8362 << CurrentType))
8363 DidWarnAboutNonPOD = true;
8364 }
8365
8366 // Look for the field.
8367 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8368 LookupQualifiedName(R, RD);
8369 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008370 IndirectFieldDecl *IndirectMemberDecl = 0;
8371 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008372 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008373 MemberDecl = IndirectMemberDecl->getAnonField();
8374 }
8375
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008376 if (!MemberDecl)
8377 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8378 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8379 OC.LocEnd));
8380
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008381 // C99 7.17p3:
8382 // (If the specified member is a bit-field, the behavior is undefined.)
8383 //
8384 // We diagnose this as an error.
8385 if (MemberDecl->getBitWidth()) {
8386 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8387 << MemberDecl->getDeclName()
8388 << SourceRange(BuiltinLoc, RParenLoc);
8389 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8390 return ExprError();
8391 }
Eli Friedman19410a72010-08-05 10:11:36 +00008392
8393 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008394 if (IndirectMemberDecl)
8395 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008396
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008397 // If the member was found in a base class, introduce OffsetOfNodes for
8398 // the base class indirections.
8399 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8400 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008401 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008402 CXXBasePath &Path = Paths.front();
8403 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8404 B != BEnd; ++B)
8405 Comps.push_back(OffsetOfNode(B->Base));
8406 }
Eli Friedman19410a72010-08-05 10:11:36 +00008407
Francois Pichet87c2e122010-11-21 06:08:52 +00008408 if (IndirectMemberDecl) {
8409 for (IndirectFieldDecl::chain_iterator FI =
8410 IndirectMemberDecl->chain_begin(),
8411 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8412 assert(isa<FieldDecl>(*FI));
8413 Comps.push_back(OffsetOfNode(OC.LocStart,
8414 cast<FieldDecl>(*FI), OC.LocEnd));
8415 }
8416 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008417 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008418
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008419 CurrentType = MemberDecl->getType().getNonReferenceType();
8420 }
8421
8422 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8423 TInfo, Comps.data(), Comps.size(),
8424 Exprs.data(), Exprs.size(), RParenLoc));
8425}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008426
John McCall60d7b3a2010-08-24 06:29:42 +00008427ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008428 SourceLocation BuiltinLoc,
8429 SourceLocation TypeLoc,
8430 ParsedType argty,
8431 OffsetOfComponent *CompPtr,
8432 unsigned NumComponents,
8433 SourceLocation RPLoc) {
8434
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008435 TypeSourceInfo *ArgTInfo;
8436 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8437 if (ArgTy.isNull())
8438 return ExprError();
8439
Eli Friedman5a15dc12010-08-05 10:15:45 +00008440 if (!ArgTInfo)
8441 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8442
8443 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8444 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008445}
8446
8447
John McCall60d7b3a2010-08-24 06:29:42 +00008448ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008449 Expr *CondExpr,
8450 Expr *LHSExpr, Expr *RHSExpr,
8451 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008452 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8453
John McCallf89e55a2010-11-18 06:31:45 +00008454 ExprValueKind VK = VK_RValue;
8455 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008456 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008457 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008458 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008459 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008460 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008461 } else {
8462 // The conditional expression is required to be a constant expression.
8463 llvm::APSInt condEval(32);
8464 SourceLocation ExpLoc;
8465 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008466 return ExprError(Diag(ExpLoc,
8467 diag::err_typecheck_choose_expr_requires_constant)
8468 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008469
Sebastian Redl28507842009-02-26 14:39:58 +00008470 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008471 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8472
8473 resType = ActiveExpr->getType();
8474 ValueDependent = ActiveExpr->isValueDependent();
8475 VK = ActiveExpr->getValueKind();
8476 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008477 }
8478
Sebastian Redlf53597f2009-03-15 17:47:39 +00008479 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008480 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008481 resType->isDependentType(),
8482 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008483}
8484
Steve Naroff4eb206b2008-09-03 18:15:37 +00008485//===----------------------------------------------------------------------===//
8486// Clang Extensions.
8487//===----------------------------------------------------------------------===//
8488
8489/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008490void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008491 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8492 PushBlockScope(BlockScope, Block);
8493 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008494 if (BlockScope)
8495 PushDeclContext(BlockScope, Block);
8496 else
8497 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008498}
8499
Mike Stump98eb8a72009-02-04 22:31:32 +00008500void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008501 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008502 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008503 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008504
John McCallbf1a0282010-06-04 23:28:52 +00008505 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008506 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008507
John McCall711c52b2011-01-05 12:14:39 +00008508 // GetTypeForDeclarator always produces a function type for a block
8509 // literal signature. Furthermore, it is always a FunctionProtoType
8510 // unless the function was written with a typedef.
8511 assert(T->isFunctionType() &&
8512 "GetTypeForDeclarator made a non-function block signature");
8513
8514 // Look for an explicit signature in that function type.
8515 FunctionProtoTypeLoc ExplicitSignature;
8516
8517 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8518 if (isa<FunctionProtoTypeLoc>(tmp)) {
8519 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8520
8521 // Check whether that explicit signature was synthesized by
8522 // GetTypeForDeclarator. If so, don't save that as part of the
8523 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008524 if (ExplicitSignature.getLocalRangeBegin() ==
8525 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008526 // This would be much cheaper if we stored TypeLocs instead of
8527 // TypeSourceInfos.
8528 TypeLoc Result = ExplicitSignature.getResultLoc();
8529 unsigned Size = Result.getFullDataSize();
8530 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8531 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8532
8533 ExplicitSignature = FunctionProtoTypeLoc();
8534 }
John McCall82dc0092010-06-04 11:21:44 +00008535 }
Mike Stump1eb44332009-09-09 15:08:12 +00008536
John McCall711c52b2011-01-05 12:14:39 +00008537 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8538 CurBlock->FunctionType = T;
8539
8540 const FunctionType *Fn = T->getAs<FunctionType>();
8541 QualType RetTy = Fn->getResultType();
8542 bool isVariadic =
8543 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8544
John McCallc71a4912010-06-04 19:02:56 +00008545 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008546
John McCall82dc0092010-06-04 11:21:44 +00008547 // Don't allow returning a objc interface by value.
8548 if (RetTy->isObjCObjectType()) {
8549 Diag(ParamInfo.getSourceRange().getBegin(),
8550 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8551 return;
8552 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008553
John McCall82dc0092010-06-04 11:21:44 +00008554 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008555 // return type. TODO: what should we do with declarators like:
8556 // ^ * { ... }
8557 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008558 if (RetTy != Context.DependentTy)
8559 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008560
John McCall82dc0092010-06-04 11:21:44 +00008561 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008562 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008563 if (ExplicitSignature) {
8564 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8565 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008566 if (Param->getIdentifier() == 0 &&
8567 !Param->isImplicit() &&
8568 !Param->isInvalidDecl() &&
8569 !getLangOptions().CPlusPlus)
8570 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008571 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008572 }
John McCall82dc0092010-06-04 11:21:44 +00008573
8574 // Fake up parameter variables if we have a typedef, like
8575 // ^ fntype { ... }
8576 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8577 for (FunctionProtoType::arg_type_iterator
8578 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8579 ParmVarDecl *Param =
8580 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8581 ParamInfo.getSourceRange().getBegin(),
8582 *I);
John McCallc71a4912010-06-04 19:02:56 +00008583 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008584 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008585 }
John McCall82dc0092010-06-04 11:21:44 +00008586
John McCallc71a4912010-06-04 19:02:56 +00008587 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008588 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008589 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008590 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8591 CurBlock->TheDecl->param_end(),
8592 /*CheckParameterNames=*/false);
8593 }
8594
John McCall82dc0092010-06-04 11:21:44 +00008595 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008596 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008597
John McCallc71a4912010-06-04 19:02:56 +00008598 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008599 Diag(ParamInfo.getAttributes()->getLoc(),
8600 diag::warn_attribute_sentinel_not_variadic) << 1;
8601 // FIXME: remove the attribute.
8602 }
8603
8604 // Put the parameter variables in scope. We can bail out immediately
8605 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008606 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008607 return;
8608
Steve Naroff090276f2008-10-10 01:28:17 +00008609 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008610 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8611 (*AI)->setOwningFunction(CurBlock->TheDecl);
8612
Steve Naroff090276f2008-10-10 01:28:17 +00008613 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008614 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008615 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008616
Steve Naroff090276f2008-10-10 01:28:17 +00008617 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008618 }
John McCall7a9813c2010-01-22 00:28:27 +00008619 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008620}
8621
8622/// ActOnBlockError - If there is an error parsing a block, this callback
8623/// is invoked to pop the information about the block from the action impl.
8624void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008625 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008626 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008627 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008628}
8629
8630/// ActOnBlockStmtExpr - This is called when the body of a block statement
8631/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008632ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008633 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008634 // If blocks are disabled, emit an error.
8635 if (!LangOpts.Blocks)
8636 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008637
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008638 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008639
Steve Naroff090276f2008-10-10 01:28:17 +00008640 PopDeclContext();
8641
Steve Naroff4eb206b2008-09-03 18:15:37 +00008642 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008643 if (!BSI->ReturnType.isNull())
8644 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008645
Mike Stump56925862009-07-28 22:04:01 +00008646 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008647 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008648
John McCall469a1eb2011-02-02 13:00:07 +00008649 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008650 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8651 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008652
John McCallc71a4912010-06-04 19:02:56 +00008653 // If the user wrote a function type in some form, try to use that.
8654 if (!BSI->FunctionType.isNull()) {
8655 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8656
8657 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8658 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8659
8660 // Turn protoless block types into nullary block types.
8661 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008662 FunctionProtoType::ExtProtoInfo EPI;
8663 EPI.ExtInfo = Ext;
8664 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008665
8666 // Otherwise, if we don't need to change anything about the function type,
8667 // preserve its sugar structure.
8668 } else if (FTy->getResultType() == RetTy &&
8669 (!NoReturn || FTy->getNoReturnAttr())) {
8670 BlockTy = BSI->FunctionType;
8671
8672 // Otherwise, make the minimal modifications to the function type.
8673 } else {
8674 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008675 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8676 EPI.TypeQuals = 0; // FIXME: silently?
8677 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008678 BlockTy = Context.getFunctionType(RetTy,
8679 FPT->arg_type_begin(),
8680 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008681 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008682 }
8683
8684 // If we don't have a function type, just build one from nothing.
8685 } else {
John McCalle23cf432010-12-14 08:05:40 +00008686 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008687 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008688 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008690
John McCallc71a4912010-06-04 19:02:56 +00008691 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8692 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008693 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008694
Chris Lattner17a78302009-04-19 05:28:12 +00008695 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008696 if (getCurFunction()->NeedsScopeChecking() &&
8697 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008698 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008699
Chris Lattnere476bdc2011-02-17 23:58:47 +00008700 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008701
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008702 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8703 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8704 const VarDecl *variable = ci->getVariable();
8705 QualType T = variable->getType();
8706 QualType::DestructionKind destructKind = T.isDestructedType();
8707 if (destructKind != QualType::DK_none)
8708 getCurFunction()->setHasBranchProtectedScope();
8709 }
8710
Benjamin Kramerd2486192011-07-12 14:11:05 +00008711 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8712 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8713 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8714
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008715 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008716}
8717
John McCall60d7b3a2010-08-24 06:29:42 +00008718ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008719 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008720 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008721 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008722 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008723 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008724}
8725
John McCall60d7b3a2010-08-24 06:29:42 +00008726ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008727 Expr *E, TypeSourceInfo *TInfo,
8728 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008729 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008730
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008731 // Get the va_list type
8732 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008733 if (VaListType->isArrayType()) {
8734 // Deal with implicit array decay; for example, on x86-64,
8735 // va_list is an array, but it's supposed to decay to
8736 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008737 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008738 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008739 ExprResult Result = UsualUnaryConversions(E);
8740 if (Result.isInvalid())
8741 return ExprError();
8742 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008743 } else {
8744 // Otherwise, the va_list argument must be an l-value because
8745 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008746 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008747 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008748 return ExprError();
8749 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008750
Douglas Gregordd027302009-05-19 23:10:31 +00008751 if (!E->isTypeDependent() &&
8752 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008753 return ExprError(Diag(E->getLocStart(),
8754 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008755 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008756 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008757
David Majnemer0adde122011-06-14 05:17:32 +00008758 if (!TInfo->getType()->isDependentType()) {
8759 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8760 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8761 << TInfo->getTypeLoc().getSourceRange()))
8762 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008763
David Majnemer0adde122011-06-14 05:17:32 +00008764 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8765 TInfo->getType(),
8766 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8767 << TInfo->getTypeLoc().getSourceRange()))
8768 return ExprError();
8769
Douglas Gregor4eb75222011-07-30 06:45:27 +00008770 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008771 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008772 TInfo->getType()->isObjCLifetimeType()
8773 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8774 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008775 << TInfo->getType()
8776 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008777 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008778
8779 // Check for va_arg where arguments of the given type will be promoted
8780 // (i.e. this va_arg is guaranteed to have undefined behavior).
8781 QualType PromoteType;
8782 if (TInfo->getType()->isPromotableIntegerType()) {
8783 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8784 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8785 PromoteType = QualType();
8786 }
8787 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8788 PromoteType = Context.DoubleTy;
8789 if (!PromoteType.isNull())
8790 Diag(TInfo->getTypeLoc().getBeginLoc(),
8791 diag::warn_second_parameter_to_va_arg_never_compatible)
8792 << TInfo->getType()
8793 << PromoteType
8794 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008795 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008796
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008797 QualType T = TInfo->getType().getNonLValueExprType(Context);
8798 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008799}
8800
John McCall60d7b3a2010-08-24 06:29:42 +00008801ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008802 // The type of __null will be int or long, depending on the size of
8803 // pointers on the target.
8804 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008805 unsigned pw = Context.Target.getPointerWidth(0);
8806 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008807 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008808 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008809 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008810 else if (pw == Context.Target.getLongLongWidth())
8811 Ty = Context.LongLongTy;
8812 else {
8813 assert(!"I don't know size of pointer!");
8814 Ty = Context.IntTy;
8815 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008816
Sebastian Redlf53597f2009-03-15 17:47:39 +00008817 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008818}
8819
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008820static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008821 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008822 if (!SemaRef.getLangOptions().ObjC1)
8823 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008824
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008825 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8826 if (!PT)
8827 return;
8828
8829 // Check if the destination is of type 'id'.
8830 if (!PT->isObjCIdType()) {
8831 // Check if the destination is the 'NSString' interface.
8832 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8833 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8834 return;
8835 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008836
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008837 // Strip off any parens and casts.
8838 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008839 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008840 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008841
Douglas Gregor849b2432010-03-31 17:46:05 +00008842 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008843}
8844
Chris Lattner5cf216b2008-01-04 18:04:52 +00008845bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8846 SourceLocation Loc,
8847 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008848 Expr *SrcExpr, AssignmentAction Action,
8849 bool *Complained) {
8850 if (Complained)
8851 *Complained = false;
8852
Chris Lattner5cf216b2008-01-04 18:04:52 +00008853 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008854 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008855 bool isInvalid = false;
8856 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008857 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008858 ConversionFixItGenerator ConvHints;
8859 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008860
Chris Lattner5cf216b2008-01-04 18:04:52 +00008861 switch (ConvTy) {
8862 default: assert(0 && "Unknown conversion type");
8863 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008864 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008865 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008866 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8867 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008868 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008869 case IntToPointer:
8870 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008871 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8872 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008873 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008874 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008875 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008876 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008877 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8878 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008879 if (Hint.isNull() && !CheckInferredResultType) {
8880 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8881 }
8882 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008883 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008884 case IncompatiblePointerSign:
8885 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8886 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008887 case FunctionVoidPointer:
8888 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8889 break;
John McCall86c05f32011-02-01 00:10:29 +00008890 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008891 // Perform array-to-pointer decay if necessary.
8892 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8893
John McCall86c05f32011-02-01 00:10:29 +00008894 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8895 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8896 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8897 DiagKind = diag::err_typecheck_incompatible_address_space;
8898 break;
John McCallf85e1932011-06-15 23:02:42 +00008899
8900
8901 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008902 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008903 break;
John McCall86c05f32011-02-01 00:10:29 +00008904 }
8905
8906 llvm_unreachable("unknown error case for discarding qualifiers!");
8907 // fallthrough
8908 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008909 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008910 // If the qualifiers lost were because we were applying the
8911 // (deprecated) C++ conversion from a string literal to a char*
8912 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8913 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008914 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008915 // bit of refactoring (so that the second argument is an
8916 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008917 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008918 // C++ semantics.
8919 if (getLangOptions().CPlusPlus &&
8920 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8921 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008922 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8923 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008924 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008925 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008926 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008927 case IntToBlockPointer:
8928 DiagKind = diag::err_int_to_block_pointer;
8929 break;
8930 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008931 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008932 break;
Steve Naroff39579072008-10-14 22:18:38 +00008933 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008934 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008935 // it can give a more specific diagnostic.
8936 DiagKind = diag::warn_incompatible_qualified_id;
8937 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008938 case IncompatibleVectors:
8939 DiagKind = diag::warn_incompatible_vectors;
8940 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00008941 case IncompatibleObjCWeakRef:
8942 DiagKind = diag::err_arc_weak_unavailable_assign;
8943 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008944 case Incompatible:
8945 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00008946 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8947 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008948 isInvalid = true;
8949 break;
8950 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008951
Douglas Gregord4eea832010-04-09 00:35:39 +00008952 QualType FirstType, SecondType;
8953 switch (Action) {
8954 case AA_Assigning:
8955 case AA_Initializing:
8956 // The destination type comes first.
8957 FirstType = DstType;
8958 SecondType = SrcType;
8959 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008960
Douglas Gregord4eea832010-04-09 00:35:39 +00008961 case AA_Returning:
8962 case AA_Passing:
8963 case AA_Converting:
8964 case AA_Sending:
8965 case AA_Casting:
8966 // The source type comes first.
8967 FirstType = SrcType;
8968 SecondType = DstType;
8969 break;
8970 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008971
Anna Zaks67221552011-07-28 19:51:27 +00008972 PartialDiagnostic FDiag = PDiag(DiagKind);
8973 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8974
8975 // If we can fix the conversion, suggest the FixIts.
8976 assert(ConvHints.isNull() || Hint.isNull());
8977 if (!ConvHints.isNull()) {
8978 for (llvm::SmallVector<FixItHint, 1>::iterator
8979 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8980 HI != HE; ++HI)
8981 FDiag << *HI;
8982 } else {
8983 FDiag << Hint;
8984 }
8985 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8986
8987 Diag(Loc, FDiag);
8988
Douglas Gregor926df6c2011-06-11 01:09:30 +00008989 if (CheckInferredResultType)
8990 EmitRelatedResultTypeNote(SrcExpr);
8991
Douglas Gregora41a8c52010-04-22 00:20:18 +00008992 if (Complained)
8993 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008994 return isInvalid;
8995}
Anders Carlssone21555e2008-11-30 19:50:32 +00008996
Chris Lattner3bf68932009-04-25 21:59:05 +00008997bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008998 llvm::APSInt ICEResult;
8999 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9000 if (Result)
9001 *Result = ICEResult;
9002 return false;
9003 }
9004
Anders Carlssone21555e2008-11-30 19:50:32 +00009005 Expr::EvalResult EvalResult;
9006
Mike Stumpeed9cac2009-02-19 03:04:26 +00009007 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009008 EvalResult.HasSideEffects) {
9009 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9010
9011 if (EvalResult.Diag) {
9012 // We only show the note if it's not the usual "invalid subexpression"
9013 // or if it's actually in a subexpression.
9014 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9015 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9016 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9017 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009018
Anders Carlssone21555e2008-11-30 19:50:32 +00009019 return true;
9020 }
9021
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009022 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9023 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009024
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009025 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009026 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9027 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009028 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009029
Anders Carlssone21555e2008-11-30 19:50:32 +00009030 if (Result)
9031 *Result = EvalResult.Val.getInt();
9032 return false;
9033}
Douglas Gregore0762c92009-06-19 23:52:42 +00009034
Douglas Gregor2afce722009-11-26 00:44:06 +00009035void
Mike Stump1eb44332009-09-09 15:08:12 +00009036Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009037 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009038 ExpressionEvaluationContextRecord(NewContext,
9039 ExprTemporaries.size(),
9040 ExprNeedsCleanups));
9041 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009042}
9043
Richard Trieu67e29332011-08-02 04:35:43 +00009044void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009045 // Pop the current expression evaluation context off the stack.
9046 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9047 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009048
Douglas Gregor06d33692009-12-12 07:57:52 +00009049 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9050 if (Rec.PotentiallyReferenced) {
9051 // Mark any remaining declarations in the current position of the stack
9052 // as "referenced". If they were not meant to be referenced, semantic
9053 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009054 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009055 I = Rec.PotentiallyReferenced->begin(),
9056 IEnd = Rec.PotentiallyReferenced->end();
9057 I != IEnd; ++I)
9058 MarkDeclarationReferenced(I->first, I->second);
9059 }
9060
9061 if (Rec.PotentiallyDiagnosed) {
9062 // Emit any pending diagnostics.
9063 for (PotentiallyEmittedDiagnostics::iterator
9064 I = Rec.PotentiallyDiagnosed->begin(),
9065 IEnd = Rec.PotentiallyDiagnosed->end();
9066 I != IEnd; ++I)
9067 Diag(I->first, I->second);
9068 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009069 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009070
9071 // When are coming out of an unevaluated context, clear out any
9072 // temporaries that we may have created as part of the evaluation of
9073 // the expression in that context: they aren't relevant because they
9074 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009075 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009076 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9077 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009078 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9079
9080 // Otherwise, merge the contexts together.
9081 } else {
9082 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9083 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009084
9085 // Destroy the popped expression evaluation record.
9086 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009087}
Douglas Gregore0762c92009-06-19 23:52:42 +00009088
John McCallf85e1932011-06-15 23:02:42 +00009089void Sema::DiscardCleanupsInEvaluationContext() {
9090 ExprTemporaries.erase(
9091 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9092 ExprTemporaries.end());
9093 ExprNeedsCleanups = false;
9094}
9095
Douglas Gregore0762c92009-06-19 23:52:42 +00009096/// \brief Note that the given declaration was referenced in the source code.
9097///
9098/// This routine should be invoke whenever a given declaration is referenced
9099/// in the source code, and where that reference occurred. If this declaration
9100/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9101/// C99 6.9p3), then the declaration will be marked as used.
9102///
9103/// \param Loc the location where the declaration was referenced.
9104///
9105/// \param D the declaration that has been referenced by the source code.
9106void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9107 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009108
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009109 D->setReferenced();
9110
Douglas Gregorc070cc62010-06-17 23:14:26 +00009111 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009112 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009113
Richard Trieu67e29332011-08-02 04:35:43 +00009114 // Mark a parameter or variable declaration "used", regardless of whether
9115 // we're in a template or not. The reason for this is that unevaluated
9116 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9117 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009118 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009119 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009120 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009121 return;
9122 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009123
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009124 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9125 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009126
Douglas Gregore0762c92009-06-19 23:52:42 +00009127 // Do not mark anything as "used" within a dependent context; wait for
9128 // an instantiation.
9129 if (CurContext->isDependentContext())
9130 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009131
Douglas Gregor2afce722009-11-26 00:44:06 +00009132 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009133 case Unevaluated:
9134 // We are in an expression that is not potentially evaluated; do nothing.
9135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009136
Douglas Gregorac7610d2009-06-22 20:57:11 +00009137 case PotentiallyEvaluated:
9138 // We are in a potentially-evaluated expression, so this declaration is
9139 // "used"; handle this below.
9140 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009141
Douglas Gregorac7610d2009-06-22 20:57:11 +00009142 case PotentiallyPotentiallyEvaluated:
9143 // We are in an expression that may be potentially evaluated; queue this
9144 // declaration reference until we know whether the expression is
9145 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009146 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009147 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009148
9149 case PotentiallyEvaluatedIfUsed:
9150 // Referenced declarations will only be used if the construct in the
9151 // containing expression is used.
9152 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009153 }
Mike Stump1eb44332009-09-09 15:08:12 +00009154
Douglas Gregore0762c92009-06-19 23:52:42 +00009155 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009156 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009157 if (Constructor->isDefaulted()) {
9158 if (Constructor->isDefaultConstructor()) {
9159 if (Constructor->isTrivial())
9160 return;
9161 if (!Constructor->isUsed(false))
9162 DefineImplicitDefaultConstructor(Loc, Constructor);
9163 } else if (Constructor->isCopyConstructor()) {
9164 if (!Constructor->isUsed(false))
9165 DefineImplicitCopyConstructor(Loc, Constructor);
9166 } else if (Constructor->isMoveConstructor()) {
9167 if (!Constructor->isUsed(false))
9168 DefineImplicitMoveConstructor(Loc, Constructor);
9169 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009170 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009171
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009172 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009173 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009174 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009175 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009176 if (Destructor->isVirtual())
9177 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009178 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009179 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009180 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009181 if (!MethodDecl->isUsed(false)) {
9182 if (MethodDecl->isCopyAssignmentOperator())
9183 DefineImplicitCopyAssignment(Loc, MethodDecl);
9184 else
9185 DefineImplicitMoveAssignment(Loc, MethodDecl);
9186 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009187 } else if (MethodDecl->isVirtual())
9188 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009189 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009190 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009191 // Recursive functions should be marked when used from another function.
9192 if (CurContext == Function) return;
9193
Mike Stump1eb44332009-09-09 15:08:12 +00009194 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009195 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009196 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009197 bool AlreadyInstantiated = false;
9198 if (FunctionTemplateSpecializationInfo *SpecInfo
9199 = Function->getTemplateSpecializationInfo()) {
9200 if (SpecInfo->getPointOfInstantiation().isInvalid())
9201 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009202 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009203 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009204 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009205 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009206 = Function->getMemberSpecializationInfo()) {
9207 if (MSInfo->getPointOfInstantiation().isInvalid())
9208 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009209 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009210 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009211 AlreadyInstantiated = true;
9212 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009213
Douglas Gregor60406be2010-01-16 22:29:39 +00009214 if (!AlreadyInstantiated) {
9215 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9216 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9217 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9218 Loc));
9219 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009220 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009221 }
John McCall15e310a2011-02-19 02:53:41 +00009222 } else {
9223 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009224 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9225 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009226 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009227 MarkDeclarationReferenced(Loc, *i);
9228 }
John McCall15e310a2011-02-19 02:53:41 +00009229 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009230
John McCall15e310a2011-02-19 02:53:41 +00009231 // Keep track of used but undefined functions.
9232 if (!Function->isPure() && !Function->hasBody() &&
9233 Function->getLinkage() != ExternalLinkage) {
9234 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9235 if (old.isInvalid()) old = Loc;
9236 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009237
John McCall15e310a2011-02-19 02:53:41 +00009238 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009239 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009240 }
Mike Stump1eb44332009-09-09 15:08:12 +00009241
Douglas Gregore0762c92009-06-19 23:52:42 +00009242 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009243 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009244 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009245 Var->getInstantiatedFromStaticDataMember()) {
9246 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9247 assert(MSInfo && "Missing member specialization information?");
9248 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9249 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9250 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009251 // This is a modification of an existing AST node. Notify listeners.
9252 if (ASTMutationListener *L = getASTMutationListener())
9253 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009254 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009255 }
9256 }
Mike Stump1eb44332009-09-09 15:08:12 +00009257
John McCall77efc682011-02-21 19:25:48 +00009258 // Keep track of used but undefined variables. We make a hole in
9259 // the warning for static const data members with in-line
9260 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009261 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009262 && Var->getLinkage() != ExternalLinkage
9263 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009264 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9265 if (old.isInvalid()) old = Loc;
9266 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009267
Douglas Gregore0762c92009-06-19 23:52:42 +00009268 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009269 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009270 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009271}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009272
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009273namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009274 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009275 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009276 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009277 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9278 Sema &S;
9279 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009280
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009281 public:
9282 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009283
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009284 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009285
9286 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9287 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009288 };
9289}
9290
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009291bool MarkReferencedDecls::TraverseTemplateArgument(
9292 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009293 if (Arg.getKind() == TemplateArgument::Declaration) {
9294 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9295 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009296
9297 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009298}
9299
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009300bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009301 if (ClassTemplateSpecializationDecl *Spec
9302 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9303 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009304 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009305 }
9306
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009307 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009308}
9309
9310void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9311 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009312 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009313}
9314
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009315namespace {
9316 /// \brief Helper class that marks all of the declarations referenced by
9317 /// potentially-evaluated subexpressions as "referenced".
9318 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9319 Sema &S;
9320
9321 public:
9322 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9323
9324 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9325
9326 void VisitDeclRefExpr(DeclRefExpr *E) {
9327 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9328 }
9329
9330 void VisitMemberExpr(MemberExpr *E) {
9331 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009332 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009333 }
9334
9335 void VisitCXXNewExpr(CXXNewExpr *E) {
9336 if (E->getConstructor())
9337 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9338 if (E->getOperatorNew())
9339 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9340 if (E->getOperatorDelete())
9341 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009342 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009343 }
9344
9345 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9346 if (E->getOperatorDelete())
9347 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009348 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9349 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9350 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9351 S.MarkDeclarationReferenced(E->getLocStart(),
9352 S.LookupDestructor(Record));
9353 }
9354
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009355 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009356 }
9357
9358 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9359 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009360 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009361 }
9362
9363 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9364 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9365 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009366
9367 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9368 Visit(E->getExpr());
9369 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009370 };
9371}
9372
9373/// \brief Mark any declarations that appear within this expression or any
9374/// potentially-evaluated subexpressions as "referenced".
9375void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9376 EvaluatedExprMarker(*this).Visit(E);
9377}
9378
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009379/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9380/// of the program being compiled.
9381///
9382/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009383/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009384/// possibility that the code will actually be executable. Code in sizeof()
9385/// expressions, code used only during overload resolution, etc., are not
9386/// potentially evaluated. This routine will suppress such diagnostics or,
9387/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009388/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009389/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009390///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009391/// This routine should be used for all diagnostics that describe the run-time
9392/// behavior of a program, such as passing a non-POD value through an ellipsis.
9393/// Failure to do so will likely result in spurious diagnostics or failures
9394/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009395bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009396 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009397 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009398 case Unevaluated:
9399 // The argument will never be evaluated, so don't complain.
9400 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009401
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009402 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009403 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009404 if (stmt && getCurFunctionOrMethodDecl()) {
9405 FunctionScopes.back()->PossiblyUnreachableDiags.
9406 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9407 }
9408 else
9409 Diag(Loc, PD);
9410
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009411 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009412
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009413 case PotentiallyPotentiallyEvaluated:
9414 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9415 break;
9416 }
9417
9418 return false;
9419}
9420
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009421bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9422 CallExpr *CE, FunctionDecl *FD) {
9423 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9424 return false;
9425
9426 PartialDiagnostic Note =
9427 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9428 << FD->getDeclName() : PDiag();
9429 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009430
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009431 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009432 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009433 PDiag(diag::err_call_function_incomplete_return)
9434 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009435 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009436 << CE->getSourceRange(),
9437 std::make_pair(NoteLoc, Note)))
9438 return true;
9439
9440 return false;
9441}
9442
Douglas Gregor92c3a042011-01-19 16:50:08 +00009443// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009444// will prevent this condition from triggering, which is what we want.
9445void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9446 SourceLocation Loc;
9447
John McCalla52ef082009-11-11 02:41:58 +00009448 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009449 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009450
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009451 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009452 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009453 return;
9454
Douglas Gregor92c3a042011-01-19 16:50:08 +00009455 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9456
John McCallc8d8ac52009-11-12 00:06:05 +00009457 // Greylist some idioms by putting them into a warning subcategory.
9458 if (ObjCMessageExpr *ME
9459 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9460 Selector Sel = ME->getSelector();
9461
John McCallc8d8ac52009-11-12 00:06:05 +00009462 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009463 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009464 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9465
9466 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009467 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009468 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9469 }
John McCalla52ef082009-11-11 02:41:58 +00009470
John McCall5a881bb2009-10-12 21:59:07 +00009471 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009472 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009473 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009474 return;
9475
Douglas Gregor92c3a042011-01-19 16:50:08 +00009476 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009477 Loc = Op->getOperatorLoc();
9478 } else {
9479 // Not an assignment.
9480 return;
9481 }
9482
Douglas Gregor55b38842010-04-14 16:09:52 +00009483 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009484
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009485 SourceLocation Open = E->getSourceRange().getBegin();
9486 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9487 Diag(Loc, diag::note_condition_assign_silence)
9488 << FixItHint::CreateInsertion(Open, "(")
9489 << FixItHint::CreateInsertion(Close, ")");
9490
Douglas Gregor92c3a042011-01-19 16:50:08 +00009491 if (IsOrAssign)
9492 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9493 << FixItHint::CreateReplacement(Loc, "!=");
9494 else
9495 Diag(Loc, diag::note_condition_assign_to_comparison)
9496 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009497}
9498
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009499/// \brief Redundant parentheses over an equality comparison can indicate
9500/// that the user intended an assignment used as condition.
9501void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009502 // Don't warn if the parens came from a macro.
9503 SourceLocation parenLoc = parenE->getLocStart();
9504 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9505 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009506 // Don't warn for dependent expressions.
9507 if (parenE->isTypeDependent())
9508 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009509
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009510 Expr *E = parenE->IgnoreParens();
9511
9512 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009513 if (opE->getOpcode() == BO_EQ &&
9514 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9515 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009516 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009517
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009518 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009519 Diag(Loc, diag::note_equality_comparison_silence)
9520 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9521 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009522 Diag(Loc, diag::note_equality_comparison_to_assign)
9523 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009524 }
9525}
9526
John Wiegley429bb272011-04-08 18:41:53 +00009527ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009528 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009529 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9530 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009531
John McCall864c0412011-04-26 20:42:42 +00009532 ExprResult result = CheckPlaceholderExpr(E);
9533 if (result.isInvalid()) return ExprError();
9534 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009535
John McCall864c0412011-04-26 20:42:42 +00009536 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009537 if (getLangOptions().CPlusPlus)
9538 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9539
John Wiegley429bb272011-04-08 18:41:53 +00009540 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9541 if (ERes.isInvalid())
9542 return ExprError();
9543 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009544
9545 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009546 if (!T->isScalarType()) { // C99 6.8.4.1p1
9547 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9548 << T << E->getSourceRange();
9549 return ExprError();
9550 }
John McCall5a881bb2009-10-12 21:59:07 +00009551 }
9552
John Wiegley429bb272011-04-08 18:41:53 +00009553 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009554}
Douglas Gregor586596f2010-05-06 17:25:47 +00009555
John McCall60d7b3a2010-08-24 06:29:42 +00009556ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9557 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009558 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009559 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009560
9561 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009562}
John McCall2a984ca2010-10-12 00:20:44 +00009563
John McCall1de4d4e2011-04-07 08:22:57 +00009564namespace {
John McCall755d8492011-04-12 00:42:48 +00009565 /// A visitor for rebuilding a call to an __unknown_any expression
9566 /// to have an appropriate type.
9567 struct RebuildUnknownAnyFunction
9568 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9569
9570 Sema &S;
9571
9572 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9573
9574 ExprResult VisitStmt(Stmt *S) {
9575 llvm_unreachable("unexpected statement!");
9576 return ExprError();
9577 }
9578
9579 ExprResult VisitExpr(Expr *expr) {
9580 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9581 << expr->getSourceRange();
9582 return ExprError();
9583 }
9584
9585 /// Rebuild an expression which simply semantically wraps another
9586 /// expression which it shares the type and value kind of.
9587 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9588 ExprResult subResult = Visit(expr->getSubExpr());
9589 if (subResult.isInvalid()) return ExprError();
9590
9591 Expr *subExpr = subResult.take();
9592 expr->setSubExpr(subExpr);
9593 expr->setType(subExpr->getType());
9594 expr->setValueKind(subExpr->getValueKind());
9595 assert(expr->getObjectKind() == OK_Ordinary);
9596 return expr;
9597 }
9598
9599 ExprResult VisitParenExpr(ParenExpr *paren) {
9600 return rebuildSugarExpr(paren);
9601 }
9602
9603 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9604 return rebuildSugarExpr(op);
9605 }
9606
9607 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9608 ExprResult subResult = Visit(op->getSubExpr());
9609 if (subResult.isInvalid()) return ExprError();
9610
9611 Expr *subExpr = subResult.take();
9612 op->setSubExpr(subExpr);
9613 op->setType(S.Context.getPointerType(subExpr->getType()));
9614 assert(op->getValueKind() == VK_RValue);
9615 assert(op->getObjectKind() == OK_Ordinary);
9616 return op;
9617 }
9618
9619 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9620 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9621
9622 expr->setType(decl->getType());
9623
9624 assert(expr->getValueKind() == VK_RValue);
9625 if (S.getLangOptions().CPlusPlus &&
9626 !(isa<CXXMethodDecl>(decl) &&
9627 cast<CXXMethodDecl>(decl)->isInstance()))
9628 expr->setValueKind(VK_LValue);
9629
9630 return expr;
9631 }
9632
9633 ExprResult VisitMemberExpr(MemberExpr *mem) {
9634 return resolveDecl(mem, mem->getMemberDecl());
9635 }
9636
9637 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9638 return resolveDecl(ref, ref->getDecl());
9639 }
9640 };
9641}
9642
9643/// Given a function expression of unknown-any type, try to rebuild it
9644/// to have a function type.
9645static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9646 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9647 if (result.isInvalid()) return ExprError();
9648 return S.DefaultFunctionArrayConversion(result.take());
9649}
9650
9651namespace {
John McCall379b5152011-04-11 07:02:50 +00009652 /// A visitor for rebuilding an expression of type __unknown_anytype
9653 /// into one which resolves the type directly on the referring
9654 /// expression. Strict preservation of the original source
9655 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009656 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009657 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009658
9659 Sema &S;
9660
9661 /// The current destination type.
9662 QualType DestType;
9663
9664 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9665 : S(S), DestType(castType) {}
9666
John McCalla5fc4722011-04-09 22:50:59 +00009667 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009668 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009669 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009670 }
9671
John McCall379b5152011-04-11 07:02:50 +00009672 ExprResult VisitExpr(Expr *expr) {
9673 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9674 << expr->getSourceRange();
9675 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009676 }
9677
John McCall379b5152011-04-11 07:02:50 +00009678 ExprResult VisitCallExpr(CallExpr *call);
9679 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9680
John McCalla5fc4722011-04-09 22:50:59 +00009681 /// Rebuild an expression which simply semantically wraps another
9682 /// expression which it shares the type and value kind of.
9683 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9684 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009685 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009686 Expr *subExpr = subResult.take();
9687 expr->setSubExpr(subExpr);
9688 expr->setType(subExpr->getType());
9689 expr->setValueKind(subExpr->getValueKind());
9690 assert(expr->getObjectKind() == OK_Ordinary);
9691 return expr;
9692 }
John McCall1de4d4e2011-04-07 08:22:57 +00009693
John McCalla5fc4722011-04-09 22:50:59 +00009694 ExprResult VisitParenExpr(ParenExpr *paren) {
9695 return rebuildSugarExpr(paren);
9696 }
9697
9698 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9699 return rebuildSugarExpr(op);
9700 }
9701
John McCall755d8492011-04-12 00:42:48 +00009702 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9703 const PointerType *ptr = DestType->getAs<PointerType>();
9704 if (!ptr) {
9705 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9706 << op->getSourceRange();
9707 return ExprError();
9708 }
9709 assert(op->getValueKind() == VK_RValue);
9710 assert(op->getObjectKind() == OK_Ordinary);
9711 op->setType(DestType);
9712
9713 // Build the sub-expression as if it were an object of the pointee type.
9714 DestType = ptr->getPointeeType();
9715 ExprResult subResult = Visit(op->getSubExpr());
9716 if (subResult.isInvalid()) return ExprError();
9717 op->setSubExpr(subResult.take());
9718 return op;
9719 }
9720
John McCall379b5152011-04-11 07:02:50 +00009721 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009722
John McCall755d8492011-04-12 00:42:48 +00009723 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009724
John McCall755d8492011-04-12 00:42:48 +00009725 ExprResult VisitMemberExpr(MemberExpr *mem) {
9726 return resolveDecl(mem, mem->getMemberDecl());
9727 }
John McCalla5fc4722011-04-09 22:50:59 +00009728
9729 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009730 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009731 }
9732 };
9733}
9734
John McCall379b5152011-04-11 07:02:50 +00009735/// Rebuilds a call expression which yielded __unknown_anytype.
9736ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9737 Expr *callee = call->getCallee();
9738
9739 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009740 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009741 FK_FunctionPointer,
9742 FK_BlockPointer
9743 };
9744
9745 FnKind kind;
9746 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009747 if (type == S.Context.BoundMemberTy) {
9748 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9749 kind = FK_MemberFunction;
9750 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009751 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9752 type = ptr->getPointeeType();
9753 kind = FK_FunctionPointer;
9754 } else {
9755 type = type->castAs<BlockPointerType>()->getPointeeType();
9756 kind = FK_BlockPointer;
9757 }
9758 const FunctionType *fnType = type->castAs<FunctionType>();
9759
9760 // Verify that this is a legal result type of a function.
9761 if (DestType->isArrayType() || DestType->isFunctionType()) {
9762 unsigned diagID = diag::err_func_returning_array_function;
9763 if (kind == FK_BlockPointer)
9764 diagID = diag::err_block_returning_array_function;
9765
9766 S.Diag(call->getExprLoc(), diagID)
9767 << DestType->isFunctionType() << DestType;
9768 return ExprError();
9769 }
9770
9771 // Otherwise, go ahead and set DestType as the call's result.
9772 call->setType(DestType.getNonLValueExprType(S.Context));
9773 call->setValueKind(Expr::getValueKindForType(DestType));
9774 assert(call->getObjectKind() == OK_Ordinary);
9775
9776 // Rebuild the function type, replacing the result type with DestType.
9777 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9778 DestType = S.Context.getFunctionType(DestType,
9779 proto->arg_type_begin(),
9780 proto->getNumArgs(),
9781 proto->getExtProtoInfo());
9782 else
9783 DestType = S.Context.getFunctionNoProtoType(DestType,
9784 fnType->getExtInfo());
9785
9786 // Rebuild the appropriate pointer-to-function type.
9787 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009788 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009789 // Nothing to do.
9790 break;
9791
9792 case FK_FunctionPointer:
9793 DestType = S.Context.getPointerType(DestType);
9794 break;
9795
9796 case FK_BlockPointer:
9797 DestType = S.Context.getBlockPointerType(DestType);
9798 break;
9799 }
9800
9801 // Finally, we can recurse.
9802 ExprResult calleeResult = Visit(callee);
9803 if (!calleeResult.isUsable()) return ExprError();
9804 call->setCallee(calleeResult.take());
9805
9806 // Bind a temporary if necessary.
9807 return S.MaybeBindToTemporary(call);
9808}
9809
9810ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009811 // Verify that this is a legal result type of a call.
9812 if (DestType->isArrayType() || DestType->isFunctionType()) {
9813 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9814 << DestType->isFunctionType() << DestType;
9815 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009816 }
9817
John McCall48218c62011-07-13 17:56:40 +00009818 // Rewrite the method result type if available.
9819 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9820 assert(method->getResultType() == S.Context.UnknownAnyTy);
9821 method->setResultType(DestType);
9822 }
John McCall755d8492011-04-12 00:42:48 +00009823
John McCall379b5152011-04-11 07:02:50 +00009824 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009825 msg->setType(DestType.getNonReferenceType());
9826 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009827
John McCall755d8492011-04-12 00:42:48 +00009828 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009829}
9830
9831ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009832 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009833 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009834 assert(ice->getValueKind() == VK_RValue);
9835 assert(ice->getObjectKind() == OK_Ordinary);
9836
John McCall755d8492011-04-12 00:42:48 +00009837 ice->setType(DestType);
9838
John McCall379b5152011-04-11 07:02:50 +00009839 // Rebuild the sub-expression as the pointee (function) type.
9840 DestType = DestType->castAs<PointerType>()->getPointeeType();
9841
9842 ExprResult result = Visit(ice->getSubExpr());
9843 if (!result.isUsable()) return ExprError();
9844
9845 ice->setSubExpr(result.take());
9846 return S.Owned(ice);
9847}
9848
John McCall755d8492011-04-12 00:42:48 +00009849ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009850 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009851 QualType type = DestType;
9852
9853 // We know how to make this work for certain kinds of decls:
9854
9855 // - functions
John McCall755d8492011-04-12 00:42:48 +00009856 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCalla19950e2011-08-10 04:12:23 +00009857 if (const PointerType *ptr = type->getAs<PointerType>()) {
9858 DestType = ptr->getPointeeType();
9859 ExprResult result = resolveDecl(expr, decl);
9860 if (result.isInvalid()) return ExprError();
9861 return S.ImpCastExprToType(result.take(), type,
9862 CK_FunctionToPointerDecay, VK_RValue);
9863 }
9864
9865 if (!type->isFunctionType()) {
9866 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9867 << decl << expr->getSourceRange();
9868 return ExprError();
9869 }
John McCall379b5152011-04-11 07:02:50 +00009870
John McCallf5307512011-04-27 00:36:17 +00009871 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9872 if (method->isInstance()) {
9873 valueKind = VK_RValue;
9874 type = S.Context.BoundMemberTy;
9875 }
9876
John McCall379b5152011-04-11 07:02:50 +00009877 // Function references aren't l-values in C.
9878 if (!S.getLangOptions().CPlusPlus)
9879 valueKind = VK_RValue;
9880
9881 // - variables
9882 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009883 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9884 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009885 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009886 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9887 << decl << expr->getSourceRange();
9888 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009889 }
9890
9891 // - nothing else
9892 } else {
9893 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9894 << decl << expr->getSourceRange();
9895 return ExprError();
9896 }
9897
John McCall755d8492011-04-12 00:42:48 +00009898 decl->setType(DestType);
9899 expr->setType(type);
9900 expr->setValueKind(valueKind);
9901 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009902}
9903
John McCall1de4d4e2011-04-07 08:22:57 +00009904/// Check a cast of an unknown-any type. We intentionally only
9905/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009906ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9907 Expr *castExpr, CastKind &castKind,
9908 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009909 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009910 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9911 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009912
John McCalla5fc4722011-04-09 22:50:59 +00009913 castExpr = result.take();
9914 VK = castExpr->getValueKind();
9915 castKind = CK_NoOp;
9916
9917 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009918}
9919
9920static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9921 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009922 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009923 while (true) {
9924 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009925 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009926 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009927 diagID = diag::err_uncasted_call_of_unknown_any;
9928 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009929 break;
John McCall379b5152011-04-11 07:02:50 +00009930 }
John McCall1de4d4e2011-04-07 08:22:57 +00009931 }
9932
John McCall379b5152011-04-11 07:02:50 +00009933 SourceLocation loc;
9934 NamedDecl *d;
9935 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9936 loc = ref->getLocation();
9937 d = ref->getDecl();
9938 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9939 loc = mem->getMemberLoc();
9940 d = mem->getMemberDecl();
9941 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9942 diagID = diag::err_uncasted_call_of_unknown_any;
9943 loc = msg->getSelectorLoc();
9944 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +00009945 if (!d) {
9946 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
9947 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
9948 << orig->getSourceRange();
9949 return ExprError();
9950 }
John McCall379b5152011-04-11 07:02:50 +00009951 } else {
9952 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9953 << e->getSourceRange();
9954 return ExprError();
9955 }
9956
9957 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +00009958
9959 // Never recoverable.
9960 return ExprError();
9961}
9962
John McCall2a984ca2010-10-12 00:20:44 +00009963/// Check for operands with placeholder types and complain if found.
9964/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +00009965ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +00009966 // Placeholder types are always *exactly* the appropriate builtin type.
9967 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +00009968
John McCall1de4d4e2011-04-07 08:22:57 +00009969 // Overloaded expressions.
9970 if (type == Context.OverloadTy)
9971 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +00009972 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +00009973 QualType(),
9974 diag::err_ovl_unresolvable);
9975
John McCall864c0412011-04-26 20:42:42 +00009976 // Bound member functions.
9977 if (type == Context.BoundMemberTy) {
9978 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9979 << E->getSourceRange();
9980 return ExprError();
9981 }
9982
John McCall1de4d4e2011-04-07 08:22:57 +00009983 // Expressions of unknown type.
9984 if (type == Context.UnknownAnyTy)
9985 return diagnoseUnknownAnyExpr(*this, E);
9986
9987 assert(!type->isPlaceholderType());
9988 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009989}
Richard Trieubb9b80c2011-04-21 21:44:26 +00009990
9991bool Sema::CheckCaseExpression(Expr *expr) {
9992 if (expr->isTypeDependent())
9993 return true;
9994 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9995 return expr->getType()->isIntegralOrEnumerationType();
9996 return false;
9997}