blob: 65c9cccaf11b515375a39a7a18ecfa5315d799dd [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 McCall5f8d6042011-08-27 01:09:30 +0000446 // C++ includes lvalue-to-rvalue conversion as a default argument
447 // promotion. If we have a gl-value, initialize a temporary.
448 if (getLangOptions().CPlusPlus && E->isGLValue()) {
449 ExprResult Temp = PerformCopyInitialization(
450 InitializedEntity::InitializeTemporary(E->getType()),
451 E->getExprLoc(),
452 Owned(E));
453 if (Temp.isInvalid())
454 return ExprError();
455 E = Temp.get();
456 }
457
John Wiegley429bb272011-04-08 18:41:53 +0000458 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000459}
460
Chris Lattner312531a2009-04-12 08:11:20 +0000461/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
462/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000463/// interfaces passed by value.
464ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000465 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000466 ExprResult ExprRes = CheckPlaceholderExpr(E);
467 if (ExprRes.isInvalid())
468 return ExprError();
469
470 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (ExprRes.isInvalid())
472 return ExprError();
473 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000475 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000476 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000477 DiagRuntimeBehavior(E->getLocStart(), 0,
478 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
479 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000480 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000481
John McCallf85e1932011-06-15 23:02:42 +0000482 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000483 // C++0x [expr.call]p7:
484 // Passing a potentially-evaluated argument of class type (Clause 9)
485 // having a non-trivial copy constructor, a non-trivial move constructor,
486 // or a non-trivial destructor, with no corresponding parameter,
487 // is conditionally-supported with implementation-defined semantics.
488 bool TrivialEnough = false;
489 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
490 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
491 if (Record->hasTrivialCopyConstructor() &&
492 Record->hasTrivialMoveConstructor() &&
493 Record->hasTrivialDestructor())
494 TrivialEnough = true;
495 }
496 }
John McCallf85e1932011-06-15 23:02:42 +0000497
498 if (!TrivialEnough &&
499 getLangOptions().ObjCAutoRefCount &&
500 E->getType()->isObjCLifetimeType())
501 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000502
503 if (TrivialEnough) {
504 // Nothing to diagnose. This is okay.
505 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000506 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000507 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000508 << CT)) {
509 // Turn this into a trap.
510 CXXScopeSpec SS;
511 UnqualifiedId Name;
512 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
513 E->getLocStart());
514 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
515 if (TrapFn.isInvalid())
516 return ExprError();
517
518 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
519 MultiExprArg(), E->getLocEnd());
520 if (Call.isInvalid())
521 return ExprError();
522
523 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
524 Call.get(), E);
525 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000526 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000527 E = Comma.get();
528 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000529 }
530
John Wiegley429bb272011-04-08 18:41:53 +0000531 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000532}
533
Chris Lattnere7a2e912008-07-25 21:10:04 +0000534/// UsualArithmeticConversions - Performs various conversions that are common to
535/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000536/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000537/// responsible for emitting appropriate error diagnostics.
538/// FIXME: verify the conversion rules for "complex int" are consistent with
539/// GCC.
Richard Trieu67e29332011-08-02 04:35:43 +0000540QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
541 ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000542 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000543 if (!isCompAssign) {
544 lhsExpr = UsualUnaryConversions(lhsExpr.take());
545 if (lhsExpr.isInvalid())
546 return QualType();
547 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000548
John Wiegley429bb272011-04-08 18:41:53 +0000549 rhsExpr = UsualUnaryConversions(rhsExpr.take());
550 if (rhsExpr.isInvalid())
551 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000552
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000554 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000555 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000556 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000557 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000558 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000559
560 // If both types are identical, no conversion is needed.
561 if (lhs == rhs)
562 return lhs;
563
564 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
565 // The caller can deal with this (e.g. pointer + int).
566 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
567 return lhs;
568
John McCallcf33b242010-11-13 08:17:45 +0000569 // Apply unary and bitfield promotions to the LHS's type.
570 QualType lhs_unpromoted = lhs;
571 if (lhs->isPromotableIntegerType())
572 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000573 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000574 if (!LHSBitfieldPromoteTy.isNull())
575 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000576 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000577 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000578
John McCallcf33b242010-11-13 08:17:45 +0000579 // If both types are identical, no conversion is needed.
580 if (lhs == rhs)
581 return lhs;
582
583 // At this point, we have two different arithmetic types.
584
585 // Handle complex types first (C99 6.3.1.8p1).
586 bool LHSComplexFloat = lhs->isComplexType();
587 bool RHSComplexFloat = rhs->isComplexType();
588 if (LHSComplexFloat || RHSComplexFloat) {
589 // if we have an integer operand, the result is the complex type.
590
John McCall2bb5d002010-11-13 09:02:35 +0000591 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
592 if (rhs->isIntegerType()) {
593 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000594 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieu67e29332011-08-02 04:35:43 +0000595 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
596 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000597 } else {
598 assert(rhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000599 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
600 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000601 }
John McCallcf33b242010-11-13 08:17:45 +0000602 return lhs;
603 }
604
John McCall2bb5d002010-11-13 09:02:35 +0000605 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
606 if (!isCompAssign) {
607 // int -> float -> _Complex float
608 if (lhs->isIntegerType()) {
609 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieu67e29332011-08-02 04:35:43 +0000610 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
611 CK_IntegralToFloating);
612 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
613 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000614 } else {
615 assert(lhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000616 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
617 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000618 }
619 }
John McCallcf33b242010-11-13 08:17:45 +0000620 return rhs;
621 }
622
623 // This handles complex/complex, complex/float, or float/complex.
624 // When both operands are complex, the shorter operand is converted to the
625 // type of the longer, and that is the type of the result. This corresponds
626 // to what is done when combining two real floating-point operands.
627 // The fun begins when size promotion occur across type domains.
628 // From H&S 6.3.4: When one operand is complex and the other is a real
629 // floating-point type, the less precise type is converted, within it's
630 // real or complex domain, to the precision of the other type. For example,
631 // when combining a "long double" with a "double _Complex", the
632 // "double _Complex" is promoted to "long double _Complex".
633 int order = Context.getFloatingTypeOrder(lhs, rhs);
634
635 // If both are complex, just cast to the more precise type.
636 if (LHSComplexFloat && RHSComplexFloat) {
637 if (order > 0) {
638 // _Complex float -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000639 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
640 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000641 return lhs;
642
643 } else if (order < 0) {
644 // _Complex float -> _Complex double
645 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000646 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
647 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000648 return rhs;
649 }
650 return lhs;
651 }
652
653 // If just the LHS is complex, the RHS needs to be converted,
654 // and the LHS might need to be promoted.
655 if (LHSComplexFloat) {
656 if (order > 0) { // LHS is wider
657 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000658 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000659 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000660 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
661 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000662 return lhs;
663 }
664
665 // RHS is at least as wide. Find its corresponding complex type.
666 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
667
668 // double -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000669 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
670 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000671
672 // _Complex float -> _Complex double
673 if (!isCompAssign && order < 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000674 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
675 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000676
677 return result;
678 }
679
680 // Just the RHS is complex, so the LHS needs to be converted
681 // and the RHS might need to be promoted.
682 assert(RHSComplexFloat);
683
684 if (order < 0) { // RHS is wider
685 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000686 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000687 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000688 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000689 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
690 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000691 }
John McCallcf33b242010-11-13 08:17:45 +0000692 return rhs;
693 }
694
695 // LHS is at least as wide. Find its corresponding complex type.
696 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
697
698 // double -> _Complex double
699 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000700 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
701 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000702
703 // _Complex float -> _Complex double
704 if (order > 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000705 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
706 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000707
708 return result;
709 }
710
711 // Now handle "real" floating types (i.e. float, double, long double).
712 bool LHSFloat = lhs->isRealFloatingType();
713 bool RHSFloat = rhs->isRealFloatingType();
714 if (LHSFloat || RHSFloat) {
715 // If we have two real floating types, convert the smaller operand
716 // to the bigger result.
717 if (LHSFloat && RHSFloat) {
718 int order = Context.getFloatingTypeOrder(lhs, rhs);
719 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000720 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000721 return lhs;
722 }
723
724 assert(order < 0 && "illegal float comparison");
725 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000726 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000727 return rhs;
728 }
729
730 // If we have an integer operand, the result is the real floating type.
731 if (LHSFloat) {
732 if (rhs->isIntegerType()) {
733 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000734 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000735 return lhs;
736 }
737
738 // Convert both sides to the appropriate complex float.
739 assert(rhs->isComplexIntegerType());
740 QualType result = Context.getComplexType(lhs);
741
742 // _Complex int -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000743 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
744 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000745
746 // float -> _Complex float
747 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000748 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
749 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000750
751 return result;
752 }
753
754 assert(RHSFloat);
755 if (lhs->isIntegerType()) {
756 // Convert lhs to the rhs floating point type.
757 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000758 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000759 return rhs;
760 }
761
762 // Convert both sides to the appropriate complex float.
763 assert(lhs->isComplexIntegerType());
764 QualType result = Context.getComplexType(rhs);
765
766 // _Complex int -> _Complex float
767 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000768 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
769 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000770
771 // float -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000772 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
773 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000774
775 return result;
776 }
777
778 // Handle GCC complex int extension.
779 // FIXME: if the operands are (int, _Complex long), we currently
780 // don't promote the complex. Also, signedness?
781 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
782 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
783 if (lhsComplexInt && rhsComplexInt) {
784 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
785 rhsComplexInt->getElementType());
786 assert(order && "inequal types with equal element ordering");
787 if (order > 0) {
788 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000789 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000790 return lhs;
791 }
792
793 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000795 return rhs;
796 } else if (lhsComplexInt) {
797 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000798 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000799 return lhs;
800 } else if (rhsComplexInt) {
801 // int -> _Complex int
802 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000803 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
804 CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000805 return rhs;
806 }
807
808 // Finally, we have two differing integer types.
809 // The rules for this case are in C99 6.3.1.8
810 int compare = Context.getIntegerTypeOrder(lhs, rhs);
811 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
812 rhsSigned = rhs->hasSignedIntegerRepresentation();
813 if (lhsSigned == rhsSigned) {
814 // Same signedness; use the higher-ranked type
815 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000816 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000817 return lhs;
818 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000819 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000820 return rhs;
821 } else if (compare != (lhsSigned ? 1 : -1)) {
822 // The unsigned type has greater than or equal rank to the
823 // signed type, so use the unsigned type
824 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000825 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000826 return lhs;
827 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000828 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000829 return rhs;
830 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
831 // The two types are different widths; if we are here, that
832 // means the signed type is larger than the unsigned type, so
833 // use the signed type.
834 if (lhsSigned) {
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 {
841 // The signed type is higher-ranked than the unsigned type,
842 // but isn't actually any bigger (like unsigned int and long
843 // on most 32-bit systems). Use the unsigned type corresponding
844 // to the signed type.
845 QualType result =
846 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000847 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000848 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000849 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000850 return result;
851 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000852}
853
Chris Lattnere7a2e912008-07-25 21:10:04 +0000854//===----------------------------------------------------------------------===//
855// Semantic Analysis for various Expression Types
856//===----------------------------------------------------------------------===//
857
858
Peter Collingbournef111d932011-04-15 00:35:48 +0000859ExprResult
860Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
861 SourceLocation DefaultLoc,
862 SourceLocation RParenLoc,
863 Expr *ControllingExpr,
864 MultiTypeArg types,
865 MultiExprArg exprs) {
866 unsigned NumAssocs = types.size();
867 assert(NumAssocs == exprs.size());
868
869 ParsedType *ParsedTypes = types.release();
870 Expr **Exprs = exprs.release();
871
872 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
873 for (unsigned i = 0; i < NumAssocs; ++i) {
874 if (ParsedTypes[i])
875 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
876 else
877 Types[i] = 0;
878 }
879
880 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
881 ControllingExpr, Types, Exprs,
882 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000883 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000884 return ER;
885}
886
887ExprResult
888Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
889 SourceLocation DefaultLoc,
890 SourceLocation RParenLoc,
891 Expr *ControllingExpr,
892 TypeSourceInfo **Types,
893 Expr **Exprs,
894 unsigned NumAssocs) {
895 bool TypeErrorFound = false,
896 IsResultDependent = ControllingExpr->isTypeDependent(),
897 ContainsUnexpandedParameterPack
898 = ControllingExpr->containsUnexpandedParameterPack();
899
900 for (unsigned i = 0; i < NumAssocs; ++i) {
901 if (Exprs[i]->containsUnexpandedParameterPack())
902 ContainsUnexpandedParameterPack = true;
903
904 if (Types[i]) {
905 if (Types[i]->getType()->containsUnexpandedParameterPack())
906 ContainsUnexpandedParameterPack = true;
907
908 if (Types[i]->getType()->isDependentType()) {
909 IsResultDependent = true;
910 } else {
911 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
912 // complete object type other than a variably modified type."
913 unsigned D = 0;
914 if (Types[i]->getType()->isIncompleteType())
915 D = diag::err_assoc_type_incomplete;
916 else if (!Types[i]->getType()->isObjectType())
917 D = diag::err_assoc_type_nonobject;
918 else if (Types[i]->getType()->isVariablyModifiedType())
919 D = diag::err_assoc_type_variably_modified;
920
921 if (D != 0) {
922 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
923 << Types[i]->getTypeLoc().getSourceRange()
924 << Types[i]->getType();
925 TypeErrorFound = true;
926 }
927
928 // C1X 6.5.1.1p2 "No two generic associations in the same generic
929 // selection shall specify compatible types."
930 for (unsigned j = i+1; j < NumAssocs; ++j)
931 if (Types[j] && !Types[j]->getType()->isDependentType() &&
932 Context.typesAreCompatible(Types[i]->getType(),
933 Types[j]->getType())) {
934 Diag(Types[j]->getTypeLoc().getBeginLoc(),
935 diag::err_assoc_compatible_types)
936 << Types[j]->getTypeLoc().getSourceRange()
937 << Types[j]->getType()
938 << Types[i]->getType();
939 Diag(Types[i]->getTypeLoc().getBeginLoc(),
940 diag::note_compat_assoc)
941 << Types[i]->getTypeLoc().getSourceRange()
942 << Types[i]->getType();
943 TypeErrorFound = true;
944 }
945 }
946 }
947 }
948 if (TypeErrorFound)
949 return ExprError();
950
951 // If we determined that the generic selection is result-dependent, don't
952 // try to compute the result expression.
953 if (IsResultDependent)
954 return Owned(new (Context) GenericSelectionExpr(
955 Context, KeyLoc, ControllingExpr,
956 Types, Exprs, NumAssocs, DefaultLoc,
957 RParenLoc, ContainsUnexpandedParameterPack));
958
Chris Lattner5f9e2722011-07-23 10:55:15 +0000959 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +0000960 unsigned DefaultIndex = -1U;
961 for (unsigned i = 0; i < NumAssocs; ++i) {
962 if (!Types[i])
963 DefaultIndex = i;
964 else if (Context.typesAreCompatible(ControllingExpr->getType(),
965 Types[i]->getType()))
966 CompatIndices.push_back(i);
967 }
968
969 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
970 // type compatible with at most one of the types named in its generic
971 // association list."
972 if (CompatIndices.size() > 1) {
973 // We strip parens here because the controlling expression is typically
974 // parenthesized in macro definitions.
975 ControllingExpr = ControllingExpr->IgnoreParens();
976 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
977 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
978 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000979 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +0000980 E = CompatIndices.end(); I != E; ++I) {
981 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
982 diag::note_compat_assoc)
983 << Types[*I]->getTypeLoc().getSourceRange()
984 << Types[*I]->getType();
985 }
986 return ExprError();
987 }
988
989 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
990 // its controlling expression shall have type compatible with exactly one of
991 // the types named in its generic association list."
992 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
993 // We strip parens here because the controlling expression is typically
994 // parenthesized in macro definitions.
995 ControllingExpr = ControllingExpr->IgnoreParens();
996 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
997 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
998 return ExprError();
999 }
1000
1001 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1002 // type name that is compatible with the type of the controlling expression,
1003 // then the result expression of the generic selection is the expression
1004 // in that generic association. Otherwise, the result expression of the
1005 // generic selection is the expression in the default generic association."
1006 unsigned ResultIndex =
1007 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1008
1009 return Owned(new (Context) GenericSelectionExpr(
1010 Context, KeyLoc, ControllingExpr,
1011 Types, Exprs, NumAssocs, DefaultLoc,
1012 RParenLoc, ContainsUnexpandedParameterPack,
1013 ResultIndex));
1014}
1015
Steve Narofff69936d2007-09-16 03:34:24 +00001016/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001017/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1018/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1019/// multiple tokens. However, the common case is that StringToks points to one
1020/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001021///
John McCall60d7b3a2010-08-24 06:29:42 +00001022ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001023Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 assert(NumStringToks && "Must have at least one string!");
1025
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001026 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001028 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001029
Chris Lattner5f9e2722011-07-23 10:55:15 +00001030 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 for (unsigned i = 0; i != NumStringToks; ++i)
1032 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001033
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001034 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001035 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001036 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001037 else if (Literal.isUTF16())
1038 StrTy = Context.Char16Ty;
1039 else if (Literal.isUTF32())
1040 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001041 else if (Literal.Pascal)
1042 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001043
Douglas Gregor5cee1192011-07-27 05:40:30 +00001044 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1045 if (Literal.isWide())
1046 Kind = StringLiteral::Wide;
1047 else if (Literal.isUTF8())
1048 Kind = StringLiteral::UTF8;
1049 else if (Literal.isUTF16())
1050 Kind = StringLiteral::UTF16;
1051 else if (Literal.isUTF32())
1052 Kind = StringLiteral::UTF32;
1053
Douglas Gregor77a52232008-09-12 00:47:35 +00001054 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001055 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001056 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001057
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001058 // Get an array type for the string, according to C99 6.4.5. This includes
1059 // the nul terminator character as well as the string length for pascal
1060 // strings.
1061 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001062 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001063 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001066 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001067 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001068 &StringTokLocs[0],
1069 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001070}
1071
John McCall469a1eb2011-02-02 13:00:07 +00001072enum CaptureResult {
1073 /// No capture is required.
1074 CR_NoCapture,
1075
1076 /// A capture is required.
1077 CR_Capture,
1078
John McCall6b5a61b2011-02-07 10:33:21 +00001079 /// A by-ref capture is required.
1080 CR_CaptureByRef,
1081
John McCall469a1eb2011-02-02 13:00:07 +00001082 /// An error occurred when trying to capture the given variable.
1083 CR_Error
1084};
1085
1086/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001087///
John McCall469a1eb2011-02-02 13:00:07 +00001088/// \param var - the variable referenced
1089/// \param DC - the context which we couldn't capture through
1090static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001091diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001092 VarDecl *var, DeclContext *DC) {
1093 switch (S.ExprEvalContexts.back().Context) {
1094 case Sema::Unevaluated:
1095 // The argument will never be evaluated, so don't complain.
1096 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
John McCall469a1eb2011-02-02 13:00:07 +00001098 case Sema::PotentiallyEvaluated:
1099 case Sema::PotentiallyEvaluatedIfUsed:
1100 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001101
John McCall469a1eb2011-02-02 13:00:07 +00001102 case Sema::PotentiallyPotentiallyEvaluated:
1103 // FIXME: delay these!
1104 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
John McCall469a1eb2011-02-02 13:00:07 +00001107 // Don't diagnose about capture if we're not actually in code right
1108 // now; in general, there are more appropriate places that will
1109 // diagnose this.
1110 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1111
John McCall4f38f412011-03-22 23:15:50 +00001112 // Certain madnesses can happen with parameter declarations, which
1113 // we want to ignore.
1114 if (isa<ParmVarDecl>(var)) {
1115 // - If the parameter still belongs to the translation unit, then
1116 // we're actually just using one parameter in the declaration of
1117 // the next. This is useful in e.g. VLAs.
1118 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1119 return CR_NoCapture;
1120
1121 // - This particular madness can happen in ill-formed default
1122 // arguments; claim it's okay and let downstream code handle it.
1123 if (S.CurContext == var->getDeclContext()->getParent())
1124 return CR_NoCapture;
1125 }
John McCall469a1eb2011-02-02 13:00:07 +00001126
1127 DeclarationName functionName;
1128 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1129 functionName = fn->getDeclName();
1130 // FIXME: variable from enclosing block that we couldn't capture from!
1131
1132 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1133 << var->getIdentifier() << functionName;
1134 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1135 << var->getIdentifier();
1136
1137 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001138}
1139
John McCall6b5a61b2011-02-07 10:33:21 +00001140/// There is a well-formed capture at a particular scope level;
1141/// propagate it through all the nested blocks.
1142static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1143 const BlockDecl::Capture &capture) {
1144 VarDecl *var = capture.getVariable();
1145
1146 // Update all the inner blocks with the capture information.
1147 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1148 i != e; ++i) {
1149 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1150 innerBlock->Captures.push_back(
1151 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1152 /*nested*/ true, capture.getCopyExpr()));
1153 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1154 }
1155
1156 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1157}
1158
1159/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001160/// given value in the current context requires a variable capture.
1161///
1162/// This also keeps the captures set in the BlockScopeInfo records
1163/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001164static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001165 ValueDecl *value) {
1166 // Only variables ever require capture.
1167 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001168 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001169
1170 // Fast path: variables from the current context never require capture.
1171 DeclContext *DC = S.CurContext;
1172 if (var->getDeclContext() == DC) return CR_NoCapture;
1173
1174 // Only variables with local storage require capture.
1175 // FIXME: What about 'const' variables in C++?
1176 if (!var->hasLocalStorage()) return CR_NoCapture;
1177
1178 // Otherwise, we need to capture.
1179
1180 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001181 do {
1182 // Only blocks (and eventually C++0x closures) can capture; other
1183 // scopes don't work.
1184 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001185 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001186
1187 BlockScopeInfo *blockScope =
1188 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1189 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1190
John McCall6b5a61b2011-02-07 10:33:21 +00001191 // Check whether we've already captured it in this block. If so,
1192 // we're done.
1193 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1194 return propagateCapture(S, functionScopesIndex,
1195 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001196
1197 functionScopesIndex--;
1198 DC = cast<BlockDecl>(DC)->getDeclContext();
1199 } while (var->getDeclContext() != DC);
1200
John McCall6b5a61b2011-02-07 10:33:21 +00001201 // Okay, we descended all the way to the block that defines the variable.
1202 // Actually try to capture it.
1203 QualType type = var->getType();
1204
1205 // Prohibit variably-modified types.
1206 if (type->isVariablyModifiedType()) {
1207 S.Diag(loc, diag::err_ref_vm_type);
1208 S.Diag(var->getLocation(), diag::note_declared_at);
1209 return CR_Error;
1210 }
1211
1212 // Prohibit arrays, even in __block variables, but not references to
1213 // them.
1214 if (type->isArrayType()) {
1215 S.Diag(loc, diag::err_ref_array_type);
1216 S.Diag(var->getLocation(), diag::note_declared_at);
1217 return CR_Error;
1218 }
1219
1220 S.MarkDeclarationReferenced(loc, var);
1221
1222 // The BlocksAttr indicates the variable is bound by-reference.
1223 bool byRef = var->hasAttr<BlocksAttr>();
1224
1225 // Build a copy expression.
1226 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001227 const RecordType *rtype;
1228 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1229 (rtype = type->getAs<RecordType>())) {
1230
1231 // The capture logic needs the destructor, so make sure we mark it.
1232 // Usually this is unnecessary because most local variables have
1233 // their destructors marked at declaration time, but parameters are
1234 // an exception because it's technically only the call site that
1235 // actually requires the destructor.
1236 if (isa<ParmVarDecl>(var))
1237 S.FinalizeVarWithDestructor(var, rtype);
1238
John McCall6b5a61b2011-02-07 10:33:21 +00001239 // According to the blocks spec, the capture of a variable from
1240 // the stack requires a const copy constructor. This is not true
1241 // of the copy/move done to move a __block variable to the heap.
1242 type.addConst();
1243
1244 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1245 ExprResult result =
1246 S.PerformCopyInitialization(
1247 InitializedEntity::InitializeBlock(var->getLocation(),
1248 type, false),
1249 loc, S.Owned(declRef));
1250
1251 // Build a full-expression copy expression if initialization
1252 // succeeded and used a non-trivial constructor. Recover from
1253 // errors by pretending that the copy isn't necessary.
1254 if (!result.isInvalid() &&
1255 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1256 result = S.MaybeCreateExprWithCleanups(result);
1257 copyExpr = result.take();
1258 }
1259 }
1260
1261 // We're currently at the declarer; go back to the closure.
1262 functionScopesIndex++;
1263 BlockScopeInfo *blockScope =
1264 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1265
1266 // Build a valid capture in this scope.
1267 blockScope->Captures.push_back(
1268 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1269 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1270
1271 // Propagate that to inner captures if necessary.
1272 return propagateCapture(S, functionScopesIndex,
1273 blockScope->Captures.back());
1274}
1275
1276static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1277 const DeclarationNameInfo &NameInfo,
1278 bool byRef) {
1279 assert(isa<VarDecl>(vd) && "capturing non-variable");
1280
1281 VarDecl *var = cast<VarDecl>(vd);
1282 assert(var->hasLocalStorage() && "capturing non-local");
1283 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1284
1285 QualType exprType = var->getType().getNonReferenceType();
1286
1287 BlockDeclRefExpr *BDRE;
1288 if (!byRef) {
1289 // The variable will be bound by copy; make it const within the
1290 // closure, but record that this was done in the expression.
1291 bool constAdded = !exprType.isConstQualified();
1292 exprType.addConst();
1293
1294 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1295 NameInfo.getLoc(), false,
1296 constAdded);
1297 } else {
1298 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1299 NameInfo.getLoc(), true);
1300 }
1301
1302 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001303}
Chris Lattner639e2d32008-10-20 05:16:36 +00001304
John McCall60d7b3a2010-08-24 06:29:42 +00001305ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001306Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001307 SourceLocation Loc,
1308 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001309 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001310 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001311}
1312
John McCall76a40212011-02-09 01:13:10 +00001313/// BuildDeclRefExpr - Build an expression that references a
1314/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001315ExprResult
John McCall76a40212011-02-09 01:13:10 +00001316Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001317 const DeclarationNameInfo &NameInfo,
1318 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001319 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
John McCall7eb0a9e2010-11-24 05:12:34 +00001321 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001322 SS? SS->getWithLocInContext(Context)
1323 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001324 D, NameInfo, Ty, VK);
1325
1326 // Just in case we're building an illegal pointer-to-member.
1327 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1328 E->setObjectKind(OK_BitField);
1329
1330 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001331}
1332
Abramo Bagnara25777432010-08-11 22:01:17 +00001333/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001334/// possibly a list of template arguments.
1335///
1336/// If this produces template arguments, it is permitted to call
1337/// DecomposeTemplateName.
1338///
1339/// This actually loses a lot of source location information for
1340/// non-standard name kinds; we should consider preserving that in
1341/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001342void
1343Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1344 TemplateArgumentListInfo &Buffer,
1345 DeclarationNameInfo &NameInfo,
1346 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001347 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1348 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1349 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1350
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001351 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001352 Id.TemplateId->getTemplateArgs(),
1353 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001354 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001355 TemplateArgsPtr.release();
1356
John McCall2b5289b2010-08-23 07:28:44 +00001357 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001358 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001359 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001360 TemplateArgs = &Buffer;
1361 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001362 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001363 TemplateArgs = 0;
1364 }
1365}
1366
John McCall578b69b2009-12-16 08:11:27 +00001367/// Diagnose an empty lookup.
1368///
1369/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001370bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001371 CorrectTypoContext CTC,
1372 TemplateArgumentListInfo *ExplicitTemplateArgs,
1373 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001374 DeclarationName Name = R.getLookupName();
1375
John McCall578b69b2009-12-16 08:11:27 +00001376 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001377 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001378 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1379 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001380 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001381 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001382 diagnostic_suggest = diag::err_undeclared_use_suggest;
1383 }
John McCall578b69b2009-12-16 08:11:27 +00001384
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001385 // If the original lookup was an unqualified lookup, fake an
1386 // unqualified lookup. This is useful when (for example) the
1387 // original lookup would not have found something because it was a
1388 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001389 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001390 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001391 if (isa<CXXRecordDecl>(DC)) {
1392 LookupQualifiedName(R, DC);
1393
1394 if (!R.empty()) {
1395 // Don't give errors about ambiguities in this lookup.
1396 R.suppressDiagnostics();
1397
1398 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1399 bool isInstance = CurMethod &&
1400 CurMethod->isInstance() &&
1401 DC == CurMethod->getParent();
1402
1403 // Give a code modification hint to insert 'this->'.
1404 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1405 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001406 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001407 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1408 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001409 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001410 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001411 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001412 Diag(R.getNameLoc(), diagnostic) << Name
1413 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1414 QualType DepThisType = DepMethod->getThisType(Context);
1415 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1416 R.getNameLoc(), DepThisType, false);
1417 TemplateArgumentListInfo TList;
1418 if (ULE->hasExplicitTemplateArgs())
1419 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001420
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001421 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001422 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001423 CXXDependentScopeMemberExpr *DepExpr =
1424 CXXDependentScopeMemberExpr::Create(
1425 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001426 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001427 R.getLookupNameInfo(), &TList);
1428 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001429 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001430 // FIXME: we should be able to handle this case too. It is correct
1431 // to add this-> here. This is a workaround for PR7947.
1432 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001433 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001434 } else {
John McCall578b69b2009-12-16 08:11:27 +00001435 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001436 }
John McCall578b69b2009-12-16 08:11:27 +00001437
1438 // Do we really want to note all of these?
1439 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1440 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1441
1442 // Tell the callee to try to recover.
1443 return false;
1444 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001445
1446 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001447 }
1448 }
1449
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001450 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001451 TypoCorrection Corrected;
1452 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1453 S, &SS, NULL, false, CTC))) {
1454 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1455 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1456 R.setLookupName(Corrected.getCorrection());
1457
Hans Wennborg701d1e72011-07-12 08:45:31 +00001458 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001459 if (Corrected.isOverloaded()) {
1460 OverloadCandidateSet OCS(R.getNameLoc());
1461 OverloadCandidateSet::iterator Best;
1462 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1463 CDEnd = Corrected.end();
1464 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001465 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001466 dyn_cast<FunctionTemplateDecl>(*CD))
1467 AddTemplateOverloadCandidate(
1468 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1469 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001470 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1471 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1472 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1473 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001474 }
1475 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1476 case OR_Success:
1477 ND = Best->Function;
1478 break;
1479 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001480 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001481 }
1482 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001483 R.addDecl(ND);
1484 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001485 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001486 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1487 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001488 else
1489 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001490 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001491 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001492 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1493 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001494 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001495 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001496
1497 // Tell the callee to try to recover.
1498 return false;
1499 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001500
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001501 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001502 // FIXME: If we ended up with a typo for a type name or
1503 // Objective-C class name, we're in trouble because the parser
1504 // is in the wrong place to recover. Suggest the typo
1505 // correction, but don't make it a fix-it since we're not going
1506 // to recover well anyway.
1507 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001508 Diag(R.getNameLoc(), diagnostic_suggest)
1509 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001510 else
1511 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001512 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001513 << SS.getRange();
1514
1515 // Don't try to recover; it won't work.
1516 return true;
1517 }
1518 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001519 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001520 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001521 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001522 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001523 else
Douglas Gregord203a162010-01-01 00:15:04 +00001524 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001525 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001526 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001527 return true;
1528 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001529 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001530 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001531
1532 // Emit a special diagnostic for failed member lookups.
1533 // FIXME: computing the declaration context might fail here (?)
1534 if (!SS.isEmpty()) {
1535 Diag(R.getNameLoc(), diag::err_no_member)
1536 << Name << computeDeclContext(SS, false)
1537 << SS.getRange();
1538 return true;
1539 }
1540
John McCall578b69b2009-12-16 08:11:27 +00001541 // Give up, we can't recover.
1542 Diag(R.getNameLoc(), diagnostic) << Name;
1543 return true;
1544}
1545
Douglas Gregorca45da02010-11-02 20:36:02 +00001546ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1547 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001548 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1549 if (!IDecl)
1550 return 0;
1551 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1552 if (!ClassImpDecl)
1553 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001554 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001555 if (!property)
1556 return 0;
1557 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001558 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1559 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001560 return 0;
1561 return property;
1562}
1563
Douglas Gregorca45da02010-11-02 20:36:02 +00001564bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1565 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1566 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1567 if (!IDecl)
1568 return false;
1569 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1570 if (!ClassImpDecl)
1571 return false;
1572 if (ObjCPropertyImplDecl *PIDecl
1573 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1574 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1575 PIDecl->getPropertyIvarDecl())
1576 return false;
1577
1578 return true;
1579}
1580
Douglas Gregor312eadb2011-04-24 05:37:28 +00001581ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1582 IdentifierInfo *II,
1583 SourceLocation NameLoc) {
1584 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001585 bool LookForIvars;
1586 if (Lookup.empty())
1587 LookForIvars = true;
1588 else if (CurMeth->isClassMethod())
1589 LookForIvars = false;
1590 else
1591 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001592 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1593 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001594 if (!LookForIvars)
1595 return 0;
1596
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001597 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1598 if (!IDecl)
1599 return 0;
1600 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001601 if (!ClassImpDecl)
1602 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001603 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001604 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001605 if (!property)
1606 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001607 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001608 DynamicImplSeen =
1609 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001610 // property implementation has a designated ivar. No need to assume a new
1611 // one.
1612 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1613 return 0;
1614 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001615 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001616 QualType PropType = Context.getCanonicalType(property->getType());
1617 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001618 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001619 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001620 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001621 (Expr *)0, true);
1622 ClassImpDecl->addDecl(Ivar);
1623 IDecl->makeDeclVisibleInContext(Ivar, false);
1624 property->setPropertyIvarDecl(Ivar);
1625 return Ivar;
1626 }
1627 return 0;
1628}
1629
John McCall60d7b3a2010-08-24 06:29:42 +00001630ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001631 CXXScopeSpec &SS,
1632 UnqualifiedId &Id,
1633 bool HasTrailingLParen,
1634 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001635 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1636 "cannot be direct & operand and have a trailing lparen");
1637
1638 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001639 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001640
John McCall129e2df2009-11-30 22:42:35 +00001641 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001642
1643 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001644 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001645 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001646 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001647
Abramo Bagnara25777432010-08-11 22:01:17 +00001648 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001649 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001650 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001651
John McCallf7a1a742009-11-24 19:00:30 +00001652 // C++ [temp.dep.expr]p3:
1653 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001654 // -- an identifier that was declared with a dependent type,
1655 // (note: handled after lookup)
1656 // -- a template-id that is dependent,
1657 // (note: handled in BuildTemplateIdExpr)
1658 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001659 // -- a nested-name-specifier that contains a class-name that
1660 // names a dependent type.
1661 // Determine whether this is a member of an unknown specialization;
1662 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001663 bool DependentID = false;
1664 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1665 Name.getCXXNameType()->isDependentType()) {
1666 DependentID = true;
1667 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001668 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001669 if (RequireCompleteDeclContext(SS, DC))
1670 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001671 } else {
1672 DependentID = true;
1673 }
1674 }
1675
Chris Lattner337e5502011-02-18 01:27:55 +00001676 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001677 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001678 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001679
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001680 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001681 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001682 LookupResult R(*this, NameInfo,
1683 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1684 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001685 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001686 // Lookup the template name again to correctly establish the context in
1687 // which it was found. This is really unfortunate as we already did the
1688 // lookup to determine that it was a template name in the first place. If
1689 // this becomes a performance hit, we can work harder to preserve those
1690 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001691 bool MemberOfUnknownSpecialization;
1692 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1693 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001694
1695 if (MemberOfUnknownSpecialization ||
1696 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1697 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1698 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001699 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001700 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001701 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001703 // If the result might be in a dependent base class, this is a dependent
1704 // id-expression.
1705 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1706 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1707 TemplateArgs);
1708
John McCallf7a1a742009-11-24 19:00:30 +00001709 // If this reference is in an Objective-C method, then we need to do
1710 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001711 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001712 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001713 if (E.isInvalid())
1714 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Chris Lattner337e5502011-02-18 01:27:55 +00001716 if (Expr *Ex = E.takeAs<Expr>())
1717 return Owned(Ex);
1718
1719 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001720 if (getLangOptions().ObjCDefaultSynthProperties &&
1721 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001722 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001723 if (const ObjCPropertyDecl *Property =
1724 canSynthesizeProvisionalIvar(II)) {
1725 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1726 Diag(Property->getLocation(), diag::note_property_declare);
1727 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001728 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1729 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001730 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001731 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001732 // for further use, this must be set to false if in class method.
1733 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001734 }
Chris Lattner8a934232008-03-31 00:36:02 +00001735 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001736
John McCallf7a1a742009-11-24 19:00:30 +00001737 if (R.isAmbiguous())
1738 return ExprError();
1739
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001740 // Determine whether this name might be a candidate for
1741 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001742 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001743
John McCallf7a1a742009-11-24 19:00:30 +00001744 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001746 // in C90, extension in C99, forbidden in C++).
1747 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1748 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1749 if (D) R.addDecl(D);
1750 }
1751
1752 // If this name wasn't predeclared and if this is not a function
1753 // call, diagnose the problem.
1754 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001755 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001756 return ExprError();
1757
1758 assert(!R.empty() &&
1759 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001760
1761 // If we found an Objective-C instance variable, let
1762 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001763 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001764 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1765 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001766 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001767 assert(E.isInvalid() || E.get());
1768 return move(E);
1769 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 }
1771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
John McCallf7a1a742009-11-24 19:00:30 +00001773 // This is guaranteed from this point on.
1774 assert(!R.empty() || ADL);
1775
John McCallaa81e162009-12-01 22:10:20 +00001776 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001777 // C++ [class.mfct.non-static]p3:
1778 // When an id-expression that is not part of a class member access
1779 // syntax and not used to form a pointer to member is used in the
1780 // body of a non-static member function of class X, if name lookup
1781 // resolves the name in the id-expression to a non-static non-type
1782 // member of some class C, the id-expression is transformed into a
1783 // class member access expression using (*this) as the
1784 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001785 //
1786 // But we don't actually need to do this for '&' operands if R
1787 // resolved to a function or overloaded function set, because the
1788 // expression is ill-formed if it actually works out to be a
1789 // non-static member function:
1790 //
1791 // C++ [expr.ref]p4:
1792 // Otherwise, if E1.E2 refers to a non-static member function. . .
1793 // [t]he expression can be used only as the left-hand operand of a
1794 // member function call.
1795 //
1796 // There are other safeguards against such uses, but it's important
1797 // to get this right here so that we don't end up making a
1798 // spuriously dependent expression if we're inside a dependent
1799 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001800 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001801 bool MightBeImplicitMember;
1802 if (!isAddressOfOperand)
1803 MightBeImplicitMember = true;
1804 else if (!SS.isEmpty())
1805 MightBeImplicitMember = false;
1806 else if (R.isOverloadedResult())
1807 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001808 else if (R.isUnresolvableResult())
1809 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001810 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001811 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1812 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001813
1814 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001815 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001816 }
1817
John McCallf7a1a742009-11-24 19:00:30 +00001818 if (TemplateArgs)
1819 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001820
John McCallf7a1a742009-11-24 19:00:30 +00001821 return BuildDeclarationNameExpr(SS, R, ADL);
1822}
1823
John McCall129e2df2009-11-30 22:42:35 +00001824/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1825/// declaration name, generally during template instantiation.
1826/// There's a large number of things which don't need to be done along
1827/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001828ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001829Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001830 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001831 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001832 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001833 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001834
John McCall77bb1aa2010-05-01 00:40:08 +00001835 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001836 return ExprError();
1837
Abramo Bagnara25777432010-08-11 22:01:17 +00001838 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001839 LookupQualifiedName(R, DC);
1840
1841 if (R.isAmbiguous())
1842 return ExprError();
1843
1844 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001845 Diag(NameInfo.getLoc(), diag::err_no_member)
1846 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001847 return ExprError();
1848 }
1849
1850 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1851}
1852
1853/// LookupInObjCMethod - The parser has read a name in, and Sema has
1854/// detected that we're currently inside an ObjC method. Perform some
1855/// additional lookup.
1856///
1857/// Ideally, most of this would be done by lookup, but there's
1858/// actually quite a lot of extra work involved.
1859///
1860/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001861ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001862Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001863 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001864 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001865 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001866
John McCallf7a1a742009-11-24 19:00:30 +00001867 // There are two cases to handle here. 1) scoped lookup could have failed,
1868 // in which case we should look for an ivar. 2) scoped lookup could have
1869 // found a decl, but that decl is outside the current instance method (i.e.
1870 // a global variable). In these two cases, we do a lookup for an ivar with
1871 // this name, if the lookup sucedes, we replace it our current decl.
1872
1873 // If we're in a class method, we don't normally want to look for
1874 // ivars. But if we don't find anything else, and there's an
1875 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001876 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001877
1878 bool LookForIvars;
1879 if (Lookup.empty())
1880 LookForIvars = true;
1881 else if (IsClassMethod)
1882 LookForIvars = false;
1883 else
1884 LookForIvars = (Lookup.isSingleResult() &&
1885 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001886 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001887 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001888 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001889 ObjCInterfaceDecl *ClassDeclared;
1890 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1891 // Diagnose using an ivar in a class method.
1892 if (IsClassMethod)
1893 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1894 << IV->getDeclName());
1895
1896 // If we're referencing an invalid decl, just return this as a silent
1897 // error node. The error diagnostic was already emitted on the decl.
1898 if (IV->isInvalidDecl())
1899 return ExprError();
1900
1901 // Check if referencing a field with __attribute__((deprecated)).
1902 if (DiagnoseUseOfDecl(IV, Loc))
1903 return ExprError();
1904
1905 // Diagnose the use of an ivar outside of the declaring class.
1906 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1907 ClassDeclared != IFace)
1908 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1909
1910 // FIXME: This should use a new expr for a direct reference, don't
1911 // turn this into Self->ivar, just return a BareIVarExpr or something.
1912 IdentifierInfo &II = Context.Idents.get("self");
1913 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001914 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001915 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001916 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001917 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001918 SelfName, false, false);
1919 if (SelfExpr.isInvalid())
1920 return ExprError();
1921
John Wiegley429bb272011-04-08 18:41:53 +00001922 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1923 if (SelfExpr.isInvalid())
1924 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001925
John McCallf7a1a742009-11-24 19:00:30 +00001926 MarkDeclarationReferenced(Loc, IV);
1927 return Owned(new (Context)
1928 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001929 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001930 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001931 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001932 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001933 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001934 ObjCInterfaceDecl *ClassDeclared;
1935 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1936 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1937 IFace == ClassDeclared)
1938 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1939 }
1940 }
1941
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001942 if (Lookup.empty() && II && AllowBuiltinCreation) {
1943 // FIXME. Consolidate this with similar code in LookupName.
1944 if (unsigned BuiltinID = II->getBuiltinID()) {
1945 if (!(getLangOptions().CPlusPlus &&
1946 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1947 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1948 S, Lookup.isForRedeclaration(),
1949 Lookup.getNameLoc());
1950 if (D) Lookup.addDecl(D);
1951 }
1952 }
1953 }
John McCallf7a1a742009-11-24 19:00:30 +00001954 // Sentinel value saying that we didn't do anything special.
1955 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001956}
John McCallba135432009-11-21 08:51:07 +00001957
John McCall6bb80172010-03-30 21:47:33 +00001958/// \brief Cast a base object to a member's actual type.
1959///
1960/// Logically this happens in three phases:
1961///
1962/// * First we cast from the base type to the naming class.
1963/// The naming class is the class into which we were looking
1964/// when we found the member; it's the qualifier type if a
1965/// qualifier was provided, and otherwise it's the base type.
1966///
1967/// * Next we cast from the naming class to the declaring class.
1968/// If the member we found was brought into a class's scope by
1969/// a using declaration, this is that class; otherwise it's
1970/// the class declaring the member.
1971///
1972/// * Finally we cast from the declaring class to the "true"
1973/// declaring class of the member. This conversion does not
1974/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001975ExprResult
1976Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001977 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001978 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001979 NamedDecl *Member) {
1980 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1981 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001982 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001983
Douglas Gregor5fccd362010-03-03 23:55:11 +00001984 QualType DestRecordType;
1985 QualType DestType;
1986 QualType FromRecordType;
1987 QualType FromType = From->getType();
1988 bool PointerConversions = false;
1989 if (isa<FieldDecl>(Member)) {
1990 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001991
Douglas Gregor5fccd362010-03-03 23:55:11 +00001992 if (FromType->getAs<PointerType>()) {
1993 DestType = Context.getPointerType(DestRecordType);
1994 FromRecordType = FromType->getPointeeType();
1995 PointerConversions = true;
1996 } else {
1997 DestType = DestRecordType;
1998 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001999 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002000 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2001 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002002 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002003
Douglas Gregor5fccd362010-03-03 23:55:11 +00002004 DestType = Method->getThisType(Context);
2005 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002006
Douglas Gregor5fccd362010-03-03 23:55:11 +00002007 if (FromType->getAs<PointerType>()) {
2008 FromRecordType = FromType->getPointeeType();
2009 PointerConversions = true;
2010 } else {
2011 FromRecordType = FromType;
2012 DestType = DestRecordType;
2013 }
2014 } else {
2015 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002016 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002017 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002018
Douglas Gregor5fccd362010-03-03 23:55:11 +00002019 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002020 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002021
Douglas Gregor5fccd362010-03-03 23:55:11 +00002022 // If the unqualified types are the same, no conversion is necessary.
2023 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002024 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002025
John McCall6bb80172010-03-30 21:47:33 +00002026 SourceRange FromRange = From->getSourceRange();
2027 SourceLocation FromLoc = FromRange.getBegin();
2028
John McCall5baba9d2010-08-25 10:28:54 +00002029 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002030
Douglas Gregor5fccd362010-03-03 23:55:11 +00002031 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002032 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002033 // class name.
2034 //
2035 // If the member was a qualified name and the qualified referred to a
2036 // specific base subobject type, we'll cast to that intermediate type
2037 // first and then to the object in which the member is declared. That allows
2038 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2039 //
2040 // class Base { public: int x; };
2041 // class Derived1 : public Base { };
2042 // class Derived2 : public Base { };
2043 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2044 //
2045 // void VeryDerived::f() {
2046 // x = 17; // error: ambiguous base subobjects
2047 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2048 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002049 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002050 QualType QType = QualType(Qualifier->getAsType(), 0);
2051 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2052 assert(QType->isRecordType() && "lookup done with non-record type");
2053
2054 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2055
2056 // In C++98, the qualifier type doesn't actually have to be a base
2057 // type of the object type, in which case we just ignore it.
2058 // Otherwise build the appropriate casts.
2059 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002060 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002061 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002062 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002063 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002064
Douglas Gregor5fccd362010-03-03 23:55:11 +00002065 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002066 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002067 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2068 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002069
2070 FromType = QType;
2071 FromRecordType = QRecordType;
2072
2073 // If the qualifier type was the same as the destination type,
2074 // we're done.
2075 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002076 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002077 }
2078 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002079
John McCall6bb80172010-03-30 21:47:33 +00002080 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002081
John McCall6bb80172010-03-30 21:47:33 +00002082 // If we actually found the member through a using declaration, cast
2083 // down to the using declaration's type.
2084 //
2085 // Pointer equality is fine here because only one declaration of a
2086 // class ever has member declarations.
2087 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2088 assert(isa<UsingShadowDecl>(FoundDecl));
2089 QualType URecordType = Context.getTypeDeclType(
2090 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2091
2092 // We only need to do this if the naming-class to declaring-class
2093 // conversion is non-trivial.
2094 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2095 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002096 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002097 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002098 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002099 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002100
John McCall6bb80172010-03-30 21:47:33 +00002101 QualType UType = URecordType;
2102 if (PointerConversions)
2103 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002104 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2105 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002106 FromType = UType;
2107 FromRecordType = URecordType;
2108 }
2109
2110 // We don't do access control for the conversion from the
2111 // declaring class to the true declaring class.
2112 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002113 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002114
John McCallf871d0c2010-08-07 06:22:56 +00002115 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002116 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2117 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002118 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002119 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002120
John Wiegley429bb272011-04-08 18:41:53 +00002121 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2122 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002123}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002124
John McCallf7a1a742009-11-24 19:00:30 +00002125bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002126 const LookupResult &R,
2127 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002128 // Only when used directly as the postfix-expression of a call.
2129 if (!HasTrailingLParen)
2130 return false;
2131
2132 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002133 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002134 return false;
2135
2136 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002137 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002138 return false;
2139
2140 // Turn off ADL when we find certain kinds of declarations during
2141 // normal lookup:
2142 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2143 NamedDecl *D = *I;
2144
2145 // C++0x [basic.lookup.argdep]p3:
2146 // -- a declaration of a class member
2147 // Since using decls preserve this property, we check this on the
2148 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002149 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002150 return false;
2151
2152 // C++0x [basic.lookup.argdep]p3:
2153 // -- a block-scope function declaration that is not a
2154 // using-declaration
2155 // NOTE: we also trigger this for function templates (in fact, we
2156 // don't check the decl type at all, since all other decl types
2157 // turn off ADL anyway).
2158 if (isa<UsingShadowDecl>(D))
2159 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2160 else if (D->getDeclContext()->isFunctionOrMethod())
2161 return false;
2162
2163 // C++0x [basic.lookup.argdep]p3:
2164 // -- a declaration that is neither a function or a function
2165 // template
2166 // And also for builtin functions.
2167 if (isa<FunctionDecl>(D)) {
2168 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2169
2170 // But also builtin functions.
2171 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2172 return false;
2173 } else if (!isa<FunctionTemplateDecl>(D))
2174 return false;
2175 }
2176
2177 return true;
2178}
2179
2180
John McCallba135432009-11-21 08:51:07 +00002181/// Diagnoses obvious problems with the use of the given declaration
2182/// as an expression. This is only actually called for lookups that
2183/// were not overloaded, and it doesn't promise that the declaration
2184/// will in fact be used.
2185static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002186 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002187 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2188 return true;
2189 }
2190
2191 if (isa<ObjCInterfaceDecl>(D)) {
2192 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2193 return true;
2194 }
2195
2196 if (isa<NamespaceDecl>(D)) {
2197 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2198 return true;
2199 }
2200
2201 return false;
2202}
2203
John McCall60d7b3a2010-08-24 06:29:42 +00002204ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002205Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002206 LookupResult &R,
2207 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002208 // If this is a single, fully-resolved result and we don't need ADL,
2209 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002210 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002211 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2212 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002213
2214 // We only need to check the declaration if there's exactly one
2215 // result, because in the overloaded case the results can only be
2216 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002217 if (R.isSingleResult() &&
2218 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002219 return ExprError();
2220
John McCallc373d482010-01-27 01:50:18 +00002221 // Otherwise, just build an unresolved lookup expression. Suppress
2222 // any lookup-related diagnostics; we'll hash these out later, when
2223 // we've picked a target.
2224 R.suppressDiagnostics();
2225
John McCallba135432009-11-21 08:51:07 +00002226 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002227 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002228 SS.getWithLocInContext(Context),
2229 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002230 NeedsADL, R.isOverloadedResult(),
2231 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002232
2233 return Owned(ULE);
2234}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002235
John McCallba135432009-11-21 08:51:07 +00002236/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002237ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002238Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002239 const DeclarationNameInfo &NameInfo,
2240 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002241 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002242 assert(!isa<FunctionTemplateDecl>(D) &&
2243 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002244
Abramo Bagnara25777432010-08-11 22:01:17 +00002245 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002246 if (CheckDeclInExpr(*this, Loc, D))
2247 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002248
Douglas Gregor9af2f522009-12-01 16:58:18 +00002249 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2250 // Specifically diagnose references to class templates that are missing
2251 // a template argument list.
2252 Diag(Loc, diag::err_template_decl_ref)
2253 << Template << SS.getRange();
2254 Diag(Template->getLocation(), diag::note_template_decl_here);
2255 return ExprError();
2256 }
2257
2258 // Make sure that we're referring to a value.
2259 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2260 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002261 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002262 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002263 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002264 return ExprError();
2265 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002266
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002267 // Check whether this declaration can be used. Note that we suppress
2268 // this check when we're going to perform argument-dependent lookup
2269 // on this function name, because this might not be the function
2270 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002271 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002272 return ExprError();
2273
Steve Naroffdd972f22008-09-05 22:11:13 +00002274 // Only create DeclRefExpr's for valid Decl's.
2275 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002276 return ExprError();
2277
John McCall5808ce42011-02-03 08:15:49 +00002278 // Handle members of anonymous structs and unions. If we got here,
2279 // and the reference is to a class member indirect field, then this
2280 // must be the subject of a pointer-to-member expression.
2281 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2282 if (!indirectField->isCXXClassMember())
2283 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2284 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002285
Chris Lattner639e2d32008-10-20 05:16:36 +00002286 // If the identifier reference is inside a block, and it refers to a value
2287 // that is outside the block, create a BlockDeclRefExpr instead of a
2288 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2289 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002290 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002291 // We do not do this for things like enum constants, global variables, etc,
2292 // as they do not get snapshotted.
2293 //
John McCall6b5a61b2011-02-07 10:33:21 +00002294 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002295 case CR_Error:
2296 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002297
John McCall469a1eb2011-02-02 13:00:07 +00002298 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002299 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2300 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2301
2302 case CR_CaptureByRef:
2303 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2304 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002305
2306 case CR_NoCapture: {
2307 // If this reference is not in a block or if the referenced
2308 // variable is within the block, create a normal DeclRefExpr.
2309
2310 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002311 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002312
2313 switch (D->getKind()) {
2314 // Ignore all the non-ValueDecl kinds.
2315#define ABSTRACT_DECL(kind)
2316#define VALUE(type, base)
2317#define DECL(type, base) \
2318 case Decl::type:
2319#include "clang/AST/DeclNodes.inc"
2320 llvm_unreachable("invalid value decl kind");
2321 return ExprError();
2322
2323 // These shouldn't make it here.
2324 case Decl::ObjCAtDefsField:
2325 case Decl::ObjCIvar:
2326 llvm_unreachable("forming non-member reference to ivar?");
2327 return ExprError();
2328
2329 // Enum constants are always r-values and never references.
2330 // Unresolved using declarations are dependent.
2331 case Decl::EnumConstant:
2332 case Decl::UnresolvedUsingValue:
2333 valueKind = VK_RValue;
2334 break;
2335
2336 // Fields and indirect fields that got here must be for
2337 // pointer-to-member expressions; we just call them l-values for
2338 // internal consistency, because this subexpression doesn't really
2339 // exist in the high-level semantics.
2340 case Decl::Field:
2341 case Decl::IndirectField:
2342 assert(getLangOptions().CPlusPlus &&
2343 "building reference to field in C?");
2344
2345 // These can't have reference type in well-formed programs, but
2346 // for internal consistency we do this anyway.
2347 type = type.getNonReferenceType();
2348 valueKind = VK_LValue;
2349 break;
2350
2351 // Non-type template parameters are either l-values or r-values
2352 // depending on the type.
2353 case Decl::NonTypeTemplateParm: {
2354 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2355 type = reftype->getPointeeType();
2356 valueKind = VK_LValue; // even if the parameter is an r-value reference
2357 break;
2358 }
2359
2360 // For non-references, we need to strip qualifiers just in case
2361 // the template parameter was declared as 'const int' or whatever.
2362 valueKind = VK_RValue;
2363 type = type.getUnqualifiedType();
2364 break;
2365 }
2366
2367 case Decl::Var:
2368 // In C, "extern void blah;" is valid and is an r-value.
2369 if (!getLangOptions().CPlusPlus &&
2370 !type.hasQualifiers() &&
2371 type->isVoidType()) {
2372 valueKind = VK_RValue;
2373 break;
2374 }
2375 // fallthrough
2376
2377 case Decl::ImplicitParam:
2378 case Decl::ParmVar:
2379 // These are always l-values.
2380 valueKind = VK_LValue;
2381 type = type.getNonReferenceType();
2382 break;
2383
2384 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002385 const FunctionType *fty = type->castAs<FunctionType>();
2386
2387 // If we're referring to a function with an __unknown_anytype
2388 // result type, make the entire expression __unknown_anytype.
2389 if (fty->getResultType() == Context.UnknownAnyTy) {
2390 type = Context.UnknownAnyTy;
2391 valueKind = VK_RValue;
2392 break;
2393 }
2394
John McCall76a40212011-02-09 01:13:10 +00002395 // Functions are l-values in C++.
2396 if (getLangOptions().CPlusPlus) {
2397 valueKind = VK_LValue;
2398 break;
2399 }
2400
2401 // C99 DR 316 says that, if a function type comes from a
2402 // function definition (without a prototype), that type is only
2403 // used for checking compatibility. Therefore, when referencing
2404 // the function, we pretend that we don't have the full function
2405 // type.
John McCall755d8492011-04-12 00:42:48 +00002406 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2407 isa<FunctionProtoType>(fty))
2408 type = Context.getFunctionNoProtoType(fty->getResultType(),
2409 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002410
2411 // Functions are r-values in C.
2412 valueKind = VK_RValue;
2413 break;
2414 }
2415
2416 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002417 // If we're referring to a method with an __unknown_anytype
2418 // result type, make the entire expression __unknown_anytype.
2419 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002420 if (const FunctionProtoType *proto
2421 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002422 if (proto->getResultType() == Context.UnknownAnyTy) {
2423 type = Context.UnknownAnyTy;
2424 valueKind = VK_RValue;
2425 break;
2426 }
2427
John McCall76a40212011-02-09 01:13:10 +00002428 // C++ methods are l-values if static, r-values if non-static.
2429 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2430 valueKind = VK_LValue;
2431 break;
2432 }
2433 // fallthrough
2434
2435 case Decl::CXXConversion:
2436 case Decl::CXXDestructor:
2437 case Decl::CXXConstructor:
2438 valueKind = VK_RValue;
2439 break;
2440 }
2441
2442 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2443 }
2444
John McCall469a1eb2011-02-02 13:00:07 +00002445 }
John McCallf89e55a2010-11-18 06:31:45 +00002446
John McCall6b5a61b2011-02-07 10:33:21 +00002447 llvm_unreachable("unknown capture result");
2448 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002449}
2450
John McCall755d8492011-04-12 00:42:48 +00002451ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002452 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002453
Reid Spencer5f016e22007-07-11 17:01:13 +00002454 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002455 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002456 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2457 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2458 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002460
Chris Lattnerfa28b302008-01-12 08:14:25 +00002461 // Pre-defined identifiers are of type char[x], where x is the length of the
2462 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Anders Carlsson3a082d82009-09-08 18:24:21 +00002464 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002465 if (!currentDecl && getCurBlock())
2466 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002467 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002468 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002469 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002470 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002471
Anders Carlsson773f3972009-09-11 01:22:35 +00002472 QualType ResTy;
2473 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2474 ResTy = Context.DependentTy;
2475 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002476 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002477
Anders Carlsson773f3972009-09-11 01:22:35 +00002478 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002479 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002480 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2481 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002482 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002483}
2484
John McCall60d7b3a2010-08-24 06:29:42 +00002485ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002486 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002487 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002488 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002489 if (Invalid)
2490 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002491
Benjamin Kramerddeea562010-02-27 13:44:12 +00002492 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002493 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002495 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002496
Chris Lattnere8337df2009-12-30 21:19:39 +00002497 QualType Ty;
2498 if (!getLangOptions().CPlusPlus)
2499 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2500 else if (Literal.isWide())
2501 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002502 else if (Literal.isUTF16())
2503 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2504 else if (Literal.isUTF32())
2505 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002506 else if (Literal.isMultiChar())
2507 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002508 else
2509 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002510
Douglas Gregor5cee1192011-07-27 05:40:30 +00002511 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2512 if (Literal.isWide())
2513 Kind = CharacterLiteral::Wide;
2514 else if (Literal.isUTF16())
2515 Kind = CharacterLiteral::UTF16;
2516 else if (Literal.isUTF32())
2517 Kind = CharacterLiteral::UTF32;
2518
2519 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2520 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002521}
2522
John McCall60d7b3a2010-08-24 06:29:42 +00002523ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2526 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002527 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002528 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002529 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002530 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 }
Ted Kremenek28396602009-01-13 23:19:12 +00002532
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002534 // Add padding so that NumericLiteralParser can overread by one character.
2535 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002537
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002539 bool Invalid = false;
2540 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2541 if (Invalid)
2542 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002543
Mike Stump1eb44332009-09-09 15:08:12 +00002544 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 Tok.getLocation(), PP);
2546 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002547 return ExprError();
2548
Chris Lattner5d661452007-08-26 03:42:43 +00002549 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002550
Chris Lattner5d661452007-08-26 03:42:43 +00002551 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002552 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002553 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002554 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002555 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002556 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002557 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002558 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002559
2560 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2561
John McCall94c939d2009-12-24 09:08:04 +00002562 using llvm::APFloat;
2563 APFloat Val(Format);
2564
2565 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002566
2567 // Overflow is always an error, but underflow is only an error if
2568 // we underflowed to zero (APFloat reports denormals as underflow).
2569 if ((result & APFloat::opOverflow) ||
2570 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002571 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002572 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002573 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002574 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002575 APFloat::getLargest(Format).toString(buffer);
2576 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002577 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002578 APFloat::getSmallest(Format).toString(buffer);
2579 }
2580
2581 Diag(Tok.getLocation(), diagnostic)
2582 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002583 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002584 }
2585
2586 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002587 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002588
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002589 if (Ty == Context.DoubleTy) {
2590 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002591 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002592 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2593 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002594 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002595 }
2596 }
Chris Lattner5d661452007-08-26 03:42:43 +00002597 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002598 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002599 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002600 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002601
Neil Boothb9449512007-08-29 22:00:19 +00002602 // long long is a C99 feature.
2603 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002604 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002605 Diag(Tok.getLocation(), diag::ext_longlong);
2606
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002608 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002609
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 if (Literal.GetIntegerValue(ResultVal)) {
2611 // If this value didn't fit into uintmax_t, warn and force to ull.
2612 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002613 Ty = Context.UnsignedLongLongTy;
2614 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002615 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 } else {
2617 // If this value fits into a ULL, try to figure out what else it fits into
2618 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2621 // be an unsigned int.
2622 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2623
2624 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002625 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002626 if (!Literal.isLong && !Literal.isLongLong) {
2627 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002628 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 // Does it fit in a unsigned int?
2631 if (ResultVal.isIntN(IntSize)) {
2632 // Does it fit in a signed int?
2633 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002634 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002636 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002637 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002640
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002642 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002643 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Does it fit in a unsigned long?
2646 if (ResultVal.isIntN(LongSize)) {
2647 // Does it fit in a signed long?
2648 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002649 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002651 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002652 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002654 }
2655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002657 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002658 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002659
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 // Does it fit in a unsigned long long?
2661 if (ResultVal.isIntN(LongLongSize)) {
2662 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002663 // To be compatible with MSVC, hex integer literals ending with the
2664 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002665 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2666 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002667 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002669 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002670 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
2672 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002673
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 // If we still couldn't decide a type, we probably have something that
2675 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002676 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002678 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002679 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002681
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002682 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002683 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002685 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002687
Chris Lattner5d661452007-08-26 03:42:43 +00002688 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2689 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002690 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002691 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002692
2693 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002694}
2695
John McCall60d7b3a2010-08-24 06:29:42 +00002696ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002697 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002698 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002699 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002700}
2701
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002702static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2703 SourceLocation Loc,
2704 SourceRange ArgRange) {
2705 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2706 // scalar or vector data type argument..."
2707 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2708 // type (C99 6.2.5p18) or void.
2709 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2710 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2711 << T << ArgRange;
2712 return true;
2713 }
2714
2715 assert((T->isVoidType() || !T->isIncompleteType()) &&
2716 "Scalar types should always be complete");
2717 return false;
2718}
2719
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002720static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2721 SourceLocation Loc,
2722 SourceRange ArgRange,
2723 UnaryExprOrTypeTrait TraitKind) {
2724 // C99 6.5.3.4p1:
2725 if (T->isFunctionType()) {
2726 // alignof(function) is allowed as an extension.
2727 if (TraitKind == UETT_SizeOf)
2728 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2729 return false;
2730 }
2731
2732 // Allow sizeof(void)/alignof(void) as an extension.
2733 if (T->isVoidType()) {
2734 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2735 return false;
2736 }
2737
2738 return true;
2739}
2740
2741static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2742 SourceLocation Loc,
2743 SourceRange ArgRange,
2744 UnaryExprOrTypeTrait TraitKind) {
2745 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2746 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2747 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2748 << T << (TraitKind == UETT_SizeOf)
2749 << ArgRange;
2750 return true;
2751 }
2752
2753 return false;
2754}
2755
Chandler Carruth9d342d02011-05-26 08:53:10 +00002756/// \brief Check the constrains on expression operands to unary type expression
2757/// and type traits.
2758///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002759/// Completes any types necessary and validates the constraints on the operand
2760/// expression. The logic mostly mirrors the type-based overload, but may modify
2761/// the expression as it completes the type for that expression through template
2762/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002763bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2764 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002765 QualType ExprTy = Op->getType();
2766
2767 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2768 // the result is the size of the referenced type."
2769 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2770 // result shall be the alignment of the referenced type."
2771 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2772 ExprTy = Ref->getPointeeType();
2773
2774 if (ExprKind == UETT_VecStep)
2775 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2776 Op->getSourceRange());
2777
2778 // Whitelist some types as extensions
2779 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2780 Op->getSourceRange(), ExprKind))
2781 return false;
2782
2783 if (RequireCompleteExprType(Op,
2784 PDiag(diag::err_sizeof_alignof_incomplete_type)
2785 << ExprKind << Op->getSourceRange(),
2786 std::make_pair(SourceLocation(), PDiag(0))))
2787 return true;
2788
2789 // Completeing the expression's type may have changed it.
2790 ExprTy = Op->getType();
2791 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2792 ExprTy = Ref->getPointeeType();
2793
2794 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2795 Op->getSourceRange(), ExprKind))
2796 return true;
2797
Nico Webercf739922011-06-15 02:47:03 +00002798 if (ExprKind == UETT_SizeOf) {
2799 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2800 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2801 QualType OType = PVD->getOriginalType();
2802 QualType Type = PVD->getType();
2803 if (Type->isPointerType() && OType->isArrayType()) {
2804 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2805 << Type << OType;
2806 Diag(PVD->getLocation(), diag::note_declared_at);
2807 }
2808 }
2809 }
2810 }
2811
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002812 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002813}
2814
2815/// \brief Check the constraints on operands to unary expression and type
2816/// traits.
2817///
2818/// This will complete any types necessary, and validate the various constraints
2819/// on those operands.
2820///
Reid Spencer5f016e22007-07-11 17:01:13 +00002821/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002822/// C99 6.3.2.1p[2-4] all state:
2823/// Except when it is the operand of the sizeof operator ...
2824///
2825/// C++ [expr.sizeof]p4
2826/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2827/// standard conversions are not applied to the operand of sizeof.
2828///
2829/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002830bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2831 SourceLocation OpLoc,
2832 SourceRange ExprRange,
2833 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002834 if (exprType->isDependentType())
2835 return false;
2836
Sebastian Redl5d484e82009-11-23 17:18:46 +00002837 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2838 // the result is the size of the referenced type."
2839 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2840 // result shall be the alignment of the referenced type."
2841 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2842 exprType = Ref->getPointeeType();
2843
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002844 if (ExprKind == UETT_VecStep)
2845 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002846
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002847 // Whitelist some types as extensions
2848 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2849 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002850 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Chris Lattner1efaa952009-04-24 00:30:45 +00002852 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002853 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002854 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002855 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002857 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2858 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002859 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Chris Lattner1efaa952009-04-24 00:30:45 +00002861 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002862}
2863
Chandler Carruth9d342d02011-05-26 08:53:10 +00002864static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002865 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002866
Mike Stump1eb44332009-09-09 15:08:12 +00002867 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002868 if (isa<DeclRefExpr>(E))
2869 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002870
2871 // Cannot know anything else if the expression is dependent.
2872 if (E->isTypeDependent())
2873 return false;
2874
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002875 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002876 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2877 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002878 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002879 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002880
2881 // Alignment of a field access is always okay, so long as it isn't a
2882 // bit-field.
2883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002884 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002885 return false;
2886
Chandler Carruth9d342d02011-05-26 08:53:10 +00002887 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002888}
2889
Chandler Carruth9d342d02011-05-26 08:53:10 +00002890bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002891 E = E->IgnoreParens();
2892
2893 // Cannot know anything else if the expression is dependent.
2894 if (E->isTypeDependent())
2895 return false;
2896
Chandler Carruth9d342d02011-05-26 08:53:10 +00002897 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002898}
2899
Douglas Gregorba498172009-03-13 21:01:28 +00002900/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002901ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002902Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2903 SourceLocation OpLoc,
2904 UnaryExprOrTypeTrait ExprKind,
2905 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002906 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002907 return ExprError();
2908
John McCalla93c9342009-12-07 02:54:59 +00002909 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002910
Douglas Gregorba498172009-03-13 21:01:28 +00002911 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002912 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002913 return ExprError();
2914
2915 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002916 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2917 Context.getSizeType(),
2918 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002919}
2920
2921/// \brief Build a sizeof or alignof expression given an expression
2922/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002923ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002924Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2925 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002926 ExprResult PE = CheckPlaceholderExpr(E);
2927 if (PE.isInvalid())
2928 return ExprError();
2929
2930 E = PE.get();
2931
Douglas Gregorba498172009-03-13 21:01:28 +00002932 // Verify that the operand is valid.
2933 bool isInvalid = false;
2934 if (E->isTypeDependent()) {
2935 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002936 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002937 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002938 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002939 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002940 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002941 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002942 isInvalid = true;
2943 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002944 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002945 }
2946
2947 if (isInvalid)
2948 return ExprError();
2949
2950 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002951 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002952 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002953 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002954}
2955
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002956/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2957/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002958/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002959ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002960Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2961 UnaryExprOrTypeTrait ExprKind, bool isType,
2962 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002963 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002964 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002965
Sebastian Redl05189992008-11-11 17:56:53 +00002966 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002967 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002968 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002969 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002970 }
Sebastian Redl05189992008-11-11 17:56:53 +00002971
Douglas Gregorba498172009-03-13 21:01:28 +00002972 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002973 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002974 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002975}
2976
John Wiegley429bb272011-04-08 18:41:53 +00002977static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002978 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002979 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002980 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002981
John McCallf6a16482010-12-04 03:47:34 +00002982 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002983 if (V.get()->getObjectKind() != OK_Ordinary) {
2984 V = S.DefaultLvalueConversion(V.take());
2985 if (V.isInvalid())
2986 return QualType();
2987 }
John McCallf6a16482010-12-04 03:47:34 +00002988
Chris Lattnercc26ed72007-08-26 05:39:26 +00002989 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002990 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002991 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Chris Lattnercc26ed72007-08-26 05:39:26 +00002993 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002994 if (V.get()->getType()->isArithmeticType())
2995 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002996
John McCall2cd11fe2010-10-12 02:09:17 +00002997 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002998 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002999 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003000 if (PR.get() != V.get()) {
3001 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003002 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003003 }
3004
Chris Lattnercc26ed72007-08-26 05:39:26 +00003005 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003006 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003007 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003008 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003009}
3010
3011
Reid Spencer5f016e22007-07-11 17:01:13 +00003012
John McCall60d7b3a2010-08-24 06:29:42 +00003013ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003014Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003015 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003016 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 switch (Kind) {
3018 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003019 case tok::plusplus: Opc = UO_PostInc; break;
3020 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003022
John McCall9ae2f072010-08-23 23:25:46 +00003023 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003024}
3025
John McCall60d7b3a2010-08-24 06:29:42 +00003026ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003027Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3028 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003029 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003030 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003031 if (Result.isInvalid()) return ExprError();
3032 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003033
John McCall9ae2f072010-08-23 23:25:46 +00003034 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Douglas Gregor337c6b92008-11-19 17:17:41 +00003036 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003037 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003038 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003039 Context.DependentTy,
3040 VK_LValue, OK_Ordinary,
3041 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003042 }
3043
Mike Stump1eb44332009-09-09 15:08:12 +00003044 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003045 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003046 LHSExp->getType()->isEnumeralType() ||
3047 RHSExp->getType()->isRecordType() ||
3048 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003049 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003050 }
3051
John McCall9ae2f072010-08-23 23:25:46 +00003052 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003053}
3054
3055
John McCall60d7b3a2010-08-24 06:29:42 +00003056ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003057Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3058 Expr *Idx, SourceLocation RLoc) {
3059 Expr *LHSExp = Base;
3060 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003061
Chris Lattner12d9ff62007-07-16 00:14:47 +00003062 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003063 if (!LHSExp->getType()->getAs<VectorType>()) {
3064 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3065 if (Result.isInvalid())
3066 return ExprError();
3067 LHSExp = Result.take();
3068 }
3069 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3070 if (Result.isInvalid())
3071 return ExprError();
3072 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003073
Chris Lattner12d9ff62007-07-16 00:14:47 +00003074 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003075 ExprValueKind VK = VK_LValue;
3076 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003077
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003079 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003080 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003081 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003082 Expr *BaseExpr, *IndexExpr;
3083 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003084 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3085 BaseExpr = LHSExp;
3086 IndexExpr = RHSExp;
3087 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003088 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003089 BaseExpr = LHSExp;
3090 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003091 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003092 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003093 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003094 BaseExpr = RHSExp;
3095 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003096 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003097 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003098 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003099 BaseExpr = LHSExp;
3100 IndexExpr = RHSExp;
3101 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003102 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003103 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003104 // Handle the uncommon case of "123[Ptr]".
3105 BaseExpr = RHSExp;
3106 IndexExpr = LHSExp;
3107 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003108 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003109 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003110 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003111 VK = LHSExp->getValueKind();
3112 if (VK != VK_RValue)
3113 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003114
Chris Lattner12d9ff62007-07-16 00:14:47 +00003115 // FIXME: need to deal with const...
3116 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003117 } else if (LHSTy->isArrayType()) {
3118 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003119 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003120 // wasn't promoted because of the C90 rule that doesn't
3121 // allow promoting non-lvalue arrays. Warn, then
3122 // force the promotion here.
3123 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3124 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003125 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3126 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003127 LHSTy = LHSExp->getType();
3128
3129 BaseExpr = LHSExp;
3130 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003131 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003132 } else if (RHSTy->isArrayType()) {
3133 // Same as previous, except for 123[f().a] case
3134 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3135 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003136 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3137 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003138 RHSTy = RHSExp->getType();
3139
3140 BaseExpr = RHSExp;
3141 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003142 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003144 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3145 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003148 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003149 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3150 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003151
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003152 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003153 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3154 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003155 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3156
Douglas Gregore7450f52009-03-24 19:52:54 +00003157 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003158 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3159 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003160 // incomplete types are not object types.
3161 if (ResultType->isFunctionType()) {
3162 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3163 << ResultType << BaseExpr->getSourceRange();
3164 return ExprError();
3165 }
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Abramo Bagnara46358452010-09-13 06:50:07 +00003167 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3168 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003169 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3170 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003171
3172 // C forbids expressions of unqualified void type from being l-values.
3173 // See IsCForbiddenLValueType.
3174 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003175 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003176 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003177 PDiag(diag::err_subscript_incomplete_type)
3178 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003179 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Chris Lattner1efaa952009-04-24 00:30:45 +00003181 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003182 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003183 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3184 << ResultType << BaseExpr->getSourceRange();
3185 return ExprError();
3186 }
Mike Stump1eb44332009-09-09 15:08:12 +00003187
John McCall09431682010-11-18 19:01:18 +00003188 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003189 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003190
Mike Stumpeed9cac2009-02-19 03:04:26 +00003191 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003192 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003193}
3194
John McCall60d7b3a2010-08-24 06:29:42 +00003195ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003196 FunctionDecl *FD,
3197 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003198 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003199 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003200 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003201 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003202 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003203 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003204 return ExprError();
3205 }
3206
3207 if (Param->hasUninstantiatedDefaultArg()) {
3208 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003209
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003210 // Instantiate the expression.
3211 MultiLevelTemplateArgumentList ArgList
3212 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003213
Nico Weber08e41a62010-11-29 18:19:25 +00003214 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003215 = ArgList.getInnermost();
3216 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3217 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003218
Nico Weber08e41a62010-11-29 18:19:25 +00003219 ExprResult Result;
3220 {
3221 // C++ [dcl.fct.default]p5:
3222 // The names in the [default argument] expression are bound, and
3223 // the semantic constraints are checked, at the point where the
3224 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003225 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003226 Result = SubstExpr(UninstExpr, ArgList);
3227 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003228 if (Result.isInvalid())
3229 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003231 // Check the expression as an initializer for the parameter.
3232 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003233 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003234 InitializationKind Kind
3235 = InitializationKind::CreateCopy(Param->getLocation(),
3236 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3237 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003238
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003239 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3240 Result = InitSeq.Perform(*this, Entity, Kind,
3241 MultiExprArg(*this, &ResultE, 1));
3242 if (Result.isInvalid())
3243 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003244
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003245 // Build the default argument expression.
3246 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3247 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003248 }
3249
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003250 // If the default expression creates temporaries, we need to
3251 // push them to the current stack of expression temporaries so they'll
3252 // be properly destroyed.
3253 // FIXME: We should really be rebuilding the default argument with new
3254 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003255 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3256 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3257 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3258 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3259 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003260 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003261 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003262
3263 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003264 // Just mark all of the declarations in this potentially-evaluated expression
3265 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003266 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003267 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003268}
3269
Douglas Gregor88a35142008-12-22 05:46:06 +00003270/// ConvertArgumentsForCall - Converts the arguments specified in
3271/// Args/NumArgs to the parameter types of the function FDecl with
3272/// function prototype Proto. Call is the call expression itself, and
3273/// Fn is the function expression. For a C++ member function, this
3274/// routine does not attempt to convert the object argument. Returns
3275/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003276bool
3277Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003278 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003279 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003280 Expr **Args, unsigned NumArgs,
3281 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003282 // Bail out early if calling a builtin with custom typechecking.
3283 // We don't need to do this in the
3284 if (FDecl)
3285 if (unsigned ID = FDecl->getBuiltinID())
3286 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3287 return false;
3288
Mike Stumpeed9cac2009-02-19 03:04:26 +00003289 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003290 // assignment, to the types of the corresponding parameter, ...
3291 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003292 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003293
Douglas Gregor88a35142008-12-22 05:46:06 +00003294 // If too few arguments are available (and we don't have default
3295 // arguments for the remaining parameters), don't make the call.
3296 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003297 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3298 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003299 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003300 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003301
3302 // Emit the location of the prototype.
3303 if (FDecl && !FDecl->getBuiltinID())
3304 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3305 << FDecl;
3306
3307 return true;
3308 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003309 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003310 }
3311
3312 // If too many are passed and not variadic, error on the extras and drop
3313 // them.
3314 if (NumArgs > NumArgsInProto) {
3315 if (!Proto->isVariadic()) {
3316 Diag(Args[NumArgsInProto]->getLocStart(),
3317 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003318 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003319 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003320 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3321 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003322
3323 // Emit the location of the prototype.
3324 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003325 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3326 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003327
Douglas Gregor88a35142008-12-22 05:46:06 +00003328 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003329 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003330 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003331 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003332 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003333 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003334 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003335 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3336 if (Fn->getType()->isBlockPointerType())
3337 CallType = VariadicBlock; // Block
3338 else if (isa<MemberExpr>(Fn))
3339 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003340 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003341 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003342 if (Invalid)
3343 return true;
3344 unsigned TotalNumArgs = AllArgs.size();
3345 for (unsigned i = 0; i < TotalNumArgs; ++i)
3346 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003347
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003348 return false;
3349}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003350
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003351bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3352 FunctionDecl *FDecl,
3353 const FunctionProtoType *Proto,
3354 unsigned FirstProtoArg,
3355 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003356 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003357 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003358 unsigned NumArgsInProto = Proto->getNumArgs();
3359 unsigned NumArgsToCheck = NumArgs;
3360 bool Invalid = false;
3361 if (NumArgs != NumArgsInProto)
3362 // Use default arguments for missing arguments
3363 NumArgsToCheck = NumArgsInProto;
3364 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003365 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003366 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003367 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003368
Douglas Gregor88a35142008-12-22 05:46:06 +00003369 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003370 if (ArgIx < NumArgs) {
3371 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003372
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003373 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3374 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003375 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003377 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003378
Douglas Gregora188ff22009-12-22 16:09:06 +00003379 // Pass the argument
3380 ParmVarDecl *Param = 0;
3381 if (FDecl && i < FDecl->getNumParams())
3382 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003383
Douglas Gregora188ff22009-12-22 16:09:06 +00003384 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003385 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003386 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3387 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003388 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003389 SourceLocation(),
3390 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003391 if (ArgE.isInvalid())
3392 return true;
3393
3394 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003395 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003396 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003397
John McCall60d7b3a2010-08-24 06:29:42 +00003398 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003399 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003400 if (ArgExpr.isInvalid())
3401 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003402
Anders Carlsson56c5e332009-08-25 03:49:14 +00003403 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003404 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003405
3406 // Check for array bounds violations for each argument to the call. This
3407 // check only triggers warnings when the argument isn't a more complex Expr
3408 // with its own checking, such as a BinaryOperator.
3409 CheckArrayAccess(Arg);
3410
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003411 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003412 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003413
Douglas Gregor88a35142008-12-22 05:46:06 +00003414 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003415 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003416
3417 // Assume that extern "C" functions with variadic arguments that
3418 // return __unknown_anytype aren't *really* variadic.
3419 if (Proto->getResultType() == Context.UnknownAnyTy &&
3420 FDecl && FDecl->isExternC()) {
3421 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3422 ExprResult arg;
3423 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3424 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3425 else
3426 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3427 Invalid |= arg.isInvalid();
3428 AllArgs.push_back(arg.take());
3429 }
3430
3431 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3432 } else {
3433 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003434 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3435 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003436 Invalid |= Arg.isInvalid();
3437 AllArgs.push_back(Arg.take());
3438 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003439 }
3440 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003441 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003442}
3443
John McCall755d8492011-04-12 00:42:48 +00003444/// Given a function expression of unknown-any type, try to rebuild it
3445/// to have a function type.
3446static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3447
Steve Narofff69936d2007-09-16 03:34:24 +00003448/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003449/// This provides the location of the left/right parens and a list of comma
3450/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003451ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003452Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003453 MultiExprArg args, SourceLocation RParenLoc,
3454 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003455 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003456
3457 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003458 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003459 if (Result.isInvalid()) return ExprError();
3460 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003461
John McCall9ae2f072010-08-23 23:25:46 +00003462 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor88a35142008-12-22 05:46:06 +00003464 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003465 // If this is a pseudo-destructor expression, build the call immediately.
3466 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3467 if (NumArgs > 0) {
3468 // Pseudo-destructor calls should not have any arguments.
3469 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003470 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003471 SourceRange(Args[0]->getLocStart(),
3472 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Douglas Gregora71d8192009-09-04 17:36:40 +00003474 NumArgs = 0;
3475 }
Mike Stump1eb44332009-09-09 15:08:12 +00003476
Douglas Gregora71d8192009-09-04 17:36:40 +00003477 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003478 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003479 }
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Douglas Gregor17330012009-02-04 15:01:18 +00003481 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003482 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003483 // FIXME: Will need to cache the results of name lookup (including ADL) in
3484 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003485 bool Dependent = false;
3486 if (Fn->isTypeDependent())
3487 Dependent = true;
3488 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3489 Dependent = true;
3490
Peter Collingbournee08ce652011-02-09 21:07:24 +00003491 if (Dependent) {
3492 if (ExecConfig) {
3493 return Owned(new (Context) CUDAKernelCallExpr(
3494 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3495 Context.DependentTy, VK_RValue, RParenLoc));
3496 } else {
3497 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3498 Context.DependentTy, VK_RValue,
3499 RParenLoc));
3500 }
3501 }
Douglas Gregor17330012009-02-04 15:01:18 +00003502
3503 // Determine whether this is a call to an object (C++ [over.call.object]).
3504 if (Fn->getType()->isRecordType())
3505 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003506 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003507
John McCall755d8492011-04-12 00:42:48 +00003508 if (Fn->getType() == Context.UnknownAnyTy) {
3509 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3510 if (result.isInvalid()) return ExprError();
3511 Fn = result.take();
3512 }
3513
John McCall864c0412011-04-26 20:42:42 +00003514 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003515 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003516 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003517 }
John McCall864c0412011-04-26 20:42:42 +00003518 }
John McCall129e2df2009-11-30 22:42:35 +00003519
John McCall864c0412011-04-26 20:42:42 +00003520 // Check for overloaded calls. This can happen even in C due to extensions.
3521 if (Fn->getType() == Context.OverloadTy) {
3522 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3523
3524 // We aren't supposed to apply this logic if there's an '&' involved.
3525 if (!find.IsAddressOfOperand) {
3526 OverloadExpr *ovl = find.Expression;
3527 if (isa<UnresolvedLookupExpr>(ovl)) {
3528 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3529 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3530 RParenLoc, ExecConfig);
3531 } else {
John McCallaa81e162009-12-01 22:10:20 +00003532 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003533 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003534 }
3535 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003536 }
3537
Douglas Gregorfa047642009-02-04 00:32:51 +00003538 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003539
Eli Friedmanefa42f72009-12-26 03:35:45 +00003540 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003541
John McCall3b4294e2009-12-16 12:17:52 +00003542 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003543 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3544 if (UnOp->getOpcode() == UO_AddrOf)
3545 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3546
John McCall3b4294e2009-12-16 12:17:52 +00003547 if (isa<DeclRefExpr>(NakedFn))
3548 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003549 else if (isa<MemberExpr>(NakedFn))
3550 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003551
Peter Collingbournee08ce652011-02-09 21:07:24 +00003552 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3553 ExecConfig);
3554}
3555
3556ExprResult
3557Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3558 MultiExprArg execConfig, SourceLocation GGGLoc) {
3559 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3560 if (!ConfigDecl)
3561 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3562 << "cudaConfigureCall");
3563 QualType ConfigQTy = ConfigDecl->getType();
3564
3565 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3566 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3567
3568 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003569}
3570
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003571/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3572///
3573/// __builtin_astype( value, dst type )
3574///
3575ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3576 SourceLocation BuiltinLoc,
3577 SourceLocation RParenLoc) {
3578 ExprValueKind VK = VK_RValue;
3579 ExprObjectKind OK = OK_Ordinary;
3580 QualType DstTy = GetTypeFromParser(destty);
3581 QualType SrcTy = expr->getType();
3582 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3583 return ExprError(Diag(BuiltinLoc,
3584 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003585 << DstTy
3586 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003587 << expr->getSourceRange());
Richard Trieu67e29332011-08-02 04:35:43 +00003588 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3589 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003590}
3591
John McCall3b4294e2009-12-16 12:17:52 +00003592/// BuildResolvedCallExpr - Build a call to a resolved expression,
3593/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003594/// unary-convert to an expression of function-pointer or
3595/// block-pointer type.
3596///
3597/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003598ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003599Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3600 SourceLocation LParenLoc,
3601 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003602 SourceLocation RParenLoc,
3603 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003604 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3605
Chris Lattner04421082008-04-08 04:40:51 +00003606 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003607 ExprResult Result = UsualUnaryConversions(Fn);
3608 if (Result.isInvalid())
3609 return ExprError();
3610 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003611
Chris Lattner925e60d2007-12-28 05:29:59 +00003612 // Make the call expr early, before semantic checks. This guarantees cleanup
3613 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003614 CallExpr *TheCall;
3615 if (Config) {
3616 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3617 cast<CallExpr>(Config),
3618 Args, NumArgs,
3619 Context.BoolTy,
3620 VK_RValue,
3621 RParenLoc);
3622 } else {
3623 TheCall = new (Context) CallExpr(Context, Fn,
3624 Args, NumArgs,
3625 Context.BoolTy,
3626 VK_RValue,
3627 RParenLoc);
3628 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003629
John McCall8e10f3b2011-02-26 05:39:39 +00003630 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3631
3632 // Bail out early if calling a builtin with custom typechecking.
3633 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3634 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3635
John McCall1de4d4e2011-04-07 08:22:57 +00003636 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003637 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003638 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003639 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3640 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003641 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003642 if (FuncT == 0)
3643 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3644 << Fn->getType() << Fn->getSourceRange());
3645 } else if (const BlockPointerType *BPT =
3646 Fn->getType()->getAs<BlockPointerType>()) {
3647 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3648 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003649 // Handle calls to expressions of unknown-any type.
3650 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003651 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003652 if (rewrite.isInvalid()) return ExprError();
3653 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003654 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003655 goto retry;
3656 }
3657
Sebastian Redl0eb23302009-01-19 00:08:26 +00003658 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3659 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003660 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003661
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003662 if (getLangOptions().CUDA) {
3663 if (Config) {
3664 // CUDA: Kernel calls must be to global functions
3665 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3666 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3667 << FDecl->getName() << Fn->getSourceRange());
3668
3669 // CUDA: Kernel function must have 'void' return type
3670 if (!FuncT->getResultType()->isVoidType())
3671 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3672 << Fn->getType() << Fn->getSourceRange());
3673 }
3674 }
3675
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003676 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003677 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003678 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003679 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003680 return ExprError();
3681
Chris Lattner925e60d2007-12-28 05:29:59 +00003682 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003683 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003684 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003685
Douglas Gregor72564e72009-02-26 23:50:07 +00003686 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003687 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003688 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003689 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003690 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003691 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003692
Douglas Gregor74734d52009-04-02 15:37:10 +00003693 if (FDecl) {
3694 // Check if we have too few/too many template arguments, based
3695 // on our knowledge of the function definition.
3696 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003697 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003698 const FunctionProtoType *Proto
3699 = Def->getType()->getAs<FunctionProtoType>();
3700 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003701 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3702 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003703 }
Douglas Gregor46542412010-10-25 20:39:23 +00003704
3705 // If the function we're calling isn't a function prototype, but we have
3706 // a function prototype from a prior declaratiom, use that prototype.
3707 if (!FDecl->hasPrototype())
3708 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003709 }
3710
Steve Naroffb291ab62007-08-28 23:30:39 +00003711 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003712 for (unsigned i = 0; i != NumArgs; i++) {
3713 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003714
3715 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003716 InitializedEntity Entity
3717 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003718 Proto->getArgType(i),
3719 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003720 ExprResult ArgE = PerformCopyInitialization(Entity,
3721 SourceLocation(),
3722 Owned(Arg));
3723 if (ArgE.isInvalid())
3724 return true;
3725
3726 Arg = ArgE.takeAs<Expr>();
3727
3728 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003729 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3730
3731 if (ArgE.isInvalid())
3732 return true;
3733
3734 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003735 }
3736
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003737 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3738 Arg->getType(),
3739 PDiag(diag::err_call_incomplete_argument)
3740 << Arg->getSourceRange()))
3741 return ExprError();
3742
Chris Lattner925e60d2007-12-28 05:29:59 +00003743 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003744 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003745 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003746
Douglas Gregor88a35142008-12-22 05:46:06 +00003747 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3748 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003749 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3750 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003751
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003752 // Check for sentinels
3753 if (NDecl)
3754 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Chris Lattner59907c42007-08-10 20:18:51 +00003756 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003757 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003758 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003759 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003760
John McCall8e10f3b2011-02-26 05:39:39 +00003761 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003762 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003763 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003764 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003765 return ExprError();
3766 }
Chris Lattner59907c42007-08-10 20:18:51 +00003767
John McCall9ae2f072010-08-23 23:25:46 +00003768 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003769}
3770
John McCall60d7b3a2010-08-24 06:29:42 +00003771ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003772Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003773 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003774 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003775 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003776 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003777
3778 TypeSourceInfo *TInfo;
3779 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3780 if (!TInfo)
3781 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3782
John McCall9ae2f072010-08-23 23:25:46 +00003783 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003784}
3785
John McCall60d7b3a2010-08-24 06:29:42 +00003786ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003787Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003788 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003789 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003790
Eli Friedman6223c222008-05-20 05:22:08 +00003791 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003792 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3793 PDiag(diag::err_illegal_decl_array_incomplete_type)
3794 << SourceRange(LParenLoc,
3795 literalExpr->getSourceRange().getEnd())))
3796 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003797 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003798 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3799 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003800 } else if (!literalType->isDependentType() &&
3801 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003802 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003803 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003804 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003805 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003806
Douglas Gregor99a2e602009-12-16 01:38:02 +00003807 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003808 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003809 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003810 = InitializationKind::CreateCStyleCast(LParenLoc,
3811 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003812 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003813 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003814 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003815 &literalType);
3816 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003817 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003818 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003819
Chris Lattner371f2582008-12-04 23:50:19 +00003820 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003821 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003822 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003823 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003824 }
Eli Friedman08544622009-12-22 02:35:53 +00003825
John McCallf89e55a2010-11-18 06:31:45 +00003826 // In C, compound literals are l-values for some reason.
3827 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3828
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003829 return MaybeBindToTemporary(
3830 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3831 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003832}
3833
John McCall60d7b3a2010-08-24 06:29:42 +00003834ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003835Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003836 SourceLocation RBraceLoc) {
3837 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003838 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003839
Steve Naroff08d92e42007-09-15 18:49:24 +00003840 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003841 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003842
Ted Kremenek709210f2010-04-13 23:39:13 +00003843 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3844 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003845 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003846 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003847}
3848
John McCallf3ea8cf2010-11-14 08:17:51 +00003849/// Prepares for a scalar cast, performing all the necessary stages
3850/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003851static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003852 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3853 // Also, callers should have filtered out the invalid cases with
3854 // pointers. Everything else should be possible.
3855
John Wiegley429bb272011-04-08 18:41:53 +00003856 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003857 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003858 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003859
John McCalldaa8e4e2010-11-15 09:13:47 +00003860 switch (SrcTy->getScalarTypeKind()) {
3861 case Type::STK_MemberPointer:
3862 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003863
John McCalldaa8e4e2010-11-15 09:13:47 +00003864 case Type::STK_Pointer:
3865 switch (DestTy->getScalarTypeKind()) {
3866 case Type::STK_Pointer:
3867 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003868 CK_AnyPointerToObjCPointerCast :
3869 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003870 case Type::STK_Bool:
3871 return CK_PointerToBoolean;
3872 case Type::STK_Integral:
3873 return CK_PointerToIntegral;
3874 case Type::STK_Floating:
3875 case Type::STK_FloatingComplex:
3876 case Type::STK_IntegralComplex:
3877 case Type::STK_MemberPointer:
3878 llvm_unreachable("illegal cast from pointer");
3879 }
3880 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003881
John McCalldaa8e4e2010-11-15 09:13:47 +00003882 case Type::STK_Bool: // casting from bool is like casting from an integer
3883 case Type::STK_Integral:
3884 switch (DestTy->getScalarTypeKind()) {
3885 case Type::STK_Pointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003886 if (Src.get()->isNullPointerConstant(S.Context,
3887 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003888 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003889 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003890 case Type::STK_Bool:
3891 return CK_IntegralToBoolean;
3892 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003893 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003894 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003895 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003896 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003897 Src = S.ImpCastExprToType(Src.take(),
3898 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003899 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003900 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003901 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003902 Src = S.ImpCastExprToType(Src.take(),
3903 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003904 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003905 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003906 case Type::STK_MemberPointer:
3907 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003908 }
3909 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003910
John McCalldaa8e4e2010-11-15 09:13:47 +00003911 case Type::STK_Floating:
3912 switch (DestTy->getScalarTypeKind()) {
3913 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003914 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003915 case Type::STK_Bool:
3916 return CK_FloatingToBoolean;
3917 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003918 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003919 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003920 Src = S.ImpCastExprToType(Src.take(),
3921 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003922 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003923 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003924 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003925 Src = S.ImpCastExprToType(Src.take(),
3926 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003927 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003928 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003929 case Type::STK_Pointer:
3930 llvm_unreachable("valid float->pointer cast?");
3931 case Type::STK_MemberPointer:
3932 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003933 }
3934 break;
3935
John McCalldaa8e4e2010-11-15 09:13:47 +00003936 case Type::STK_FloatingComplex:
3937 switch (DestTy->getScalarTypeKind()) {
3938 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003939 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003940 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003941 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003942 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003943 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003944 if (S.Context.hasSameType(ET, DestTy))
3945 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003946 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003947 return CK_FloatingCast;
3948 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003949 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003950 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003951 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003952 Src = S.ImpCastExprToType(Src.take(),
3953 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003954 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003955 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003956 case Type::STK_Pointer:
3957 llvm_unreachable("valid complex float->pointer cast?");
3958 case Type::STK_MemberPointer:
3959 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003960 }
3961 break;
3962
John McCalldaa8e4e2010-11-15 09:13:47 +00003963 case Type::STK_IntegralComplex:
3964 switch (DestTy->getScalarTypeKind()) {
3965 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003966 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003967 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003968 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003969 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003970 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003971 if (S.Context.hasSameType(ET, DestTy))
3972 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003973 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003974 return CK_IntegralCast;
3975 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003976 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003977 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003978 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003979 Src = S.ImpCastExprToType(Src.take(),
3980 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003981 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003982 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003983 case Type::STK_Pointer:
3984 llvm_unreachable("valid complex int->pointer cast?");
3985 case Type::STK_MemberPointer:
3986 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003987 }
3988 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003989 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003990
John McCallf3ea8cf2010-11-14 08:17:51 +00003991 llvm_unreachable("Unhandled scalar cast");
3992 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003993}
3994
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003995/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00003996ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3997 QualType castType, Expr *castExpr,
3998 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00003999 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00004000 if (castExpr->getType() == Context.UnknownAnyTy)
4001 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
4002
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004003 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004004 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00004005 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004006 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004007 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004008
John McCallfb8721c2011-04-10 19:13:55 +00004009 assert(!castExpr->getType()->isPlaceholderType());
4010
John McCallf89e55a2010-11-18 06:31:45 +00004011 // We only support r-value casts in C.
4012 VK = VK_RValue;
4013
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004014 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4015 // type needs to be scalar.
4016 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004017 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00004018 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4019 if (castExprRes.isInvalid())
4020 return ExprError();
4021 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004022
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004023 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004024 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00004025 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004026 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004027
John Wiegley429bb272011-04-08 18:41:53 +00004028 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4029 if (castExprRes.isInvalid())
4030 return ExprError();
4031 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004032
Eli Friedman8d438082010-07-17 20:43:49 +00004033 if (RequireCompleteType(TyR.getBegin(), castType,
4034 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004035 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004036
Anders Carlssonebeaf202009-10-16 02:35:04 +00004037 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004038 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004039 (castType->isStructureType() || castType->isUnionType())) {
4040 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004041 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004042 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4043 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004044 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00004045 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004046 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004047
Anders Carlssonc3516322009-10-16 02:48:28 +00004048 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004049 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004050 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004051 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004052 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004053 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004054 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004055 castExpr->getType()) &&
4056 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004057 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4058 << castExpr->getSourceRange();
4059 break;
4060 }
4061 }
John Wiegley429bb272011-04-08 18:41:53 +00004062 if (Field == FieldEnd) {
4063 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004064 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004065 return ExprError();
4066 }
John McCall2de56d12010-08-25 11:45:40 +00004067 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00004068 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004069 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004070
Anders Carlssonc3516322009-10-16 02:48:28 +00004071 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00004072 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00004073 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004074 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004075 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004076
John McCallf3ea8cf2010-11-14 08:17:51 +00004077 // The type we're casting to is known to be a scalar or vector.
4078
4079 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004080 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004081 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004082 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004083 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004084 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004085 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004086 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004087
4088 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004089 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004090
Anton Yartsevd06fea82011-03-27 09:32:40 +00004091 if (castType->isVectorType()) {
4092 if (castType->getAs<VectorType>()->getVectorKind() ==
4093 VectorType::AltiVecVector &&
4094 (castExpr->getType()->isIntegerType() ||
4095 castExpr->getType()->isFloatingType())) {
4096 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004097 return Owned(castExpr);
4098 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4099 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004100 } else
John Wiegley429bb272011-04-08 18:41:53 +00004101 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004102 }
John Wiegley429bb272011-04-08 18:41:53 +00004103 if (castExpr->getType()->isVectorType()) {
4104 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4105 return ExprError();
4106 else
4107 return Owned(castExpr);
4108 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004109
John McCallf3ea8cf2010-11-14 08:17:51 +00004110 // The source and target types are both scalars, i.e.
4111 // - arithmetic types (fundamental, enum, and complex)
4112 // - all kinds of pointers
4113 // Note that member pointers were filtered out with C++, above.
4114
John Wiegley429bb272011-04-08 18:41:53 +00004115 if (isa<ObjCSelectorExpr>(castExpr)) {
4116 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4117 return ExprError();
4118 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004119
John McCallf3ea8cf2010-11-14 08:17:51 +00004120 // If either type is a pointer, the other type has to be either an
4121 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004122 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004123 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004124 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004125 castExprType->isArithmeticType()) {
4126 Diag(castExpr->getLocStart(),
4127 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004128 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004129 return ExprError();
4130 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004131 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004132 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4133 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004134 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004135 return ExprError();
4136 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004137 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004138
John McCallf85e1932011-06-15 23:02:42 +00004139 if (getLangOptions().ObjCAutoRefCount) {
4140 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4141 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4142 castType, castExpr, CCK_CStyleCast);
4143
4144 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4145 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4146 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4147 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4148 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4149 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4150 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4151 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004152 diag::err_typecheck_incompatible_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004153 << castExprType << castType << AA_Casting
4154 << castExpr->getSourceRange();
4155
4156 return ExprError();
4157 }
4158 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004159 }
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004160 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4161 Diag(castExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004162 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004163 << castExprType << castType
4164 << castExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004165 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004166 }
4167 }
4168
John Wiegley429bb272011-04-08 18:41:53 +00004169 castExprRes = Owned(castExpr);
4170 Kind = PrepareScalarCast(*this, castExprRes, castType);
4171 if (castExprRes.isInvalid())
4172 return ExprError();
4173 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004174
John McCallf3ea8cf2010-11-14 08:17:51 +00004175 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004176 CheckCastAlign(castExpr, castType, TyR);
4177
John Wiegley429bb272011-04-08 18:41:53 +00004178 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004179}
4180
Anders Carlssonc3516322009-10-16 02:48:28 +00004181bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004182 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004183 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004184
Anders Carlssona64db8f2007-11-27 05:51:55 +00004185 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004186 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004187 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004188 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004189 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004190 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004191 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004192 } else
4193 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004194 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004195 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196
John McCall2de56d12010-08-25 11:45:40 +00004197 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004198 return false;
4199}
4200
John Wiegley429bb272011-04-08 18:41:53 +00004201ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4202 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004203 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004204
Anders Carlsson16a89042009-10-16 05:23:41 +00004205 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004206
Nate Begeman9b10da62009-06-27 22:05:55 +00004207 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4208 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004209 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004210 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4211 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004212 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004213 return ExprError();
4214 }
John McCall2de56d12010-08-25 11:45:40 +00004215 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004216 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004217 }
4218
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004219 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004220 // conversion will take place first from scalar to elt type, and then
4221 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004222 if (SrcTy->isPointerType())
4223 return Diag(R.getBegin(),
4224 diag::err_invalid_conversion_between_vector_and_scalar)
4225 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004226
4227 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004228 ExprResult CastExprRes = Owned(CastExpr);
4229 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4230 if (CastExprRes.isInvalid())
4231 return ExprError();
4232 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004233
John McCall2de56d12010-08-25 11:45:40 +00004234 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004235 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004236}
4237
John McCall60d7b3a2010-08-24 06:29:42 +00004238ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004239Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4240 Declarator &D, ParsedType &Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004241 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004242 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004243 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004244
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004245 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4246 if (D.isInvalidType())
4247 return ExprError();
4248
4249 if (getLangOptions().CPlusPlus) {
4250 // Check that there are no default arguments (C++ only).
4251 CheckExtraCXXDefaultArguments(D);
4252 }
4253
4254 QualType castType = castTInfo->getType();
4255 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004257 bool isVectorLiteral = false;
4258
4259 // Check for an altivec or OpenCL literal,
4260 // i.e. all the elements are integer constants.
4261 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4262 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4263 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4264 if (PLE && PLE->getNumExprs() == 0) {
4265 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4266 return ExprError();
4267 }
4268 if (PE || PLE->getNumExprs() == 1) {
4269 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4270 if (!E->getType()->isVectorType())
4271 isVectorLiteral = true;
4272 }
4273 else
4274 isVectorLiteral = true;
4275 }
4276
4277 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4278 // then handle it as such.
4279 if (isVectorLiteral)
4280 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4281
Nate Begeman2ef13e52009-08-10 23:49:36 +00004282 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004283 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4284 // sequence of BinOp comma operators.
4285 if (isa<ParenListExpr>(castExpr)) {
4286 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4287 if (Result.isInvalid()) return ExprError();
4288 castExpr = Result.take();
4289 }
John McCallb042fdf2010-01-15 18:56:44 +00004290
John McCall9ae2f072010-08-23 23:25:46 +00004291 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004292}
4293
John McCall60d7b3a2010-08-24 06:29:42 +00004294ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004295Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004296 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004297 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004298 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004299 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004300 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004301 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4302 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004303 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004304 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004305 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004306
Richard Trieu67e29332011-08-02 04:35:43 +00004307 return Owned(CStyleCastExpr::Create(
4308 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4309 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004310}
4311
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004312ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4313 SourceLocation RParenLoc, Expr *E,
4314 TypeSourceInfo *TInfo) {
4315 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4316 "Expected paren or paren list expression");
4317
4318 Expr **exprs;
4319 unsigned numExprs;
4320 Expr *subExpr;
4321 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4322 exprs = PE->getExprs();
4323 numExprs = PE->getNumExprs();
4324 } else {
4325 subExpr = cast<ParenExpr>(E)->getSubExpr();
4326 exprs = &subExpr;
4327 numExprs = 1;
4328 }
4329
4330 QualType Ty = TInfo->getType();
4331 assert(Ty->isVectorType() && "Expected vector type");
4332
Chris Lattner5f9e2722011-07-23 10:55:15 +00004333 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004334 const VectorType *VTy = Ty->getAs<VectorType>();
4335 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4336
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004337 // '(...)' form of vector initialization in AltiVec: the number of
4338 // initializers must be one or must match the size of the vector.
4339 // If a single value is specified in the initializer then it will be
4340 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004341 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004342 // The number of initializers must be one or must match the size of the
4343 // vector. If a single value is specified in the initializer then it will
4344 // be replicated to all the components of the vector
4345 if (numExprs == 1) {
4346 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4347 ExprResult Literal = Owned(exprs[0]);
4348 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4349 PrepareScalarCast(*this, Literal, ElemTy));
4350 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4351 }
4352 else if (numExprs < numElems) {
4353 Diag(E->getExprLoc(),
4354 diag::err_incorrect_number_of_vector_initializers);
4355 return ExprError();
4356 }
4357 else
4358 for (unsigned i = 0, e = numExprs; i != e; ++i)
4359 initExprs.push_back(exprs[i]);
4360 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004361 else {
4362 // For OpenCL, when the number of initializers is a single value,
4363 // it will be replicated to all components of the vector.
4364 if (getLangOptions().OpenCL &&
4365 VTy->getVectorKind() == VectorType::GenericVector &&
4366 numExprs == 1) {
4367 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4368 ExprResult Literal = Owned(exprs[0]);
4369 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4370 PrepareScalarCast(*this, Literal, ElemTy));
4371 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4372 }
4373
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004374 for (unsigned i = 0, e = numExprs; i != e; ++i)
4375 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004376 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004377 // FIXME: This means that pretty-printing the final AST will produce curly
4378 // braces instead of the original commas.
4379 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4380 &initExprs[0],
4381 initExprs.size(), RParenLoc);
4382 initE->setType(Ty);
4383 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4384}
4385
Nate Begeman2ef13e52009-08-10 23:49:36 +00004386/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4387/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004388ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004389Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004390 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4391 if (!E)
4392 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004393
John McCall60d7b3a2010-08-24 06:29:42 +00004394 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004395
Nate Begeman2ef13e52009-08-10 23:49:36 +00004396 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004397 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4398 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004399
John McCall9ae2f072010-08-23 23:25:46 +00004400 if (Result.isInvalid()) return ExprError();
4401
4402 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004403}
4404
John McCall60d7b3a2010-08-24 06:29:42 +00004405ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004406 SourceLocation R,
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004407 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004408 unsigned nexprs = Val.size();
4409 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004410 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4411 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004412 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004413 expr = new (Context) ParenExpr(L, R, exprs[0]);
4414 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004415 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4416 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004417 return Owned(expr);
4418}
4419
Chandler Carruth82214a82011-02-18 23:54:50 +00004420/// \brief Emit a specialized diagnostic when one expression is a null pointer
4421/// constant and the other is not a pointer.
4422bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4423 SourceLocation QuestionLoc) {
4424 Expr *NullExpr = LHS;
4425 Expr *NonPointerExpr = RHS;
4426 Expr::NullPointerConstantKind NullKind =
4427 NullExpr->isNullPointerConstant(Context,
4428 Expr::NPC_ValueDependentIsNotNull);
4429
4430 if (NullKind == Expr::NPCK_NotNull) {
4431 NullExpr = RHS;
4432 NonPointerExpr = LHS;
4433 NullKind =
4434 NullExpr->isNullPointerConstant(Context,
4435 Expr::NPC_ValueDependentIsNotNull);
4436 }
4437
4438 if (NullKind == Expr::NPCK_NotNull)
4439 return false;
4440
4441 if (NullKind == Expr::NPCK_ZeroInteger) {
4442 // In this case, check to make sure that we got here from a "NULL"
4443 // string in the source code.
4444 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004445 SourceLocation loc = NullExpr->getExprLoc();
4446 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004447 return false;
4448 }
4449
4450 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4451 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4452 << NonPointerExpr->getType() << DiagType
4453 << NonPointerExpr->getSourceRange();
4454 return true;
4455}
4456
Sebastian Redl28507842009-02-26 14:39:58 +00004457/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4458/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004459/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004460QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4461 ExprResult &RHS, ExprValueKind &VK,
4462 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004463 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004464
John McCallfb8721c2011-04-10 19:13:55 +00004465 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004466 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004467 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004468
John McCallfb8721c2011-04-10 19:13:55 +00004469 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004470 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004471 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004472
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004473 // C++ is sufficiently different to merit its own checker.
4474 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004475 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004476
4477 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004478 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004479
John Wiegley429bb272011-04-08 18:41:53 +00004480 Cond = UsualUnaryConversions(Cond.take());
4481 if (Cond.isInvalid())
4482 return QualType();
4483 LHS = UsualUnaryConversions(LHS.take());
4484 if (LHS.isInvalid())
4485 return QualType();
4486 RHS = UsualUnaryConversions(RHS.take());
4487 if (RHS.isInvalid())
4488 return QualType();
4489
4490 QualType CondTy = Cond.get()->getType();
4491 QualType LHSTy = LHS.get()->getType();
4492 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004493
Reid Spencer5f016e22007-07-11 17:01:13 +00004494 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004495 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00004496 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4497 // Throw an error if its not either.
4498 if (getLangOptions().OpenCL) {
4499 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004500 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00004501 diag::err_typecheck_cond_expect_scalar_or_vector)
4502 << CondTy;
4503 return QualType();
4504 }
4505 }
4506 else {
John Wiegley429bb272011-04-08 18:41:53 +00004507 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004508 << CondTy;
4509 return QualType();
4510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004511 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004512
Chris Lattner70d67a92008-01-06 22:42:25 +00004513 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004514 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004515 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004516
Nate Begeman6155d732010-09-20 22:41:17 +00004517 // OpenCL: If the condition is a vector, and both operands are scalar,
4518 // attempt to implicity convert them to the vector type to act like the
4519 // built in select.
4520 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4521 // Both operands should be of scalar type.
4522 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004523 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004524 << CondTy;
4525 return QualType();
4526 }
4527 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004528 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004529 << CondTy;
4530 return QualType();
4531 }
4532 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00004533 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4534 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00004535 }
4536
Chris Lattner70d67a92008-01-06 22:42:25 +00004537 // If both operands have arithmetic type, do the usual arithmetic conversions
4538 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004539 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4540 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004541 if (LHS.isInvalid() || RHS.isInvalid())
4542 return QualType();
4543 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004544 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004545
Chris Lattner70d67a92008-01-06 22:42:25 +00004546 // If both operands are the same structure or union type, the result is that
4547 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004548 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4549 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004550 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004551 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004552 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004553 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004554 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004555 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004556
Chris Lattner70d67a92008-01-06 22:42:25 +00004557 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004558 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004559 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4560 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004561 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4562 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004563 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004564 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4565 << LHS.get()->getSourceRange();
4566 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4567 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004568 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004569 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004570 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4571 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004572 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004573 RHS.get()->isNullPointerConstant(Context,
4574 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004575 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00004576 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004577 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004578 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004579 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004580 LHS.get()->isNullPointerConstant(Context,
4581 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00004582 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004583 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004584 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004585
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004586 // All objective-c pointer type analysis is done here.
4587 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4588 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004589 if (LHS.isInvalid() || RHS.isInvalid())
4590 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004591 if (!compositeType.isNull())
4592 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004593
4594
Steve Naroff7154a772009-07-01 14:36:47 +00004595 // Handle block pointer types.
4596 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4597 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4598 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4599 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004600 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4601 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004602 return destType;
4603 }
4604 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004605 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4606 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004607 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004608 }
Steve Naroff7154a772009-07-01 14:36:47 +00004609 // We have 2 block pointer types.
4610 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4611 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004612 return LHSTy;
4613 }
Steve Naroff7154a772009-07-01 14:36:47 +00004614 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004615 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4616 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004617
Steve Naroff7154a772009-07-01 14:36:47 +00004618 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4619 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004620 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004621 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4622 << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004623 // In this situation, we assume void* type. No especially good
4624 // reason, but this is what gcc does, and we do have to pick
4625 // to get a consistent AST.
4626 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004627 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4628 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004629 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004630 }
Steve Naroff7154a772009-07-01 14:36:47 +00004631 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004632 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4633 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004634 return LHSTy;
4635 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004636
Steve Naroff7154a772009-07-01 14:36:47 +00004637 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4638 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4639 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004640 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4641 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004642
4643 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4644 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4645 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004646 QualType destPointee
4647 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004648 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004649 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004650 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004651 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004652 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004653 return destType;
4654 }
4655 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004656 QualType destPointee
4657 = Context.getQualifiedType(rhptee, lhptee.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 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004661 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004662 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004663 return destType;
4664 }
4665
4666 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4667 // Two identical pointer types are always compatible.
4668 return LHSTy;
4669 }
4670 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4671 rhptee.getUnqualifiedType())) {
4672 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004673 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4674 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004675 // In this situation, we assume void* type. No especially good
4676 // reason, but this is what gcc does, and we do have to pick
4677 // to get a consistent AST.
4678 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004679 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4680 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004681 return incompatTy;
4682 }
4683 // The pointer types are compatible.
4684 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4685 // differently qualified versions of compatible types, the result type is
4686 // a pointer to an appropriately qualified version of the *composite*
4687 // type.
4688 // FIXME: Need to calculate the composite type.
4689 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00004690 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4691 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004692 return LHSTy;
4693 }
Mike Stump1eb44332009-09-09 15:08:12 +00004694
John McCall404cd162010-11-13 01:35:44 +00004695 // GCC compatibility: soften pointer/integer mismatch. Note that
4696 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00004697 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4698 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004699 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4700 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004701 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004702 return RHSTy;
4703 }
4704 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4705 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004706 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4707 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004708 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004709 return LHSTy;
4710 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004711
Chandler Carruth82214a82011-02-18 23:54:50 +00004712 // Emit a better diagnostic if one of the expressions is a null pointer
4713 // constant and the other is not a pointer type. In this case, the user most
4714 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004715 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004716 return QualType();
4717
Chris Lattner70d67a92008-01-06 22:42:25 +00004718 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004719 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004720 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4721 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004722 return QualType();
4723}
4724
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004725/// FindCompositeObjCPointerType - Helper method to find composite type of
4726/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004727QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004728 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004729 QualType LHSTy = LHS.get()->getType();
4730 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004731
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004732 // Handle things like Class and struct objc_class*. Here we case the result
4733 // to the pseudo-builtin, because that will be implicitly cast back to the
4734 // redefinition type if an attempt is made to access its fields.
4735 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004736 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004737 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004738 return LHSTy;
4739 }
4740 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004741 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004742 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004743 return RHSTy;
4744 }
4745 // And the same for struct objc_object* / id
4746 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004747 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004748 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004749 return LHSTy;
4750 }
4751 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004752 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004753 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004754 return RHSTy;
4755 }
4756 // And the same for struct objc_selector* / SEL
4757 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004758 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004759 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004760 return LHSTy;
4761 }
4762 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004763 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004764 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004765 return RHSTy;
4766 }
4767 // Check constraints for Objective-C object pointers types.
4768 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004769
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004770 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4771 // Two identical object pointer types are always compatible.
4772 return LHSTy;
4773 }
4774 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4775 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4776 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004777
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004778 // If both operands are interfaces and either operand can be
4779 // assigned to the other, use that type as the composite
4780 // type. This allows
4781 // xxx ? (A*) a : (B*) b
4782 // where B is a subclass of A.
4783 //
4784 // Additionally, as for assignment, if either type is 'id'
4785 // allow silent coercion. Finally, if the types are
4786 // incompatible then make sure to use 'id' as the composite
4787 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004788
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004789 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4790 // It could return the composite type.
4791 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4792 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4793 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4794 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4795 } else if ((LHSTy->isObjCQualifiedIdType() ||
4796 RHSTy->isObjCQualifiedIdType()) &&
4797 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4798 // Need to handle "id<xx>" explicitly.
4799 // GCC allows qualified id and any Objective-C type to devolve to
4800 // id. Currently localizing to here until clear this should be
4801 // part of ObjCQualifiedIdTypesAreCompatible.
4802 compositeType = Context.getObjCIdType();
4803 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4804 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004805 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004806 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4807 ;
4808 else {
4809 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4810 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004811 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004812 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004813 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4814 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004815 return incompatTy;
4816 }
4817 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004818 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4819 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004820 return compositeType;
4821 }
4822 // Check Objective-C object pointer types and 'void *'
4823 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4824 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4825 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4826 QualType destPointee
4827 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4828 QualType destType = Context.getPointerType(destPointee);
4829 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004830 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004831 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004832 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004833 return destType;
4834 }
4835 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4836 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4837 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4838 QualType destPointee
4839 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4840 QualType destType = Context.getPointerType(destPointee);
4841 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004842 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004843 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004844 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004845 return destType;
4846 }
4847 return QualType();
4848}
4849
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004850/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004851/// ParenRange in parentheses.
4852static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004853 const PartialDiagnostic &Note,
4854 SourceRange ParenRange) {
4855 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4856 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4857 EndLoc.isValid()) {
4858 Self.Diag(Loc, Note)
4859 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4860 << FixItHint::CreateInsertion(EndLoc, ")");
4861 } else {
4862 // We can't display the parentheses, so just show the bare note.
4863 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004864 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004865}
4866
4867static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4868 return Opc >= BO_Mul && Opc <= BO_Shr;
4869}
4870
Hans Wennborg2f072b42011-06-09 17:06:51 +00004871/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4872/// expression, either using a built-in or overloaded operator,
4873/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4874static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4875 Expr **RHS) {
4876 E = E->IgnoreParenImpCasts();
4877 E = E->IgnoreConversionOperator();
4878 E = E->IgnoreParenImpCasts();
4879
4880 // Built-in binary operator.
4881 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4882 if (IsArithmeticOp(OP->getOpcode())) {
4883 *Opcode = OP->getOpcode();
4884 *RHS = OP->getRHS();
4885 return true;
4886 }
4887 }
4888
4889 // Overloaded operator.
4890 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4891 if (Call->getNumArgs() != 2)
4892 return false;
4893
4894 // Make sure this is really a binary operator that is safe to pass into
4895 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4896 OverloadedOperatorKind OO = Call->getOperator();
4897 if (OO < OO_Plus || OO > OO_Arrow)
4898 return false;
4899
4900 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4901 if (IsArithmeticOp(OpKind)) {
4902 *Opcode = OpKind;
4903 *RHS = Call->getArg(1);
4904 return true;
4905 }
4906 }
4907
4908 return false;
4909}
4910
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004911static bool IsLogicOp(BinaryOperatorKind Opc) {
4912 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4913}
4914
Hans Wennborg2f072b42011-06-09 17:06:51 +00004915/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4916/// or is a logical expression such as (x==y) which has int type, but is
4917/// commonly interpreted as boolean.
4918static bool ExprLooksBoolean(Expr *E) {
4919 E = E->IgnoreParenImpCasts();
4920
4921 if (E->getType()->isBooleanType())
4922 return true;
4923 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4924 return IsLogicOp(OP->getOpcode());
4925 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4926 return OP->getOpcode() == UO_LNot;
4927
4928 return false;
4929}
4930
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004931/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4932/// and binary operator are mixed in a way that suggests the programmer assumed
4933/// the conditional operator has higher precedence, for example:
4934/// "int x = a + someBinaryCondition ? 1 : 2".
4935static void DiagnoseConditionalPrecedence(Sema &Self,
4936 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004937 Expr *Condition,
4938 Expr *LHS,
4939 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004940 BinaryOperatorKind CondOpcode;
4941 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004942
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004943 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004944 return;
4945 if (!ExprLooksBoolean(CondRHS))
4946 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004947
Hans Wennborg2f072b42011-06-09 17:06:51 +00004948 // The condition is an arithmetic binary expression, with a right-
4949 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004950
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004951 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004952 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004953 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004954
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004955 SuggestParentheses(Self, OpLoc,
4956 Self.PDiag(diag::note_precedence_conditional_silence)
4957 << BinaryOperator::getOpcodeStr(CondOpcode),
4958 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004959
4960 SuggestParentheses(Self, OpLoc,
4961 Self.PDiag(diag::note_precedence_conditional_first),
4962 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004963}
4964
Steve Narofff69936d2007-09-16 03:34:24 +00004965/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004966/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004967ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004968 SourceLocation ColonLoc,
4969 Expr *CondExpr, Expr *LHSExpr,
4970 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004971 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4972 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004973 OpaqueValueExpr *opaqueValue = 0;
4974 Expr *commonExpr = 0;
4975 if (LHSExpr == 0) {
4976 commonExpr = CondExpr;
4977
4978 // We usually want to apply unary conversions *before* saving, except
4979 // in the special case of a C++ l-value conditional.
4980 if (!(getLangOptions().CPlusPlus
4981 && !commonExpr->isTypeDependent()
4982 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4983 && commonExpr->isGLValue()
4984 && commonExpr->isOrdinaryOrBitFieldObject()
4985 && RHSExpr->isOrdinaryOrBitFieldObject()
4986 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004987 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4988 if (commonRes.isInvalid())
4989 return ExprError();
4990 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00004991 }
4992
4993 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4994 commonExpr->getType(),
4995 commonExpr->getValueKind(),
4996 commonExpr->getObjectKind());
4997 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004998 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004999
John McCallf89e55a2010-11-18 06:31:45 +00005000 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005001 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005002 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5003 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005004 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005005 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5006 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005007 return ExprError();
5008
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005009 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5010 RHS.get());
5011
John McCall56ca35d2011-02-17 10:25:35 +00005012 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005013 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5014 LHS.take(), ColonLoc,
5015 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005016
5017 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005018 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005019 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5020 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005021}
5022
John McCalle4be87e2011-01-31 23:13:11 +00005023// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005024// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005025// routine is it effectively iqnores the qualifiers on the top level pointee.
5026// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5027// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005028static Sema::AssignConvertType
5029checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5030 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5031 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005032
Reid Spencer5f016e22007-07-11 17:01:13 +00005033 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005034 const Type *lhptee, *rhptee;
5035 Qualifiers lhq, rhq;
5036 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5037 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005038
John McCalle4be87e2011-01-31 23:13:11 +00005039 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005040
5041 // C99 6.5.16.1p1: This following citation is common to constraints
5042 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5043 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005044 Qualifiers lq;
5045
John McCallf85e1932011-06-15 23:02:42 +00005046 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5047 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5048 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5049 // Ignore lifetime for further calculation.
5050 lhq.removeObjCLifetime();
5051 rhq.removeObjCLifetime();
5052 }
5053
John McCall86c05f32011-02-01 00:10:29 +00005054 if (!lhq.compatiblyIncludes(rhq)) {
5055 // Treat address-space mismatches as fatal. TODO: address subspaces
5056 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5057 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5058
John McCallf85e1932011-06-15 23:02:42 +00005059 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005060 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005061 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5062 .compatiblyIncludes(
5063 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005064 && (lhptee->isVoidType() || rhptee->isVoidType()))
5065 ; // keep old
5066
John McCallf85e1932011-06-15 23:02:42 +00005067 // Treat lifetime mismatches as fatal.
5068 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5069 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5070
John McCall86c05f32011-02-01 00:10:29 +00005071 // For GCC compatibility, other qualifier mismatches are treated
5072 // as still compatible in C.
5073 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5074 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005075
Mike Stumpeed9cac2009-02-19 03:04:26 +00005076 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5077 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005078 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005079 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005080 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005081 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005082
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005083 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005084 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005085 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005086 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005087
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005088 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005089 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005090 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005091
5092 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005093 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005094 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005095 }
John McCall86c05f32011-02-01 00:10:29 +00005096
Mike Stumpeed9cac2009-02-19 03:04:26 +00005097 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005098 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005099 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5100 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005101 // Check if the pointee types are compatible ignoring the sign.
5102 // We explicitly check for char so that we catch "char" vs
5103 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005104 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005105 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005106 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005107 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005108
Chris Lattner6a2b9262009-10-17 20:33:28 +00005109 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005110 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005111 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005112 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005113
John McCall86c05f32011-02-01 00:10:29 +00005114 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005115 // Types are compatible ignoring the sign. Qualifier incompatibility
5116 // takes priority over sign incompatibility because the sign
5117 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005118 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005119 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005120
John McCalle4be87e2011-01-31 23:13:11 +00005121 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005122 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005123
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005124 // If we are a multi-level pointer, it's possible that our issue is simply
5125 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5126 // the eventual target type is the same and the pointers have the same
5127 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005128 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005129 do {
John McCall86c05f32011-02-01 00:10:29 +00005130 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5131 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005132 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005133
John McCall86c05f32011-02-01 00:10:29 +00005134 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005135 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005136 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005137
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005138 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005139 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005140 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005141 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005142}
5143
John McCalle4be87e2011-01-31 23:13:11 +00005144/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005145/// block pointer types are compatible or whether a block and normal pointer
5146/// are compatible. It is more restrict than comparing two function pointer
5147// types.
John McCalle4be87e2011-01-31 23:13:11 +00005148static Sema::AssignConvertType
5149checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5150 QualType rhsType) {
5151 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5152 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5153
Steve Naroff1c7d0672008-09-04 15:10:53 +00005154 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005155
Steve Naroff1c7d0672008-09-04 15:10:53 +00005156 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005157 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5158 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005159
John McCalle4be87e2011-01-31 23:13:11 +00005160 // In C++, the types have to match exactly.
5161 if (S.getLangOptions().CPlusPlus)
5162 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005163
John McCalle4be87e2011-01-31 23:13:11 +00005164 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005165
Steve Naroff1c7d0672008-09-04 15:10:53 +00005166 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005167 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5168 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005169
John McCalle4be87e2011-01-31 23:13:11 +00005170 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5171 return Sema::IncompatibleBlockPointer;
5172
Steve Naroff1c7d0672008-09-04 15:10:53 +00005173 return ConvTy;
5174}
5175
John McCalle4be87e2011-01-31 23:13:11 +00005176/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005177/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005178static Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005179checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5180 QualType rhsType) {
John McCalle4be87e2011-01-31 23:13:11 +00005181 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5182 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5183
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005184 if (lhsType->isObjCBuiltinType()) {
5185 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005186 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5187 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005188 return Sema::IncompatiblePointer;
5189 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005190 }
5191 if (rhsType->isObjCBuiltinType()) {
5192 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005193 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5194 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005195 return Sema::IncompatiblePointer;
5196 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005197 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005198 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005199 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005200 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005201 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005202
John McCalle4be87e2011-01-31 23:13:11 +00005203 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5204 return Sema::CompatiblePointerDiscardsQualifiers;
5205
5206 if (S.Context.typesAreCompatible(lhsType, rhsType))
5207 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005208 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005209 return Sema::IncompatibleObjCQualifiedId;
5210 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005211}
5212
John McCall1c23e912010-11-16 02:32:08 +00005213Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005214Sema::CheckAssignmentConstraints(SourceLocation Loc,
5215 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005216 // Fake up an opaque expression. We don't actually care about what
5217 // cast operations are required, so if CheckAssignmentConstraints
5218 // adds casts to this they'll be wasted, but fortunately that doesn't
5219 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005220 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005221 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005222 CastKind K = CK_Invalid;
5223
5224 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5225}
5226
Mike Stumpeed9cac2009-02-19 03:04:26 +00005227/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5228/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005229/// pointers. Here are some objectionable examples that GCC considers warnings:
5230///
5231/// int a, *pint;
5232/// short *pshort;
5233/// struct foo *pfoo;
5234///
5235/// pint = pshort; // warning: assignment from incompatible pointer type
5236/// a = pint; // warning: assignment makes integer from pointer without a cast
5237/// pint = a; // warning: assignment makes pointer from integer without a cast
5238/// pint = pfoo; // warning: assignment from incompatible pointer type
5239///
5240/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005241/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005242///
John McCalldaa8e4e2010-11-15 09:13:47 +00005243/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005244Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005245Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005246 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005247 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005248 QualType origLhsType = lhsType;
John McCall1c23e912010-11-16 02:32:08 +00005249
Chris Lattnerfc144e22008-01-04 23:18:45 +00005250 // Get canonical types. We're not formatting these types, just comparing
5251 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005252 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5253 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005254
John McCallb6cfa242011-01-31 22:28:28 +00005255 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005256 if (lhsType == rhsType) {
5257 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005258 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005259 }
5260
Douglas Gregor9d293df2008-10-28 00:22:11 +00005261 // If the left-hand side is a reference type, then we are in a
5262 // (rare!) case where we've allowed the use of references in C,
5263 // e.g., as a parameter type in a built-in function. In this case,
5264 // just make sure that the type referenced is compatible with the
5265 // right-hand side type. The caller is responsible for adjusting
5266 // lhsType so that the resulting expression does not have reference
5267 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005268 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005269 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5270 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005271 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005272 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005273 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005274 }
John McCallb6cfa242011-01-31 22:28:28 +00005275
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005276 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5277 // to the same ExtVector type.
5278 if (lhsType->isExtVectorType()) {
5279 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005280 return Incompatible;
5281 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005282 // CK_VectorSplat does T -> vector T, so first cast to the
5283 // element type.
5284 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5285 if (elType != rhsType) {
5286 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005287 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005288 }
5289 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005290 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005291 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005292 }
Mike Stump1eb44332009-09-09 15:08:12 +00005293
John McCallb6cfa242011-01-31 22:28:28 +00005294 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005295 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005296 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005297 // Allow assignments of an AltiVec vector type to an equivalent GCC
5298 // vector type and vice versa
5299 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5300 Kind = CK_BitCast;
5301 return Compatible;
5302 }
5303
Douglas Gregor255210e2010-08-06 10:14:59 +00005304 // If we are allowing lax vector conversions, and LHS and RHS are both
5305 // vectors, the total size only needs to be the same. This is a bitcast;
5306 // no bits are changed but the result type is different.
5307 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005308 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005309 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005310 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005311 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005312 }
5313 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005314 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005315
John McCallb6cfa242011-01-31 22:28:28 +00005316 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005317 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005318 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005319 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005320 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005321 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005322
John McCallb6cfa242011-01-31 22:28:28 +00005323 // Conversions to normal pointers.
5324 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5325 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005326 if (isa<PointerType>(rhsType)) {
5327 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005328 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005329 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005330
John McCallb6cfa242011-01-31 22:28:28 +00005331 // int -> T*
5332 if (rhsType->isIntegerType()) {
5333 Kind = CK_IntegralToPointer; // FIXME: null?
5334 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005335 }
John McCallb6cfa242011-01-31 22:28:28 +00005336
5337 // C pointers are not compatible with ObjC object pointers,
5338 // with two exceptions:
5339 if (isa<ObjCObjectPointerType>(rhsType)) {
5340 // - conversions to void*
5341 if (lhsPointer->getPointeeType()->isVoidType()) {
5342 Kind = CK_AnyPointerToObjCPointerCast;
5343 return Compatible;
5344 }
5345
5346 // - conversions from 'Class' to the redefinition type
5347 if (rhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005348 Context.hasSameType(lhsType,
5349 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005350 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005351 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005352 }
Steve Naroffb4406862008-09-29 18:10:17 +00005353
John McCallb6cfa242011-01-31 22:28:28 +00005354 Kind = CK_BitCast;
5355 return IncompatiblePointer;
5356 }
5357
5358 // U^ -> void*
5359 if (rhsType->getAs<BlockPointerType>()) {
5360 if (lhsPointer->getPointeeType()->isVoidType()) {
5361 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005362 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005363 }
Steve Naroffb4406862008-09-29 18:10:17 +00005364 }
John McCallb6cfa242011-01-31 22:28:28 +00005365
Steve Naroff1c7d0672008-09-04 15:10:53 +00005366 return Incompatible;
5367 }
5368
John McCallb6cfa242011-01-31 22:28:28 +00005369 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005370 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005371 // U^ -> T^
5372 if (rhsType->isBlockPointerType()) {
5373 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005374 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005375 }
5376
5377 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005378 if (rhsType->isIntegerType()) {
5379 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005380 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005381 }
5382
John McCallb6cfa242011-01-31 22:28:28 +00005383 // id -> T^
5384 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5385 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005386 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005387 }
Steve Naroffb4406862008-09-29 18:10:17 +00005388
John McCallb6cfa242011-01-31 22:28:28 +00005389 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005390 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005391 if (RHSPT->getPointeeType()->isVoidType()) {
5392 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005393 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005394 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005395
Chris Lattnerfc144e22008-01-04 23:18:45 +00005396 return Incompatible;
5397 }
5398
John McCallb6cfa242011-01-31 22:28:28 +00005399 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005400 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005401 // A* -> B*
5402 if (rhsType->isObjCObjectPointerType()) {
5403 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005404 Sema::AssignConvertType result =
5405 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5406 if (getLangOptions().ObjCAutoRefCount &&
5407 result == Compatible &&
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005408 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5409 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005410 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005411 }
5412
5413 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005414 if (rhsType->isIntegerType()) {
5415 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005416 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005417 }
5418
John McCallb6cfa242011-01-31 22:28:28 +00005419 // In general, C pointers are not compatible with ObjC object pointers,
5420 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005421 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005422 // - conversions from 'void*'
5423 if (rhsType->isVoidPointerType()) {
5424 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005425 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005426 }
5427
5428 // - conversions to 'Class' from its redefinition type
5429 if (lhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005430 Context.hasSameType(rhsType,
5431 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005432 Kind = CK_BitCast;
5433 return Compatible;
5434 }
5435
5436 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005437 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005438 }
John McCallb6cfa242011-01-31 22:28:28 +00005439
5440 // T^ -> A*
5441 if (rhsType->isBlockPointerType()) {
5442 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005443 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005444 }
5445
Steve Naroff14108da2009-07-10 23:34:53 +00005446 return Incompatible;
5447 }
John McCallb6cfa242011-01-31 22:28:28 +00005448
5449 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005450 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005451 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005452 if (lhsType == Context.BoolTy) {
5453 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005454 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005455 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005456
John McCallb6cfa242011-01-31 22:28:28 +00005457 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005458 if (lhsType->isIntegerType()) {
5459 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005460 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005461 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005462
Chris Lattnerfc144e22008-01-04 23:18:45 +00005463 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005464 }
John McCallb6cfa242011-01-31 22:28:28 +00005465
5466 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005467 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005468 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005469 if (lhsType == Context.BoolTy) {
5470 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005471 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005472 }
Steve Naroff14108da2009-07-10 23:34:53 +00005473
John McCallb6cfa242011-01-31 22:28:28 +00005474 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005475 if (lhsType->isIntegerType()) {
5476 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005477 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005478 }
5479
Steve Naroff14108da2009-07-10 23:34:53 +00005480 return Incompatible;
5481 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005482
John McCallb6cfa242011-01-31 22:28:28 +00005483 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005484 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005485 if (Context.typesAreCompatible(lhsType, rhsType)) {
5486 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005487 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005488 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005489 }
John McCallb6cfa242011-01-31 22:28:28 +00005490
Reid Spencer5f016e22007-07-11 17:01:13 +00005491 return Incompatible;
5492}
5493
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005494/// \brief Constructs a transparent union from an expression that is
5495/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005496static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5497 ExprResult &EResult, QualType UnionType,
5498 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005499 // Build an initializer list that designates the appropriate member
5500 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005501 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005502 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005503 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005504 SourceLocation());
5505 Initializer->setType(UnionType);
5506 Initializer->setInitializedFieldInUnion(Field);
5507
5508 // Build a compound literal constructing a value of the transparent
5509 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005510 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005511 EResult = S.Owned(
5512 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5513 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005514}
5515
5516Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005517Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5518 ExprResult &rExpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005519 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005520
Mike Stump1eb44332009-09-09 15:08:12 +00005521 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005522 // transparent_union GCC extension.
5523 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005524 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005525 return Incompatible;
5526
5527 // The field to initialize within the transparent union.
5528 RecordDecl *UD = UT->getDecl();
5529 FieldDecl *InitField = 0;
5530 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005531 for (RecordDecl::field_iterator it = UD->field_begin(),
5532 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005533 it != itend; ++it) {
5534 if (it->getType()->isPointerType()) {
5535 // If the transparent union contains a pointer type, we allow:
5536 // 1) void pointer
5537 // 2) null pointer constant
5538 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005539 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005540 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005541 InitField = *it;
5542 break;
5543 }
Mike Stump1eb44332009-09-09 15:08:12 +00005544
John Wiegley429bb272011-04-08 18:41:53 +00005545 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005546 Expr::NPC_ValueDependentIsNull)) {
Richard Trieu67e29332011-08-02 04:35:43 +00005547 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5548 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005549 InitField = *it;
5550 break;
5551 }
5552 }
5553
John McCalldaa8e4e2010-11-15 09:13:47 +00005554 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005555 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005556 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005557 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005558 InitField = *it;
5559 break;
5560 }
5561 }
5562
5563 if (!InitField)
5564 return Incompatible;
5565
John Wiegley429bb272011-04-08 18:41:53 +00005566 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005567 return Compatible;
5568}
5569
Chris Lattner5cf216b2008-01-04 18:04:52 +00005570Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005571Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005572 if (getLangOptions().CPlusPlus) {
5573 if (!lhsType->isRecordType()) {
5574 // C++ 5.17p3: If the left operand is not of class type, the
5575 // expression is implicitly converted (C++ 4) to the
5576 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005577 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5578 lhsType.getUnqualifiedType(),
5579 AA_Assigning);
5580 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005581 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005582 Sema::AssignConvertType result = Compatible;
5583 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieu67e29332011-08-02 04:35:43 +00005584 !CheckObjCARCUnavailableWeakConversion(lhsType,
5585 rExpr.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005586 result = IncompatibleObjCWeakRef;
John Wiegley429bb272011-04-08 18:41:53 +00005587 rExpr = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005588 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005589 }
5590
5591 // FIXME: Currently, we fall through and treat C++ classes like C
5592 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005593 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005594
Steve Naroff529a4ad2007-11-27 17:58:44 +00005595 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5596 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005597 if ((lhsType->isPointerType() ||
5598 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005599 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005600 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005601 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005602 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005603 return Compatible;
5604 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005605
Chris Lattner943140e2007-10-16 02:55:40 +00005606 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005607 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005608 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005609 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005610 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005611 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005612 if (!lhsType->isReferenceType()) {
5613 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5614 if (rExpr.isInvalid())
5615 return Incompatible;
5616 }
Steve Narofff1120de2007-08-24 22:33:52 +00005617
John McCalldaa8e4e2010-11-15 09:13:47 +00005618 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005619 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005620 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005621
Steve Narofff1120de2007-08-24 22:33:52 +00005622 // C99 6.5.16.1p2: The value of the right operand is converted to the
5623 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005624 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5625 // so that we can use references in built-in functions even in C.
5626 // The getNonReferenceType() call makes sure that the resulting expression
5627 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005628 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieu67e29332011-08-02 04:35:43 +00005629 rExpr = ImpCastExprToType(rExpr.take(),
5630 lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005631 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005632}
5633
Richard Trieu67e29332011-08-02 04:35:43 +00005634QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5635 ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005636 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005637 << lex.get()->getType() << rex.get()->getType()
5638 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005639 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005640}
5641
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005642QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5643 SourceLocation Loc, bool isCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005644 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005645 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005646 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005647 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005648 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005649 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005650
Nate Begemanbe2341d2008-07-14 18:02:46 +00005651 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005652 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005653 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005654
Douglas Gregor255210e2010-08-06 10:14:59 +00005655 // Handle the case of equivalent AltiVec and GCC vector types
5656 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5657 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005658 if (lhsType->isExtVectorType()) {
5659 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5660 return lhsType;
5661 }
5662
5663 if (!isCompAssign)
5664 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005665 return rhsType;
5666 }
5667
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005668 if (getLangOptions().LaxVectorConversions &&
5669 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5670 // If we are allowing lax vector conversions, and LHS and RHS are both
5671 // vectors, the total size only needs to be the same. This is a
5672 // bitcast; no bits are changed but the result type is different.
5673 // FIXME: Should we really be allowing this?
5674 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5675 return lhsType;
5676 }
5677
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005678 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5679 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5680 bool swapped = false;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005681 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005682 swapped = true;
5683 std::swap(rex, lex);
5684 std::swap(rhsType, lhsType);
5685 }
Mike Stump1eb44332009-09-09 15:08:12 +00005686
Nate Begemandde25982009-06-28 19:12:57 +00005687 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005688 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005689 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005690 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005691 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5692 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005693 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005694 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005695 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005696 if (swapped) std::swap(rex, lex);
5697 return lhsType;
5698 }
5699 }
5700 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5701 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005702 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5703 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005704 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005705 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005706 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005707 if (swapped) std::swap(rex, lex);
5708 return lhsType;
5709 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005710 }
5711 }
Mike Stump1eb44332009-09-09 15:08:12 +00005712
Nate Begemandde25982009-06-28 19:12:57 +00005713 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005714 if (swapped) std::swap(rex, lex);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005715 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005716 << lex.get()->getType() << rex.get()->getType()
5717 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005718 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005719}
5720
Richard Trieu67e29332011-08-02 04:35:43 +00005721QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5722 SourceLocation Loc,
5723 bool isCompAssign, bool isDiv) {
5724 if (lex.get()->getType()->isVectorType() ||
5725 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005726 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005727
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005728 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005729 if (lex.isInvalid() || rex.isInvalid())
5730 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005731
John Wiegley429bb272011-04-08 18:41:53 +00005732 if (!lex.get()->getType()->isArithmeticType() ||
5733 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005734 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005735
Chris Lattner7ef655a2010-01-12 21:23:57 +00005736 // Check for division by zero.
5737 if (isDiv &&
Richard Trieu67e29332011-08-02 04:35:43 +00005738 rex.get()->isNullPointerConstant(Context,
5739 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005740 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieu67e29332011-08-02 04:35:43 +00005741 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005742
Chris Lattner7ef655a2010-01-12 21:23:57 +00005743 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005744}
5745
Chris Lattner7ef655a2010-01-12 21:23:57 +00005746QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005747 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00005748 if (lex.get()->getType()->isVectorType() ||
5749 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005750 if (lex.get()->getType()->hasIntegerRepresentation() &&
5751 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005752 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005753 return InvalidOperands(Loc, lex, rex);
5754 }
Steve Naroff90045e82007-07-13 23:32:42 +00005755
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005756 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005757 if (lex.isInvalid() || rex.isInvalid())
5758 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005759
Richard Trieu67e29332011-08-02 04:35:43 +00005760 if (!lex.get()->getType()->isIntegerType() ||
5761 !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005762 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005763
Chris Lattner7ef655a2010-01-12 21:23:57 +00005764 // Check for remainder by zero.
Richard Trieu67e29332011-08-02 04:35:43 +00005765 if (rex.get()->isNullPointerConstant(Context,
5766 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005767 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5768 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005769
Chris Lattner7ef655a2010-01-12 21:23:57 +00005770 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005771}
5772
Chandler Carruth13b21be2011-06-27 08:02:19 +00005773/// \brief Diagnose invalid arithmetic on two void pointers.
5774static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5775 Expr *LHS, Expr *RHS) {
5776 S.Diag(Loc, S.getLangOptions().CPlusPlus
5777 ? diag::err_typecheck_pointer_arith_void_type
5778 : diag::ext_gnu_void_ptr)
5779 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5780}
5781
5782/// \brief Diagnose invalid arithmetic on a void pointer.
5783static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5784 Expr *Pointer) {
5785 S.Diag(Loc, S.getLangOptions().CPlusPlus
5786 ? diag::err_typecheck_pointer_arith_void_type
5787 : diag::ext_gnu_void_ptr)
5788 << 0 /* one pointer */ << Pointer->getSourceRange();
5789}
5790
5791/// \brief Diagnose invalid arithmetic on two function pointers.
5792static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5793 Expr *LHS, Expr *RHS) {
5794 assert(LHS->getType()->isAnyPointerType());
5795 assert(RHS->getType()->isAnyPointerType());
5796 S.Diag(Loc, S.getLangOptions().CPlusPlus
5797 ? diag::err_typecheck_pointer_arith_function_type
5798 : diag::ext_gnu_ptr_func_arith)
5799 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5800 // We only show the second type if it differs from the first.
5801 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5802 RHS->getType())
5803 << RHS->getType()->getPointeeType()
5804 << LHS->getSourceRange() << RHS->getSourceRange();
5805}
5806
5807/// \brief Diagnose invalid arithmetic on a function pointer.
5808static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5809 Expr *Pointer) {
5810 assert(Pointer->getType()->isAnyPointerType());
5811 S.Diag(Loc, S.getLangOptions().CPlusPlus
5812 ? diag::err_typecheck_pointer_arith_function_type
5813 : diag::ext_gnu_ptr_func_arith)
5814 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5815 << 0 /* one pointer, so only one type */
5816 << Pointer->getSourceRange();
5817}
5818
5819/// \brief Check the validity of an arithmetic pointer operand.
5820///
5821/// If the operand has pointer type, this code will check for pointer types
5822/// which are invalid in arithmetic operations. These will be diagnosed
5823/// appropriately, including whether or not the use is supported as an
5824/// extension.
5825///
5826/// \returns True when the operand is valid to use (even if as an extension).
5827static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5828 Expr *Operand) {
5829 if (!Operand->getType()->isAnyPointerType()) return true;
5830
5831 QualType PointeeTy = Operand->getType()->getPointeeType();
5832 if (PointeeTy->isVoidType()) {
5833 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5834 return !S.getLangOptions().CPlusPlus;
5835 }
5836 if (PointeeTy->isFunctionType()) {
5837 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5838 return !S.getLangOptions().CPlusPlus;
5839 }
5840
5841 if ((Operand->getType()->isPointerType() &&
5842 !Operand->getType()->isDependentType()) ||
5843 Operand->getType()->isObjCObjectPointerType()) {
5844 QualType PointeeTy = Operand->getType()->getPointeeType();
5845 if (S.RequireCompleteType(
5846 Loc, PointeeTy,
5847 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5848 << PointeeTy << Operand->getSourceRange()))
5849 return false;
5850 }
5851
5852 return true;
5853}
5854
5855/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5856/// operands.
5857///
5858/// This routine will diagnose any invalid arithmetic on pointer operands much
5859/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5860/// for emitting a single diagnostic even for operations where both LHS and RHS
5861/// are (potentially problematic) pointers.
5862///
5863/// \returns True when the operand is valid to use (even if as an extension).
5864static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5865 Expr *LHS, Expr *RHS) {
5866 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5867 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5868 if (!isLHSPointer && !isRHSPointer) return true;
5869
5870 QualType LHSPointeeTy, RHSPointeeTy;
5871 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5872 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5873
5874 // Check for arithmetic on pointers to incomplete types.
5875 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5876 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5877 if (isLHSVoidPtr || isRHSVoidPtr) {
5878 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5879 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5880 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5881
5882 return !S.getLangOptions().CPlusPlus;
5883 }
5884
5885 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5886 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5887 if (isLHSFuncPtr || isRHSFuncPtr) {
5888 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5889 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5890 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5891
5892 return !S.getLangOptions().CPlusPlus;
5893 }
5894
5895 Expr *Operands[] = { LHS, RHS };
5896 for (unsigned i = 0; i < 2; ++i) {
5897 Expr *Operand = Operands[i];
5898 if ((Operand->getType()->isPointerType() &&
5899 !Operand->getType()->isDependentType()) ||
5900 Operand->getType()->isObjCObjectPointerType()) {
5901 QualType PointeeTy = Operand->getType()->getPointeeType();
5902 if (S.RequireCompleteType(
5903 Loc, PointeeTy,
5904 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5905 << PointeeTy << Operand->getSourceRange()))
5906 return false;
5907 }
5908 }
5909 return true;
5910}
5911
Chris Lattner7ef655a2010-01-12 21:23:57 +00005912QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005913 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu67e29332011-08-02 04:35:43 +00005914 if (lex.get()->getType()->isVectorType() ||
5915 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005916 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005917 if (CompLHSTy) *CompLHSTy = compType;
5918 return compType;
5919 }
Steve Naroff49b45262007-07-13 16:58:59 +00005920
Eli Friedmanab3a8522009-03-28 01:22:36 +00005921 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005922 if (lex.isInvalid() || rex.isInvalid())
5923 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005924
Reid Spencer5f016e22007-07-11 17:01:13 +00005925 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005926 if (lex.get()->getType()->isArithmeticType() &&
5927 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005928 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005929 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005930 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005931
Eli Friedmand72d16e2008-05-18 18:08:51 +00005932 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005933 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005934 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005935 std::swap(PExp, IExp);
5936
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005937 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005938 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005939 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5940 return QualType();
5941
Steve Naroff760e3c42009-07-13 21:20:41 +00005942 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005943
Chris Lattnerb5f15622009-04-24 23:50:08 +00005944 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005945 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005946 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5947 << PointeeTy << PExp->getSourceRange();
5948 return QualType();
5949 }
Mike Stump1eb44332009-09-09 15:08:12 +00005950
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005951 // Check array bounds for pointer arithemtic
5952 CheckArrayAccess(PExp, IExp);
5953
Eli Friedmanab3a8522009-03-28 01:22:36 +00005954 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005955 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005956 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005957 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005958 if (LHSTy->isPromotableIntegerType())
5959 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005960 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005961 *CompLHSTy = LHSTy;
5962 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005963 return PExp->getType();
5964 }
5965 }
5966
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005967 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005968}
5969
Chris Lattnereca7be62008-04-07 05:30:13 +00005970// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005971QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieu67e29332011-08-02 04:35:43 +00005972 SourceLocation Loc,
5973 QualType* CompLHSTy) {
5974 if (lex.get()->getType()->isVectorType() ||
5975 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005976 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005977 if (CompLHSTy) *CompLHSTy = compType;
5978 return compType;
5979 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005980
Eli Friedmanab3a8522009-03-28 01:22:36 +00005981 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005982 if (lex.isInvalid() || rex.isInvalid())
5983 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005984
Chris Lattner6e4ab612007-12-09 21:53:25 +00005985 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005986
Chris Lattner6e4ab612007-12-09 21:53:25 +00005987 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005988 if (lex.get()->getType()->isArithmeticType() &&
5989 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005990 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005991 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005992 }
Mike Stump1eb44332009-09-09 15:08:12 +00005993
Chris Lattner6e4ab612007-12-09 21:53:25 +00005994 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00005995 if (lex.get()->getType()->isAnyPointerType()) {
5996 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005997
Chris Lattnerb5f15622009-04-24 23:50:08 +00005998 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005999 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006000 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00006001 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006002 return QualType();
6003 }
Mike Stump1eb44332009-09-09 15:08:12 +00006004
Chris Lattner6e4ab612007-12-09 21:53:25 +00006005 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00006006 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00006007 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6008 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006009
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006010 Expr *IExpr = rex.get()->IgnoreParenCasts();
6011 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6012 OK_Ordinary, IExpr->getExprLoc());
6013 // Check array bounds for pointer arithemtic
6014 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6015
John Wiegley429bb272011-04-08 18:41:53 +00006016 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6017 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006018 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006019
Chris Lattner6e4ab612007-12-09 21:53:25 +00006020 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006021 if (const PointerType *RHSPTy
6022 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006023 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006024
Eli Friedman88d936b2009-05-16 13:54:38 +00006025 if (getLangOptions().CPlusPlus) {
6026 // Pointee types must be the same: C++ [expr.add]
6027 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6028 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006029 << lex.get()->getType() << rex.get()->getType()
6030 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006031 return QualType();
6032 }
6033 } else {
6034 // Pointee types must be compatible C99 6.5.6p3
6035 if (!Context.typesAreCompatible(
6036 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6037 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
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 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006043 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006044
Chandler Carruth13b21be2011-06-27 08:02:19 +00006045 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6046 lex.get(), rex.get()))
6047 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006048
John Wiegley429bb272011-04-08 18:41:53 +00006049 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006050 return Context.getPointerDiffType();
6051 }
6052 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006053
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006054 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006055}
6056
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006057static bool isScopedEnumerationType(QualType T) {
6058 if (const EnumType *ET = dyn_cast<EnumType>(T))
6059 return ET->getDecl()->isScoped();
6060 return false;
6061}
6062
John Wiegley429bb272011-04-08 18:41:53 +00006063static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006064 SourceLocation Loc, unsigned Opc,
6065 QualType LHSTy) {
6066 llvm::APSInt Right;
6067 // Check right/shifter operand
Richard Trieu67e29332011-08-02 04:35:43 +00006068 if (rex.get()->isValueDependent() ||
6069 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006070 return;
6071
6072 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006073 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006074 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006075 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006076 return;
6077 }
6078 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006079 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006080 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006081 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006082 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006083 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006084 return;
6085 }
6086 if (Opc != BO_Shl)
6087 return;
6088
6089 // When left shifting an ICE which is signed, we can check for overflow which
6090 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6091 // integers have defined behavior modulo one more than the maximum value
6092 // representable in the result type, so never warn for those.
6093 llvm::APSInt Left;
Richard Trieu67e29332011-08-02 04:35:43 +00006094 if (lex.get()->isValueDependent() ||
6095 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006096 LHSTy->hasUnsignedIntegerRepresentation())
6097 return;
6098 llvm::APInt ResultBits =
6099 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6100 if (LeftBits.uge(ResultBits))
6101 return;
6102 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6103 Result = Result.shl(Right);
6104
Ted Kremenekfa821382011-06-15 00:54:52 +00006105 // Print the bit representation of the signed integer as an unsigned
6106 // hexadecimal number.
6107 llvm::SmallString<40> HexResult;
6108 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6109
Chandler Carruth21206d52011-02-23 23:34:11 +00006110 // If we are only missing a sign bit, this is less likely to result in actual
6111 // bugs -- if the result is cast back to an unsigned type, it will have the
6112 // expected value. Thus we place this behind a different warning that can be
6113 // turned off separately if needed.
6114 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006115 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6116 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006117 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006118 return;
6119 }
6120
6121 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00006122 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieu67e29332011-08-02 04:35:43 +00006123 << Left.getBitWidth() << lex.get()->getSourceRange()
6124 << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006125}
6126
Chris Lattnereca7be62008-04-07 05:30:13 +00006127// C99 6.5.7
Richard Trieu67e29332011-08-02 04:35:43 +00006128QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6129 SourceLocation Loc, unsigned Opc,
6130 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006131 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00006132 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6133 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006134 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006136 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6137 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00006138 if (isScopedEnumerationType(lex.get()->getType()) ||
6139 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006140 return InvalidOperands(Loc, lex, rex);
6141 }
6142
Nate Begeman2207d792009-10-25 02:26:48 +00006143 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu67e29332011-08-02 04:35:43 +00006144 if (lex.get()->getType()->isVectorType() ||
6145 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006146 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006147
Chris Lattnerca5eede2007-12-12 05:47:28 +00006148 // Shifts don't perform usual arithmetic conversions, they just do integer
6149 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006150
John McCall1bc80af2010-12-16 19:28:59 +00006151 // For the LHS, do usual unary conversions, but then reset them away
6152 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00006153 ExprResult old_lex = lex;
6154 lex = UsualUnaryConversions(lex.take());
6155 if (lex.isInvalid())
6156 return QualType();
6157 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00006158 if (isCompAssign) lex = old_lex;
6159
6160 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00006161 rex = UsualUnaryConversions(rex.take());
6162 if (rex.isInvalid())
6163 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006164
Ryan Flynnd0439682009-08-07 16:20:20 +00006165 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006166 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006167
Chris Lattnerca5eede2007-12-12 05:47:28 +00006168 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006169 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006170}
6171
Chandler Carruth99919472010-07-10 12:30:03 +00006172static bool IsWithinTemplateSpecialization(Decl *D) {
6173 if (DeclContext *DC = D->getDeclContext()) {
6174 if (isa<ClassTemplateSpecializationDecl>(DC))
6175 return true;
6176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6177 return FD->isFunctionTemplateSpecialization();
6178 }
6179 return false;
6180}
6181
Douglas Gregor0c6db942009-05-04 06:07:12 +00006182// C99 6.5.8, C++ [expr.rel]
Richard Trieu67e29332011-08-02 04:35:43 +00006183QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6184 SourceLocation Loc, unsigned OpaqueOpc,
6185 bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006186 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006187
Chris Lattner02dd4b12009-12-05 05:40:13 +00006188 // Handle vector comparisons separately.
Richard Trieu67e29332011-08-02 04:35:43 +00006189 if (lex.get()->getType()->isVectorType() ||
6190 rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006191 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006192
John Wiegley429bb272011-04-08 18:41:53 +00006193 QualType lType = lex.get()->getType();
6194 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006195
John Wiegley429bb272011-04-08 18:41:53 +00006196 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6197 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006198 QualType LHSStrippedType = LHSStripped->getType();
6199 QualType RHSStrippedType = RHSStripped->getType();
6200
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006201
6202
Chandler Carruth543cb652011-02-17 08:37:06 +00006203 // Two different enums will raise a warning when compared.
6204 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6205 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6206 if (LHSEnumType->getDecl()->getIdentifier() &&
6207 RHSEnumType->getDecl()->getIdentifier() &&
6208 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6209 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6210 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00006211 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00006212 }
6213 }
6214 }
6215
Douglas Gregor8eee1192010-06-22 22:12:46 +00006216 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006217 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00006218 !lex.get()->getLocStart().isMacroID() &&
6219 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006220 // For non-floating point types, check for self-comparisons of the form
6221 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6222 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006223 //
6224 // NOTE: Don't warn about comparison expressions resulting from macro
6225 // expansion. Also don't warn about comparisons which are only self
6226 // comparisons within a template specialization. The warnings should catch
6227 // obvious cases in the definition of the template anyways. The idea is to
6228 // warn when the typed comparison operator will always evaluate to the same
6229 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006230 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006231 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006232 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006233 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006234 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006235 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006236 << (Opc == BO_EQ
6237 || Opc == BO_LE
6238 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006239 } else if (lType->isArrayType() && rType->isArrayType() &&
6240 !DRL->getDecl()->getType()->isReferenceType() &&
6241 !DRR->getDecl()->getType()->isReferenceType()) {
6242 // what is it always going to eval to?
6243 char always_evals_to;
6244 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006245 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006246 always_evals_to = 0; // false
6247 break;
John McCall2de56d12010-08-25 11:45:40 +00006248 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006249 always_evals_to = 1; // true
6250 break;
6251 default:
6252 // best we can say is 'a constant'
6253 always_evals_to = 2; // e.g. array1 <= array2
6254 break;
6255 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006256 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006257 << 1 // array
6258 << always_evals_to);
6259 }
6260 }
Chandler Carruth99919472010-07-10 12:30:03 +00006261 }
Mike Stump1eb44332009-09-09 15:08:12 +00006262
Chris Lattner55660a72009-03-08 19:39:53 +00006263 if (isa<CastExpr>(LHSStripped))
6264 LHSStripped = LHSStripped->IgnoreParenCasts();
6265 if (isa<CastExpr>(RHSStripped))
6266 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006267
Chris Lattner55660a72009-03-08 19:39:53 +00006268 // Warn about comparisons against a string constant (unless the other
6269 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006270 Expr *literalString = 0;
6271 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006272 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006273 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006274 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006275 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006276 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006277 } else if ((isa<StringLiteral>(RHSStripped) ||
6278 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006279 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006280 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006281 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006282 literalStringStripped = RHSStripped;
6283 }
6284
6285 if (literalString) {
6286 std::string resultComparison;
6287 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006288 case BO_LT: resultComparison = ") < 0"; break;
6289 case BO_GT: resultComparison = ") > 0"; break;
6290 case BO_LE: resultComparison = ") <= 0"; break;
6291 case BO_GE: resultComparison = ") >= 0"; break;
6292 case BO_EQ: resultComparison = ") == 0"; break;
6293 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006294 default: assert(false && "Invalid comparison operator");
6295 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006296
Ted Kremenek351ba912011-02-23 01:52:04 +00006297 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006298 PDiag(diag::warn_stringcompare)
6299 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006300 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006301 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006302 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006303
Douglas Gregord64fdd02010-06-08 19:50:34 +00006304 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieu67e29332011-08-02 04:35:43 +00006305 if (lex.get()->getType()->isArithmeticType() &&
6306 rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006307 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006308 if (lex.isInvalid() || rex.isInvalid())
6309 return QualType();
6310 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006311 else {
John Wiegley429bb272011-04-08 18:41:53 +00006312 lex = UsualUnaryConversions(lex.take());
6313 if (lex.isInvalid())
6314 return QualType();
6315
6316 rex = UsualUnaryConversions(rex.take());
6317 if (rex.isInvalid())
6318 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006319 }
6320
John Wiegley429bb272011-04-08 18:41:53 +00006321 lType = lex.get()->getType();
6322 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006323
Douglas Gregor447b69e2008-11-19 03:25:36 +00006324 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006325 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006326
Chris Lattnera5937dd2007-08-26 01:18:55 +00006327 if (isRelational) {
6328 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006329 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006330 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006331 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006332 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006333 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006334
Chris Lattnera5937dd2007-08-26 01:18:55 +00006335 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006336 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006337 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006338
John Wiegley429bb272011-04-08 18:41:53 +00006339 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006340 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006341 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006342 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006343
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006344 // All of the following pointer-related warnings are GCC extensions, except
6345 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006346 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006347 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006348 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006349 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006350 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006351
Douglas Gregor0c6db942009-05-04 06:07:12 +00006352 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006353 if (LCanPointeeTy == RCanPointeeTy)
6354 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006355 if (!isRelational &&
6356 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6357 // Valid unless comparison between non-null pointer and function pointer
6358 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006359 // In a SFINAE context, we treat this as a hard error to maintain
6360 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006361 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6362 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006363 Diag(Loc,
6364 isSFINAEContext()?
6365 diag::err_typecheck_comparison_of_fptr_to_void
6366 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006367 << lType << rType << lex.get()->getSourceRange()
6368 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006369
6370 if (isSFINAEContext())
6371 return QualType();
6372
John Wiegley429bb272011-04-08 18:41:53 +00006373 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006374 return ResultTy;
6375 }
6376 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006377
Douglas Gregor0c6db942009-05-04 06:07:12 +00006378 // C++ [expr.rel]p2:
6379 // [...] Pointer conversions (4.10) and qualification
6380 // conversions (4.4) are performed on pointer operands (or on
6381 // a pointer operand and a null pointer constant) to bring
6382 // them to their composite pointer type. [...]
6383 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006384 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006385 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006386 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006387 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006388 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006389 if (T.isNull()) {
6390 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006391 << lType << rType << lex.get()->getSourceRange()
6392 << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006393 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006394 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006395 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006396 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006397 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006398 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006399 }
6400
John Wiegley429bb272011-04-08 18:41:53 +00006401 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6402 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006403 return ResultTy;
6404 }
Eli Friedman3075e762009-08-23 00:27:47 +00006405 // C99 6.5.9p2 and C99 6.5.8p2
6406 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6407 RCanPointeeTy.getUnqualifiedType())) {
6408 // Valid unless a relational comparison of function pointers
6409 if (isRelational && LCanPointeeTy->isFunctionType()) {
6410 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006411 << lType << rType << lex.get()->getSourceRange()
6412 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006413 }
6414 } else if (!isRelational &&
6415 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6416 // Valid unless comparison between non-null pointer and function pointer
6417 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6418 && !LHSIsNull && !RHSIsNull) {
6419 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006420 << lType << rType << lex.get()->getSourceRange()
6421 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006422 }
6423 } else {
6424 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006425 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006426 << lType << rType << lex.get()->getSourceRange()
6427 << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006428 }
John McCall34d6f932011-03-11 04:25:25 +00006429 if (LCanPointeeTy != RCanPointeeTy) {
6430 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006431 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006432 else
John Wiegley429bb272011-04-08 18:41:53 +00006433 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006434 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006435 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006436 }
Mike Stump1eb44332009-09-09 15:08:12 +00006437
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006438 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006439 // Comparison of nullptr_t with itself.
6440 if (lType->isNullPtrType() && rType->isNullPtrType())
6441 return ResultTy;
6442
Mike Stump1eb44332009-09-09 15:08:12 +00006443 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006444 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006445 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006446 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006447 (!isRelational &&
6448 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006449 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006450 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006451 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006452 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006453 return ResultTy;
6454 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006455 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006456 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006457 (!isRelational &&
6458 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006459 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006460 rType->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
6466 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006467 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006468 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6469 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006470 // In addition, pointers to members can be compared, or a pointer to
6471 // member and a null pointer constant. Pointer to member conversions
6472 // (4.11) and qualification conversions (4.4) are performed to bring
6473 // them to a common type. If one operand is a null pointer constant,
6474 // the common type is the type of the other operand. Otherwise, the
6475 // common type is a pointer to member type similar (4.4) to the type
6476 // of one of the operands, with a cv-qualification signature (4.4)
6477 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006478 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006479 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006480 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006481 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006482 if (T.isNull()) {
6483 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006484 << lType << rType << lex.get()->getSourceRange()
6485 << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006486 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006487 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006488 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006489 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006490 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006491 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006492 }
Mike Stump1eb44332009-09-09 15:08:12 +00006493
John Wiegley429bb272011-04-08 18:41:53 +00006494 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6495 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006496 return ResultTy;
6497 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006498
6499 // Handle scoped enumeration types specifically, since they don't promote
6500 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006501 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieu67e29332011-08-02 04:35:43 +00006502 Context.hasSameUnqualifiedType(lex.get()->getType(),
6503 rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006504 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006505 }
Mike Stump1eb44332009-09-09 15:08:12 +00006506
Steve Naroff1c7d0672008-09-04 15:10:53 +00006507 // Handle block pointer types.
Richard Trieu67e29332011-08-02 04:35:43 +00006508 if (!isRelational && lType->isBlockPointerType() &&
6509 rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006510 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6511 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006512
Steve Naroff1c7d0672008-09-04 15:10:53 +00006513 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006514 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006515 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006516 << lType << rType << lex.get()->getSourceRange()
6517 << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006518 }
John Wiegley429bb272011-04-08 18:41:53 +00006519 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006520 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006521 }
John Wiegley429bb272011-04-08 18:41:53 +00006522
Steve Naroff59f53942008-09-28 01:11:11 +00006523 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006524 if (!isRelational
6525 && ((lType->isBlockPointerType() && rType->isPointerType())
6526 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006527 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006528 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006529 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006530 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006531 ->getPointeeType()->isVoidType())))
6532 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006533 << lType << rType << lex.get()->getSourceRange()
6534 << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006535 }
John McCall34d6f932011-03-11 04:25:25 +00006536 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006537 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006538 else
John Wiegley429bb272011-04-08 18:41:53 +00006539 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006540 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006541 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006542
John McCall34d6f932011-03-11 04:25:25 +00006543 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6544 const PointerType *LPT = lType->getAs<PointerType>();
6545 const PointerType *RPT = rType->getAs<PointerType>();
6546 if (LPT || RPT) {
6547 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6548 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006549
Steve Naroffa8069f12008-11-17 19:49:16 +00006550 if (!LPtrToVoid && !RPtrToVoid &&
6551 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006552 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006553 << lType << rType << lex.get()->getSourceRange()
6554 << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006555 }
John McCall34d6f932011-03-11 04:25:25 +00006556 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006557 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006558 else
John Wiegley429bb272011-04-08 18:41:53 +00006559 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006560 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006561 }
Steve Naroff14108da2009-07-10 23:34:53 +00006562 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006563 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006564 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006565 << lType << rType << lex.get()->getSourceRange()
6566 << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00006567 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006568 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006569 else
John Wiegley429bb272011-04-08 18:41:53 +00006570 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006571 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006572 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006573 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006574 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6575 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006576 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006577 bool isError = false;
6578 if ((LHSIsNull && lType->isIntegerType()) ||
6579 (RHSIsNull && rType->isIntegerType())) {
6580 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006581 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006582 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006583 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006584 else if (getLangOptions().CPlusPlus) {
6585 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6586 isError = true;
6587 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006588 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006589
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006590 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006591 Diag(Loc, DiagID)
Richard Trieu67e29332011-08-02 04:35:43 +00006592 << lType << rType << lex.get()->getSourceRange()
6593 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006594 if (isError)
6595 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006596 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006597
6598 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006599 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006600 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006601 else
John Wiegley429bb272011-04-08 18:41:53 +00006602 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006603 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006604 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006605 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006606
Steve Naroff39218df2008-09-04 16:56:14 +00006607 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006608 if (!isRelational && RHSIsNull
6609 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006610 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006611 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006612 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006613 if (!isRelational && LHSIsNull
6614 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006615 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006616 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006617 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006618
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006619 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006620}
6621
Nate Begemanbe2341d2008-07-14 18:02:46 +00006622/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006623/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006624/// like a scalar comparison, a vector comparison produces a vector of integer
6625/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006626QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006627 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006628 bool isRelational) {
6629 // Check to make sure we're operating on vectors of the same type and width,
6630 // Allowing one side to be a scalar of element type.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006631 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006632 if (vType.isNull())
6633 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006634
John Wiegley429bb272011-04-08 18:41:53 +00006635 QualType lType = lex.get()->getType();
6636 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006637
Anton Yartsev7870b132011-03-27 15:36:07 +00006638 // If AltiVec, the comparison results in a numeric type, i.e.
6639 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006640 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006641 return Context.getLogicalOperationType();
6642
Nate Begemanbe2341d2008-07-14 18:02:46 +00006643 // For non-floating point types, check for self-comparisons of the form
6644 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6645 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006646 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006647 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6648 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006649 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006650 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006651 PDiag(diag::warn_comparison_always)
6652 << 0 // self-
6653 << 2 // "a constant"
6654 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006655 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006656
Nate Begemanbe2341d2008-07-14 18:02:46 +00006657 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006658 if (!isRelational && lType->hasFloatingRepresentation()) {
6659 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006660 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006661 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662
Nate Begemanbe2341d2008-07-14 18:02:46 +00006663 // Return the type for the comparison, which is the same as vector type for
6664 // integer vectors, or an integer type of identical size and number of
6665 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006666 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006667 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006668
John McCall183700f2009-09-21 23:43:11 +00006669 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006670 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006671 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006672 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006673 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006674 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6675
Mike Stumpeed9cac2009-02-19 03:04:26 +00006676 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006677 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006678 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6679}
6680
Reid Spencer5f016e22007-07-11 17:01:13 +00006681inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006682 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00006683 if (lex.get()->getType()->isVectorType() ||
6684 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006685 if (lex.get()->getType()->hasIntegerRepresentation() &&
6686 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006687 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006688
6689 return InvalidOperands(Loc, lex, rex);
6690 }
Steve Naroff90045e82007-07-13 23:32:42 +00006691
John Wiegley429bb272011-04-08 18:41:53 +00006692 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieu67e29332011-08-02 04:35:43 +00006693 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6694 isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006695 if (lexResult.isInvalid() || rexResult.isInvalid())
6696 return QualType();
6697 lex = lexResult.take();
6698 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006699
John Wiegley429bb272011-04-08 18:41:53 +00006700 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6701 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006702 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006703 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006704}
6705
6706inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006707 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006708
6709 // Diagnose cases where the user write a logical and/or but probably meant a
6710 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6711 // is a constant.
Richard Trieu67e29332011-08-02 04:35:43 +00006712 if (lex.get()->getType()->isIntegerType() &&
6713 !lex.get()->getType()->isBooleanType() &&
John Wiegley429bb272011-04-08 18:41:53 +00006714 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006715 // Don't warn in macros or template instantiations.
6716 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006717 // If the RHS can be constant folded, and if it constant folds to something
6718 // that isn't 0 or 1 (which indicate a potential logical operation that
6719 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006720 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006721 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006722 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6723 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6724 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6725 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6726 << rex.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006727 << (Opc == BO_LAnd ? "&&" : "||");
6728 // Suggest replacing the logical operator with the bitwise version
6729 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6730 << (Opc == BO_LAnd ? "&" : "|")
6731 << FixItHint::CreateReplacement(SourceRange(
6732 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6733 getLangOptions())),
6734 Opc == BO_LAnd ? "&" : "|");
6735 if (Opc == BO_LAnd)
6736 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6737 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6738 << FixItHint::CreateRemoval(
6739 SourceRange(
6740 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6741 0, getSourceManager(),
6742 getLangOptions()),
6743 rex.get()->getLocEnd()));
6744 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006745 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006746
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006747 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006748 lex = UsualUnaryConversions(lex.take());
6749 if (lex.isInvalid())
6750 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006751
John Wiegley429bb272011-04-08 18:41:53 +00006752 rex = UsualUnaryConversions(rex.take());
6753 if (rex.isInvalid())
6754 return QualType();
6755
Richard Trieu67e29332011-08-02 04:35:43 +00006756 if (!lex.get()->getType()->isScalarType() ||
6757 !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006758 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006759
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006760 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006761 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006762
John McCall75f7c0f2010-06-04 00:29:51 +00006763 // The following is safe because we only use this method for
6764 // non-overloadable operands.
6765
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006766 // C++ [expr.log.and]p1
6767 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006768 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006769 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6770 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006771 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006772 lex = move(lexRes);
6773
6774 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6775 if (rexRes.isInvalid())
6776 return InvalidOperands(Loc, lex, rex);
6777 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006778
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006779 // C++ [expr.log.and]p2
6780 // C++ [expr.log.or]p2
6781 // The result is a bool.
6782 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006783}
6784
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006785/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6786/// is a read-only property; return true if so. A readonly property expression
6787/// depends on various declarations and thus must be treated specially.
6788///
Mike Stump1eb44332009-09-09 15:08:12 +00006789static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006790 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6791 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006792 if (PropExpr->isImplicitProperty()) return false;
6793
6794 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6795 QualType BaseType = PropExpr->isSuperReceiver() ?
6796 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006797 PropExpr->getBase()->getType();
6798
John McCall12f78a62010-12-02 01:19:52 +00006799 if (const ObjCObjectPointerType *OPT =
6800 BaseType->getAsObjCInterfacePointerType())
6801 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6802 if (S.isPropertyReadonly(PDecl, IFace))
6803 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006804 }
6805 return false;
6806}
6807
Fariborz Jahanian14086762011-03-28 23:47:18 +00006808static bool IsConstProperty(Expr *E, Sema &S) {
6809 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6810 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6811 if (PropExpr->isImplicitProperty()) return false;
6812
6813 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6814 QualType T = PDecl->getType();
6815 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006816 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006817 CanQualType CT = S.Context.getCanonicalType(T);
6818 return CT.isConstQualified();
6819 }
6820 return false;
6821}
6822
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006823static bool IsReadonlyMessage(Expr *E, Sema &S) {
6824 if (E->getStmtClass() != Expr::MemberExprClass)
6825 return false;
6826 const MemberExpr *ME = cast<MemberExpr>(E);
6827 NamedDecl *Member = ME->getMemberDecl();
6828 if (isa<FieldDecl>(Member)) {
6829 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6830 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6831 return false;
6832 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6833 }
6834 return false;
6835}
6836
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006837/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6838/// emit an error and return true. If so, return false.
6839static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006840 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006841 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006842 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006843 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6844 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006845 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6846 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006847 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6848 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006849 if (IsLV == Expr::MLV_Valid)
6850 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006851
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006852 unsigned Diag = 0;
6853 bool NeedType = false;
6854 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006855 case Expr::MLV_ConstQualified:
6856 Diag = diag::err_typecheck_assign_const;
6857
John McCall7acddac2011-06-17 06:42:21 +00006858 // In ARC, use some specialized diagnostics for occasions where we
6859 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006860 if (S.getLangOptions().ObjCAutoRefCount) {
6861 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6862 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6863 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6864
John McCall7acddac2011-06-17 06:42:21 +00006865 // Use the normal diagnostic if it's pseudo-__strong but the
6866 // user actually wrote 'const'.
6867 if (var->isARCPseudoStrong() &&
6868 (!var->getTypeSourceInfo() ||
6869 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6870 // There are two pseudo-strong cases:
6871 // - self
John McCallf85e1932011-06-15 23:02:42 +00006872 ObjCMethodDecl *method = S.getCurMethodDecl();
6873 if (method && var == method->getSelfDecl())
6874 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006875
6876 // - fast enumeration variables
6877 else
John McCallf85e1932011-06-15 23:02:42 +00006878 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006879
John McCallf85e1932011-06-15 23:02:42 +00006880 SourceRange Assign;
6881 if (Loc != OrigLoc)
6882 Assign = SourceRange(OrigLoc, OrigLoc);
6883 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6884 // We need to preserve the AST regardless, so migration tool
6885 // can do its job.
6886 return false;
6887 }
6888 }
6889 }
6890
6891 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006892 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006893 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6894 NeedType = true;
6895 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006896 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006897 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6898 NeedType = true;
6899 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006900 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006901 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6902 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006903 case Expr::MLV_Valid:
6904 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006905 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006906 case Expr::MLV_MemberFunction:
6907 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006908 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6909 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006910 case Expr::MLV_IncompleteType:
6911 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006912 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006913 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006914 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006915 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006916 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6917 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006918 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006919 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6920 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006921 case Expr::MLV_ReadonlyProperty:
6922 Diag = diag::error_readonly_property_assignment;
6923 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006924 case Expr::MLV_NoSetterProperty:
6925 Diag = diag::error_nosetter_property_assignment;
6926 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006927 case Expr::MLV_InvalidMessageExpression:
6928 Diag = diag::error_readonly_message_assignment;
6929 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006930 case Expr::MLV_SubObjCPropertySetting:
6931 Diag = diag::error_no_subobject_property_setting;
6932 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006933 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006934
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006935 SourceRange Assign;
6936 if (Loc != OrigLoc)
6937 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006938 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006939 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006940 else
Mike Stump1eb44332009-09-09 15:08:12 +00006941 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006942 return true;
6943}
6944
6945
6946
6947// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006948QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006949 SourceLocation Loc,
6950 QualType CompoundType) {
6951 // Verify that LHS is a modifiable lvalue, and emit error if not.
6952 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006953 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006954
6955 QualType LHSType = LHS->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00006956 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6957 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006958 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006959 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006960 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006961 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00006962 if (LHS->getObjectKind() == OK_ObjCProperty) {
6963 ExprResult LHSResult = Owned(LHS);
6964 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6965 if (LHSResult.isInvalid())
6966 return QualType();
6967 LHS = LHSResult.take();
6968 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006969 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00006970 if (RHS.isInvalid())
6971 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006972 // Special case of NSObject attributes on c-style pointer types.
6973 if (ConvTy == IncompatiblePointer &&
6974 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006975 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006976 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006977 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006978 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006979
John McCallf89e55a2010-11-18 06:31:45 +00006980 if (ConvTy == Compatible &&
6981 getLangOptions().ObjCNonFragileABI &&
6982 LHSType->isObjCObjectType())
6983 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6984 << LHSType;
6985
Chris Lattner2c156472008-08-21 18:04:13 +00006986 // If the RHS is a unary plus or minus, check to see if they = and + are
6987 // right next to each other. If so, the user may have typo'd "x =+ 4"
6988 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00006989 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00006990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6991 RHSCheck = ICE->getSubExpr();
6992 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00006993 if ((UO->getOpcode() == UO_Plus ||
6994 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006995 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006996 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006997 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6998 // And there is a space or other character before the subexpr of the
6999 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007000 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7001 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007002 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007003 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007004 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007005 }
Chris Lattner2c156472008-08-21 18:04:13 +00007006 }
John McCallf85e1932011-06-15 23:02:42 +00007007
7008 if (ConvTy == Compatible) {
7009 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7010 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007011 else if (getLangOptions().ObjCAutoRefCount)
7012 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007013 }
Chris Lattner2c156472008-08-21 18:04:13 +00007014 } else {
7015 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007016 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007017 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007018
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007019 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007020 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007021 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007022
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007023 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007024
Reid Spencer5f016e22007-07-11 17:01:13 +00007025 // C99 6.5.16p3: The type of an assignment expression is the type of the
7026 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007027 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007028 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7029 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007030 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007031 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007032 return (getLangOptions().CPlusPlus
7033 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007034}
7035
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007036// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007037static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007038 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007039 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007040
John McCallfb8721c2011-04-10 19:13:55 +00007041 LHS = S.CheckPlaceholderExpr(LHS.take());
7042 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007043 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007044 return QualType();
7045
John McCallcf2e5062010-10-12 07:14:40 +00007046 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7047 // operands, but not unary promotions.
7048 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007049
John McCallf6a16482010-12-04 03:47:34 +00007050 // So we treat the LHS as a ignored value, and in C++ we allow the
7051 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007052 LHS = S.IgnoredValueConversions(LHS.take());
7053 if (LHS.isInvalid())
7054 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007055
7056 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007057 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7058 if (RHS.isInvalid())
7059 return QualType();
7060 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007061 S.RequireCompleteType(Loc, RHS.get()->getType(),
7062 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007063 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007064
John Wiegley429bb272011-04-08 18:41:53 +00007065 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007066}
7067
Steve Naroff49b45262007-07-13 16:58:59 +00007068/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7069/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007070static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7071 ExprValueKind &VK,
7072 SourceLocation OpLoc,
7073 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007074 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007075 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007076
Chris Lattner3528d352008-11-21 07:05:48 +00007077 QualType ResType = Op->getType();
7078 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007079
John McCall09431682010-11-18 19:01:18 +00007080 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007081 // Decrement of bool is not allowed.
7082 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007083 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007084 return QualType();
7085 }
7086 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007087 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007088 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007089 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007090 } else if (ResType->isAnyPointerType()) {
7091 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007092
Chris Lattner3528d352008-11-21 07:05:48 +00007093 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007094 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007095 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007096
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007097 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007098 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7099 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007100 << PointeeTy << Op->getSourceRange();
7101 return QualType();
7102 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007103 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007104 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007105 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007106 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007107 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007108 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007109 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007110 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7111 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007112 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7113 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007114 } else {
John McCall09431682010-11-18 19:01:18 +00007115 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007116 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007117 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007118 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007119 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007120 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007121 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007122 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007123 // In C++, a prefix increment is the same type as the operand. Otherwise
7124 // (in C or with postfix), the increment is the unqualified type of the
7125 // operand.
John McCall09431682010-11-18 19:01:18 +00007126 if (isPrefix && S.getLangOptions().CPlusPlus) {
7127 VK = VK_LValue;
7128 return ResType;
7129 } else {
7130 VK = VK_RValue;
7131 return ResType.getUnqualifiedType();
7132 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007133}
7134
John Wiegley429bb272011-04-08 18:41:53 +00007135ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007136 assert(E->getValueKind() == VK_LValue &&
7137 E->getObjectKind() == OK_ObjCProperty);
7138 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7139
Douglas Gregor926df6c2011-06-11 01:09:30 +00007140 QualType T = E->getType();
7141 QualType ReceiverType;
7142 if (PRE->isObjectReceiver())
7143 ReceiverType = PRE->getBase()->getType();
7144 else if (PRE->isSuperReceiver())
7145 ReceiverType = PRE->getSuperReceiverType();
7146 else
7147 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7148
John McCallf6a16482010-12-04 03:47:34 +00007149 ExprValueKind VK = VK_RValue;
7150 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007151 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007152 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007153 T = getMessageSendResultType(ReceiverType, GetterMethod,
7154 PRE->isClassReceiver(),
7155 PRE->isSuperReceiver());
7156 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007157 }
7158 else {
7159 Diag(PRE->getLocation(), diag::err_getter_not_found)
7160 << PRE->getBase()->getType();
7161 }
John McCallf6a16482010-12-04 03:47:34 +00007162 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007163
7164 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007165 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007166
7167 ExprResult Result = MaybeBindToTemporary(E);
7168 if (!Result.isInvalid())
7169 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007170
7171 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007172}
7173
Richard Trieu67e29332011-08-02 04:35:43 +00007174void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7175 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007176 assert(LHS.get()->getValueKind() == VK_LValue &&
7177 LHS.get()->getObjectKind() == OK_ObjCProperty);
7178 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007179
John McCallf85e1932011-06-15 23:02:42 +00007180 bool Consumed = false;
7181
John Wiegley429bb272011-04-08 18:41:53 +00007182 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007183 // If using property-dot syntax notation for assignment, and there is a
7184 // setter, RHS expression is being passed to the setter argument. So,
7185 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007186 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007187 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7188 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007189 Consumed = (getLangOptions().ObjCAutoRefCount &&
7190 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007191
7192 // Otherwise, if the getter returns an l-value, just call that.
7193 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007194 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007195 ExprValueKind VK = Expr::getValueKindForType(Result);
7196 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007197 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7198 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007199 return;
John McCall12f78a62010-12-02 01:19:52 +00007200 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007201 }
John McCallf85e1932011-06-15 23:02:42 +00007202 } else if (getLangOptions().ObjCAutoRefCount) {
7203 const ObjCMethodDecl *setter
7204 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7205 if (setter) {
7206 ObjCMethodDecl::param_iterator P = setter->param_begin();
7207 LHSTy = (*P)->getType();
7208 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7209 }
John McCallf6a16482010-12-04 03:47:34 +00007210 }
7211
John McCallf85e1932011-06-15 23:02:42 +00007212 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7213 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007214 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007215 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007216 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007217 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007218 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007219 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7220 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7221 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007222 }
7223}
7224
7225
Anders Carlsson369dee42008-02-01 07:15:58 +00007226/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007227/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007228/// where the declaration is needed for type checking. We only need to
7229/// handle cases when the expression references a function designator
7230/// or is an lvalue. Here are some examples:
7231/// - &(x) => x
7232/// - &*****f => f for f a function designator.
7233/// - &s.xx => s
7234/// - &s.zz[1].yy -> s, if zz is an array
7235/// - *(x + 1) -> x, if x is an array
7236/// - &"123"[2] -> 0
7237/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007238static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007239 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007240 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007241 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007242 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007243 // If this is an arrow operator, the address is an offset from
7244 // the base's value, so the object the base refers to is
7245 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007246 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007247 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007248 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007249 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007250 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007251 // FIXME: This code shouldn't be necessary! We should catch the implicit
7252 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007253 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7254 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7255 if (ICE->getSubExpr()->getType()->isArrayType())
7256 return getPrimaryDecl(ICE->getSubExpr());
7257 }
7258 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007259 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007260 case Stmt::UnaryOperatorClass: {
7261 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007262
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007263 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007264 case UO_Real:
7265 case UO_Imag:
7266 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007267 return getPrimaryDecl(UO->getSubExpr());
7268 default:
7269 return 0;
7270 }
7271 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007272 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007273 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007274 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007275 // If the result of an implicit cast is an l-value, we care about
7276 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007277 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007278 default:
7279 return 0;
7280 }
7281}
7282
7283/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007284/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007285/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007286/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007287/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007288/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007289/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007290static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7291 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007292 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007293 return S.Context.DependentTy;
7294 if (OrigOp->getType() == S.Context.OverloadTy)
7295 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007296 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7297 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007298 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7299 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7300 << OrigOp->getSourceRange();
7301 return QualType();
7302 }
John McCall9c72c602010-08-27 09:08:28 +00007303
John McCall755d8492011-04-12 00:42:48 +00007304 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007305
John McCall9c72c602010-08-27 09:08:28 +00007306 // Make sure to ignore parentheses in subsequent checks
7307 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007308
John McCall09431682010-11-18 19:01:18 +00007309 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007310 // Implement C99-only parts of addressof rules.
7311 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007312 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007313 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7314 // (assuming the deref expression is valid).
7315 return uOp->getSubExpr()->getType();
7316 }
7317 // Technically, there should be a check for array subscript
7318 // expressions here, but the result of one is always an lvalue anyway.
7319 }
John McCall5808ce42011-02-03 08:15:49 +00007320 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007321 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007322
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007323 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007324 bool sfinae = S.isSFINAEContext();
7325 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7326 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007327 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007328 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007329 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007330 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007331 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007332 } else if (lval == Expr::LV_MemberFunction) {
7333 // If it's an instance method, make a member pointer.
7334 // The expression must have exactly the form &A::foo.
7335
7336 // If the underlying expression isn't a decl ref, give up.
7337 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007338 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007339 << OrigOp->getSourceRange();
7340 return QualType();
7341 }
7342 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7343 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7344
7345 // The id-expression was parenthesized.
7346 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007347 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007348 << OrigOp->getSourceRange();
7349
7350 // The method was named without a qualifier.
7351 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007352 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007353 << op->getSourceRange();
7354 }
7355
John McCall09431682010-11-18 19:01:18 +00007356 return S.Context.getMemberPointerType(op->getType(),
7357 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007358 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007359 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007360 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007361 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007362 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007363 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007364 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007365 return QualType();
7366 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007367 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007368 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007369 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007370 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007371 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007372 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007373 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007374 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007375 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007376 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007377 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007378 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007379 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007380 << "property expression" << op->getSourceRange();
7381 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007382 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007383 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007384 // with the register storage-class specifier.
7385 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007386 // in C++ it is not error to take address of a register
7387 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007388 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007389 !S.getLangOptions().CPlusPlus) {
7390 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007391 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007392 return QualType();
7393 }
John McCallba135432009-11-21 08:51:07 +00007394 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007395 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007396 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007397 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007398 // Could be a pointer to member, though, if there is an explicit
7399 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007400 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007401 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007402 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007403 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007404 S.Diag(OpLoc,
7405 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007406 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007407 return QualType();
7408 }
Mike Stump1eb44332009-09-09 15:08:12 +00007409
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007410 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7411 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007412 return S.Context.getMemberPointerType(op->getType(),
7413 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007414 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007415 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007416 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007417 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007418 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007419
Eli Friedman441cf102009-05-16 23:27:50 +00007420 if (lval == Expr::LV_IncompleteVoidType) {
7421 // Taking the address of a void variable is technically illegal, but we
7422 // allow it in cases which are otherwise valid.
7423 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007424 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007425 }
7426
Reid Spencer5f016e22007-07-11 17:01:13 +00007427 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007428 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007429 return S.Context.getObjCObjectPointerType(op->getType());
7430 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007431}
7432
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007433/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007434static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7435 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007436 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007437 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007438
John Wiegley429bb272011-04-08 18:41:53 +00007439 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7440 if (ConvResult.isInvalid())
7441 return QualType();
7442 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007443 QualType OpTy = Op->getType();
7444 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007445
7446 if (isa<CXXReinterpretCastExpr>(Op)) {
7447 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7448 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7449 Op->getSourceRange());
7450 }
7451
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007452 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7453 // is an incomplete type or void. It would be possible to warn about
7454 // dereferencing a void pointer, but it's completely well-defined, and such a
7455 // warning is unlikely to catch any mistakes.
7456 if (const PointerType *PT = OpTy->getAs<PointerType>())
7457 Result = PT->getPointeeType();
7458 else if (const ObjCObjectPointerType *OPT =
7459 OpTy->getAs<ObjCObjectPointerType>())
7460 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007461 else {
John McCallfb8721c2011-04-10 19:13:55 +00007462 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007463 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007464 if (PR.take() != Op)
7465 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007466 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007467
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007468 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007469 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007470 << OpTy << Op->getSourceRange();
7471 return QualType();
7472 }
John McCall09431682010-11-18 19:01:18 +00007473
7474 // Dereferences are usually l-values...
7475 VK = VK_LValue;
7476
7477 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007478 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007479 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007480
7481 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007482}
7483
John McCall2de56d12010-08-25 11:45:40 +00007484static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007485 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007486 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007487 switch (Kind) {
7488 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007489 case tok::periodstar: Opc = BO_PtrMemD; break;
7490 case tok::arrowstar: Opc = BO_PtrMemI; break;
7491 case tok::star: Opc = BO_Mul; break;
7492 case tok::slash: Opc = BO_Div; break;
7493 case tok::percent: Opc = BO_Rem; break;
7494 case tok::plus: Opc = BO_Add; break;
7495 case tok::minus: Opc = BO_Sub; break;
7496 case tok::lessless: Opc = BO_Shl; break;
7497 case tok::greatergreater: Opc = BO_Shr; break;
7498 case tok::lessequal: Opc = BO_LE; break;
7499 case tok::less: Opc = BO_LT; break;
7500 case tok::greaterequal: Opc = BO_GE; break;
7501 case tok::greater: Opc = BO_GT; break;
7502 case tok::exclaimequal: Opc = BO_NE; break;
7503 case tok::equalequal: Opc = BO_EQ; break;
7504 case tok::amp: Opc = BO_And; break;
7505 case tok::caret: Opc = BO_Xor; break;
7506 case tok::pipe: Opc = BO_Or; break;
7507 case tok::ampamp: Opc = BO_LAnd; break;
7508 case tok::pipepipe: Opc = BO_LOr; break;
7509 case tok::equal: Opc = BO_Assign; break;
7510 case tok::starequal: Opc = BO_MulAssign; break;
7511 case tok::slashequal: Opc = BO_DivAssign; break;
7512 case tok::percentequal: Opc = BO_RemAssign; break;
7513 case tok::plusequal: Opc = BO_AddAssign; break;
7514 case tok::minusequal: Opc = BO_SubAssign; break;
7515 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7516 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7517 case tok::ampequal: Opc = BO_AndAssign; break;
7518 case tok::caretequal: Opc = BO_XorAssign; break;
7519 case tok::pipeequal: Opc = BO_OrAssign; break;
7520 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007521 }
7522 return Opc;
7523}
7524
John McCall2de56d12010-08-25 11:45:40 +00007525static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007526 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007527 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007528 switch (Kind) {
7529 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007530 case tok::plusplus: Opc = UO_PreInc; break;
7531 case tok::minusminus: Opc = UO_PreDec; break;
7532 case tok::amp: Opc = UO_AddrOf; break;
7533 case tok::star: Opc = UO_Deref; break;
7534 case tok::plus: Opc = UO_Plus; break;
7535 case tok::minus: Opc = UO_Minus; break;
7536 case tok::tilde: Opc = UO_Not; break;
7537 case tok::exclaim: Opc = UO_LNot; break;
7538 case tok::kw___real: Opc = UO_Real; break;
7539 case tok::kw___imag: Opc = UO_Imag; break;
7540 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007541 }
7542 return Opc;
7543}
7544
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007545/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7546/// This warning is only emitted for builtin assignment operations. It is also
7547/// suppressed in the event of macro expansions.
7548static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7549 SourceLocation OpLoc) {
7550 if (!S.ActiveTemplateInstantiations.empty())
7551 return;
7552 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7553 return;
7554 lhs = lhs->IgnoreParenImpCasts();
7555 rhs = rhs->IgnoreParenImpCasts();
7556 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7557 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7558 if (!LeftDeclRef || !RightDeclRef ||
7559 LeftDeclRef->getLocation().isMacroID() ||
7560 RightDeclRef->getLocation().isMacroID())
7561 return;
7562 const ValueDecl *LeftDecl =
7563 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7564 const ValueDecl *RightDecl =
7565 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7566 if (LeftDecl != RightDecl)
7567 return;
7568 if (LeftDecl->getType().isVolatileQualified())
7569 return;
7570 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7571 if (RefTy->getPointeeType().isVolatileQualified())
7572 return;
7573
7574 S.Diag(OpLoc, diag::warn_self_assignment)
7575 << LeftDeclRef->getType()
7576 << lhs->getSourceRange() << rhs->getSourceRange();
7577}
7578
Douglas Gregoreaebc752008-11-06 23:29:22 +00007579/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7580/// operator @p Opc at location @c TokLoc. This routine only supports
7581/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007582ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007583 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007584 Expr *lhsExpr, Expr *rhsExpr) {
7585 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007586 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007587 // The following two variables are used for compound assignment operators
7588 QualType CompLHSTy; // Type of LHS after promotions for computation
7589 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007590 ExprValueKind VK = VK_RValue;
7591 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007592
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007593 // Check if a 'foo<int>' involved in a binary op, identifies a single
7594 // function unambiguously (i.e. an lvalue ala 13.4)
7595 // But since an assignment can trigger target based overload, exclude it in
7596 // our blind search. i.e:
7597 // template<class T> void f(); template<class T, class U> void f(U);
7598 // f<int> == 0; // resolve f<int> blindly
7599 // void (*p)(int); p = f<int>; // resolve f<int> using target
7600 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007601 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007602 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007603 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007604
John McCallfb8721c2011-04-10 19:13:55 +00007605 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007606 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007607 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007608 }
7609
Eli Friedmaned3b2562011-06-17 20:52:22 +00007610 // The canonical way to check for a GNU null is with isNullPointerConstant,
7611 // but we use a bit of a hack here for speed; this is a relatively
7612 // hot path, and isNullPointerConstant is slow.
7613 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7614 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu3e95ba92011-06-16 21:36:56 +00007615
7616 // Detect when a NULL constant is used improperly in an expression. These
7617 // are mainly cases where the null pointer is used as an integer instead
7618 // of a pointer.
7619 if (LeftNull || RightNull) {
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007620 // Avoid analyzing cases where the result will either be invalid (and
7621 // diagnosed as such) or entirely valid and not something to warn about.
7622 QualType LeftType = lhs.get()->getType();
7623 QualType RightType = rhs.get()->getType();
7624 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7625 !LeftType->isFunctionType() &&
7626 !RightType->isBlockPointerType() &&
7627 !RightType->isMemberPointerType() &&
7628 !RightType->isFunctionType()) {
7629 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7630 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7631 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7632 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7633 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7634 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7635 // These are the operations that would not make sense with a null pointer
Richard Trieu67e29332011-08-02 04:35:43 +00007636 // pointer no matter what the other expression is.
Chandler Carruth2af68e42011-06-19 09:05:14 +00007637 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007638 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7639 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7640 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7641 Opc == BO_EQ || Opc == BO_NE) {
7642 // These are the operations that would not make sense with a null pointer
7643 // if the other expression the other expression is not a pointer.
7644 if (LeftNull != RightNull &&
7645 !LeftType->isAnyPointerType() &&
7646 !LeftType->canDecayToPointerType() &&
7647 !RightType->isAnyPointerType() &&
7648 !RightType->canDecayToPointerType()) {
Richard Trieu79e610a2011-08-11 22:38:21 +00007649 Diag(OpLoc, diag::warn_null_in_comparison_operation)
7650 << LeftNull /* LHS is NULL */
7651 << (LeftNull ? rhs.get()->getType() : lhs.get()->getType())
7652 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007653 }
Richard Trieu3e95ba92011-06-16 21:36:56 +00007654 }
7655 }
7656 }
7657
Douglas Gregoreaebc752008-11-06 23:29:22 +00007658 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007659 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007660 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007661 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007662 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7663 VK = lhs.get()->getValueKind();
7664 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007665 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007666 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007667 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007668 break;
John McCall2de56d12010-08-25 11:45:40 +00007669 case BO_PtrMemD:
7670 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007671 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007672 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007673 break;
John McCall2de56d12010-08-25 11:45:40 +00007674 case BO_Mul:
7675 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007676 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007677 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007678 break;
John McCall2de56d12010-08-25 11:45:40 +00007679 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007680 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7681 break;
John McCall2de56d12010-08-25 11:45:40 +00007682 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007683 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7684 break;
John McCall2de56d12010-08-25 11:45:40 +00007685 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007686 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7687 break;
John McCall2de56d12010-08-25 11:45:40 +00007688 case BO_Shl:
7689 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007690 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007691 break;
John McCall2de56d12010-08-25 11:45:40 +00007692 case BO_LE:
7693 case BO_LT:
7694 case BO_GE:
7695 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007696 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007697 break;
John McCall2de56d12010-08-25 11:45:40 +00007698 case BO_EQ:
7699 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007700 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007701 break;
John McCall2de56d12010-08-25 11:45:40 +00007702 case BO_And:
7703 case BO_Xor:
7704 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007705 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7706 break;
John McCall2de56d12010-08-25 11:45:40 +00007707 case BO_LAnd:
7708 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007709 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007710 break;
John McCall2de56d12010-08-25 11:45:40 +00007711 case BO_MulAssign:
7712 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007713 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007714 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007715 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007716 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7717 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007718 break;
John McCall2de56d12010-08-25 11:45:40 +00007719 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007720 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7721 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007722 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7723 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007724 break;
John McCall2de56d12010-08-25 11:45:40 +00007725 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007726 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007727 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7728 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007729 break;
John McCall2de56d12010-08-25 11:45:40 +00007730 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007731 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
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_ShlAssign:
7736 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007737 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007738 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007739 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7740 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007741 break;
John McCall2de56d12010-08-25 11:45:40 +00007742 case BO_AndAssign:
7743 case BO_XorAssign:
7744 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007745 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7746 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007747 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7748 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007749 break;
John McCall2de56d12010-08-25 11:45:40 +00007750 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007751 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007752 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7753 VK = rhs.get()->getValueKind();
7754 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007755 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007756 break;
7757 }
John Wiegley429bb272011-04-08 18:41:53 +00007758 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007759 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007760
7761 // Check for array bounds violations for both sides of the BinaryOperator
7762 CheckArrayAccess(lhs.get());
7763 CheckArrayAccess(rhs.get());
7764
Eli Friedmanab3a8522009-03-28 01:22:36 +00007765 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007766 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7767 ResultTy, VK, OK, OpLoc));
Richard Trieu67e29332011-08-02 04:35:43 +00007768 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7769 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007770 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007771 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007772 }
John Wiegley429bb272011-04-08 18:41:53 +00007773 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7774 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007775 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007776}
7777
Sebastian Redlaee3c932009-10-27 12:10:02 +00007778/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7779/// operators are mixed in a way that suggests that the programmer forgot that
7780/// comparison operators have higher precedence. The most typical example of
7781/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007782static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007783 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007784 typedef BinaryOperator BinOp;
7785 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7786 rhsopc = static_cast<BinOp::Opcode>(-1);
7787 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007788 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007789 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007790 rhsopc = BO->getOpcode();
7791
7792 // Subs are not binary operators.
7793 if (lhsopc == -1 && rhsopc == -1)
7794 return;
7795
7796 // Bitwise operations are sometimes used as eager logical ops.
7797 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007798 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7799 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007800 return;
7801
Richard Trieu70979d42011-08-10 22:41:34 +00007802 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7803 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7804 if (!isLeftComp && !isRightComp) return;
7805
7806 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7807 : SourceRange(OpLoc, rhs->getLocEnd());
7808 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7809 : BinOp::getOpcodeStr(rhsopc);
7810 SourceRange ParensRange = isLeftComp ?
7811 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7812 rhs->getLocEnd())
7813 : SourceRange(lhs->getLocStart(),
7814 cast<BinOp>(rhs)->getLHS()->getLocStart());
7815
7816 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7817 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7818 SuggestParentheses(Self, OpLoc,
7819 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7820 rhs->getSourceRange());
7821 SuggestParentheses(Self, OpLoc,
7822 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7823 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007824}
7825
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007826/// \brief It accepts a '&' expr that is inside a '|' one.
7827/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7828/// in parentheses.
7829static void
7830EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7831 BinaryOperator *Bop) {
7832 assert(Bop->getOpcode() == BO_And);
7833 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7834 << Bop->getSourceRange() << OpLoc;
7835 SuggestParentheses(Self, Bop->getOperatorLoc(),
7836 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7837 Bop->getSourceRange());
7838}
7839
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007840/// \brief It accepts a '&&' expr that is inside a '||' one.
7841/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7842/// in parentheses.
7843static void
7844EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007845 BinaryOperator *Bop) {
7846 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007847 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7848 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007849 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007850 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007851 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007852}
7853
7854/// \brief Returns true if the given expression can be evaluated as a constant
7855/// 'true'.
7856static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7857 bool Res;
7858 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7859}
7860
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007861/// \brief Returns true if the given expression can be evaluated as a constant
7862/// 'false'.
7863static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7864 bool Res;
7865 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7866}
7867
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007868/// \brief Look for '&&' in the left hand of a '||' expr.
7869static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007870 Expr *OrLHS, Expr *OrRHS) {
7871 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007872 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007873 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7874 if (EvaluatesAsFalse(S, OrRHS))
7875 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007876 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7877 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7878 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7879 } else if (Bop->getOpcode() == BO_LOr) {
7880 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7881 // If it's "a || b && 1 || c" we didn't warn earlier for
7882 // "a || b && 1", but warn now.
7883 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7884 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7885 }
7886 }
7887 }
7888}
7889
7890/// \brief Look for '&&' in the right hand of a '||' expr.
7891static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007892 Expr *OrLHS, Expr *OrRHS) {
7893 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007894 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007895 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7896 if (EvaluatesAsFalse(S, OrLHS))
7897 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007898 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7899 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7900 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007901 }
7902 }
7903}
7904
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007905/// \brief Look for '&' in the left or right hand of a '|' expr.
7906static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7907 Expr *OrArg) {
7908 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7909 if (Bop->getOpcode() == BO_And)
7910 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7911 }
7912}
7913
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007914/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007915/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007916static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007917 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007918 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007919 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007920 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7921
7922 // Diagnose "arg1 & arg2 | arg3"
7923 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7924 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7925 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7926 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007927
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007928 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7929 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007930 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007931 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7932 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007933 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007934}
7935
Reid Spencer5f016e22007-07-11 17:01:13 +00007936// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007937ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007938 tok::TokenKind Kind,
7939 Expr *lhs, Expr *rhs) {
7940 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00007941 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7942 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007943
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007944 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7945 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7946
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007947 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7948}
7949
John McCall60d7b3a2010-08-24 06:29:42 +00007950ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007951 BinaryOperatorKind Opc,
7952 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00007953 if (getLangOptions().CPlusPlus) {
7954 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007955
John McCall01b2e4e2010-12-06 05:26:58 +00007956 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7957 UseBuiltinOperator = false;
7958 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7959 UseBuiltinOperator = true;
7960 } else {
7961 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7962 !rhs->getType()->isOverloadableType();
7963 }
7964
7965 if (!UseBuiltinOperator) {
7966 // Find all of the overloaded operators visible from this
7967 // point. We perform both an operator-name lookup from the local
7968 // scope and an argument-dependent lookup based on the types of
7969 // the arguments.
7970 UnresolvedSet<16> Functions;
7971 OverloadedOperatorKind OverOp
7972 = BinaryOperator::getOverloadedOperator(Opc);
7973 if (S && OverOp != OO_None)
7974 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7975 Functions);
7976
7977 // Build the (potentially-overloaded, potentially-dependent)
7978 // binary operation.
7979 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7980 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007981 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007982
Douglas Gregoreaebc752008-11-06 23:29:22 +00007983 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007984 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00007985}
7986
John McCall60d7b3a2010-08-24 06:29:42 +00007987ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007988 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007989 Expr *InputExpr) {
7990 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00007991 ExprValueKind VK = VK_RValue;
7992 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00007993 QualType resultType;
7994 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007995 case UO_PreInc:
7996 case UO_PreDec:
7997 case UO_PostInc:
7998 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00007999 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008000 Opc == UO_PreInc ||
8001 Opc == UO_PostInc,
8002 Opc == UO_PreInc ||
8003 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008004 break;
John McCall2de56d12010-08-25 11:45:40 +00008005 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008006 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008007 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008008 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008009 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008010 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008011 Input = move(resolved);
8012 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8013 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008014 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008015 }
John McCall2de56d12010-08-25 11:45:40 +00008016 case UO_Plus:
8017 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008018 Input = UsualUnaryConversions(Input.take());
8019 if (Input.isInvalid()) return ExprError();
8020 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008021 if (resultType->isDependentType())
8022 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008023 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8024 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008025 break;
8026 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8027 resultType->isEnumeralType())
8028 break;
8029 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008030 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008031 resultType->isPointerType())
8032 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008033 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008034 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008035 if (Input.isInvalid()) return ExprError();
8036 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008037 }
Douglas Gregor74253732008-11-19 15:42:04 +00008038
Sebastian Redl0eb23302009-01-19 00:08:26 +00008039 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008040 << resultType << Input.get()->getSourceRange());
8041
John McCall2de56d12010-08-25 11:45:40 +00008042 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008043 Input = UsualUnaryConversions(Input.take());
8044 if (Input.isInvalid()) return ExprError();
8045 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008046 if (resultType->isDependentType())
8047 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008048 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8049 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8050 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008051 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008052 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008053 else if (resultType->hasIntegerRepresentation())
8054 break;
8055 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008056 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008057 if (Input.isInvalid()) return ExprError();
8058 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008059 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008060 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008061 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008062 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008063 break;
John Wiegley429bb272011-04-08 18:41:53 +00008064
John McCall2de56d12010-08-25 11:45:40 +00008065 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008066 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008067 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8068 if (Input.isInvalid()) return ExprError();
8069 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008070 if (resultType->isDependentType())
8071 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008072 if (resultType->isScalarType()) {
8073 // C99 6.5.3.3p1: ok, fallthrough;
8074 if (Context.getLangOptions().CPlusPlus) {
8075 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8076 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008077 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8078 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008079 }
John McCall2cd11fe2010-10-12 02:09:17 +00008080 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008081 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008082 if (Input.isInvalid()) return ExprError();
8083 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008084 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008085 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008086 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008087 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008088
Reid Spencer5f016e22007-07-11 17:01:13 +00008089 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008090 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008091 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008092 break;
John McCall2de56d12010-08-25 11:45:40 +00008093 case UO_Real:
8094 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008095 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008096 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008097 if (Input.isInvalid()) return ExprError();
8098 if (Input.get()->getValueKind() != VK_RValue &&
8099 Input.get()->getObjectKind() == OK_Ordinary)
8100 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008101 break;
John McCall2de56d12010-08-25 11:45:40 +00008102 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008103 resultType = Input.get()->getType();
8104 VK = Input.get()->getValueKind();
8105 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008106 break;
8107 }
John Wiegley429bb272011-04-08 18:41:53 +00008108 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008109 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008110
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008111 // Check for array bounds violations in the operand of the UnaryOperator,
8112 // except for the '*' and '&' operators that have to be handled specially
8113 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8114 // that are explicitly defined as valid by the standard).
8115 if (Opc != UO_AddrOf && Opc != UO_Deref)
8116 CheckArrayAccess(Input.get());
8117
John Wiegley429bb272011-04-08 18:41:53 +00008118 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008119 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008120}
8121
John McCall60d7b3a2010-08-24 06:29:42 +00008122ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008123 UnaryOperatorKind Opc,
8124 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008125 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008126 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008127 // Find all of the overloaded operators visible from this
8128 // point. We perform both an operator-name lookup from the local
8129 // scope and an argument-dependent lookup based on the types of
8130 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008131 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008132 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008133 if (S && OverOp != OO_None)
8134 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8135 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008136
John McCall9ae2f072010-08-23 23:25:46 +00008137 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008138 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008139
John McCall9ae2f072010-08-23 23:25:46 +00008140 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008141}
8142
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008143// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008144ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008145 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008146 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008147}
8148
Steve Naroff1b273c42007-09-16 14:56:35 +00008149/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008150ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008151 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008152 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008153 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008154 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008155 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008156}
8157
John McCallf85e1932011-06-15 23:02:42 +00008158/// Given the last statement in a statement-expression, check whether
8159/// the result is a producing expression (like a call to an
8160/// ns_returns_retained function) and, if so, rebuild it to hoist the
8161/// release out of the full-expression. Otherwise, return null.
8162/// Cannot fail.
8163static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8164 // Should always be wrapped with one of these.
8165 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8166 if (!cleanups) return 0;
8167
8168 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8169 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8170 return 0;
8171
8172 // Splice out the cast. This shouldn't modify any interesting
8173 // features of the statement.
8174 Expr *producer = cast->getSubExpr();
8175 assert(producer->getType() == cast->getType());
8176 assert(producer->getValueKind() == cast->getValueKind());
8177 cleanups->setSubExpr(producer);
8178 return cleanups;
8179}
8180
John McCall60d7b3a2010-08-24 06:29:42 +00008181ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008182Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008183 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008184 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8185 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8186
Douglas Gregordd8f5692010-03-10 04:54:39 +00008187 bool isFileScope
8188 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008189 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008190 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008191
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008192 // FIXME: there are a variety of strange constraints to enforce here, for
8193 // example, it is not possible to goto into a stmt expression apparently.
8194 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008195
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008196 // If there are sub stmts in the compound stmt, take the type of the last one
8197 // as the type of the stmtexpr.
8198 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008199 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008200 if (!Compound->body_empty()) {
8201 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008202 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008203 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008204 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8205 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008206 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008207 }
John McCallf85e1932011-06-15 23:02:42 +00008208
John Wiegley429bb272011-04-08 18:41:53 +00008209 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008210 // Do function/array conversion on the last expression, but not
8211 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008212 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8213 if (LastExpr.isInvalid())
8214 return ExprError();
8215 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008216
John Wiegley429bb272011-04-08 18:41:53 +00008217 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008218 // In ARC, if the final expression ends in a consume, splice
8219 // the consume out and bind it later. In the alternate case
8220 // (when dealing with a retainable type), the result
8221 // initialization will create a produce. In both cases the
8222 // result will be +1, and we'll need to balance that out with
8223 // a bind.
8224 if (Expr *rebuiltLastStmt
8225 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8226 LastExpr = rebuiltLastStmt;
8227 } else {
8228 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008229 InitializedEntity::InitializeResult(LPLoc,
8230 Ty,
8231 false),
8232 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008233 LastExpr);
8234 }
8235
John Wiegley429bb272011-04-08 18:41:53 +00008236 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008237 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008238 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008239 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008240 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008241 else
John Wiegley429bb272011-04-08 18:41:53 +00008242 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008243 StmtExprMayBindToTemp = true;
8244 }
8245 }
8246 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008247 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008248
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008249 // FIXME: Check that expression type is complete/non-abstract; statement
8250 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008251 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8252 if (StmtExprMayBindToTemp)
8253 return MaybeBindToTemporary(ResStmtExpr);
8254 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008255}
Steve Naroffd34e9152007-08-01 22:05:33 +00008256
John McCall60d7b3a2010-08-24 06:29:42 +00008257ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008258 TypeSourceInfo *TInfo,
8259 OffsetOfComponent *CompPtr,
8260 unsigned NumComponents,
8261 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008262 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008263 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008264 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008265
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008266 // We must have at least one component that refers to the type, and the first
8267 // one is known to be a field designator. Verify that the ArgTy represents
8268 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008269 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008270 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8271 << ArgTy << TypeRange);
8272
8273 // Type must be complete per C99 7.17p3 because a declaring a variable
8274 // with an incomplete type would be ill-formed.
8275 if (!Dependent
8276 && RequireCompleteType(BuiltinLoc, ArgTy,
8277 PDiag(diag::err_offsetof_incomplete_type)
8278 << TypeRange))
8279 return ExprError();
8280
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008281 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8282 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008283 // FIXME: This diagnostic isn't actually visible because the location is in
8284 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008285 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008286 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8287 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008288
8289 bool DidWarnAboutNonPOD = false;
8290 QualType CurrentType = ArgTy;
8291 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008292 SmallVector<OffsetOfNode, 4> Comps;
8293 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008294 for (unsigned i = 0; i != NumComponents; ++i) {
8295 const OffsetOfComponent &OC = CompPtr[i];
8296 if (OC.isBrackets) {
8297 // Offset of an array sub-field. TODO: Should we allow vector elements?
8298 if (!CurrentType->isDependentType()) {
8299 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8300 if(!AT)
8301 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8302 << CurrentType);
8303 CurrentType = AT->getElementType();
8304 } else
8305 CurrentType = Context.DependentTy;
8306
8307 // The expression must be an integral expression.
8308 // FIXME: An integral constant expression?
8309 Expr *Idx = static_cast<Expr*>(OC.U.E);
8310 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8311 !Idx->getType()->isIntegerType())
8312 return ExprError(Diag(Idx->getLocStart(),
8313 diag::err_typecheck_subscript_not_integer)
8314 << Idx->getSourceRange());
8315
8316 // Record this array index.
8317 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8318 Exprs.push_back(Idx);
8319 continue;
8320 }
8321
8322 // Offset of a field.
8323 if (CurrentType->isDependentType()) {
8324 // We have the offset of a field, but we can't look into the dependent
8325 // type. Just record the identifier of the field.
8326 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8327 CurrentType = Context.DependentTy;
8328 continue;
8329 }
8330
8331 // We need to have a complete type to look into.
8332 if (RequireCompleteType(OC.LocStart, CurrentType,
8333 diag::err_offsetof_incomplete_type))
8334 return ExprError();
8335
8336 // Look for the designated field.
8337 const RecordType *RC = CurrentType->getAs<RecordType>();
8338 if (!RC)
8339 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8340 << CurrentType);
8341 RecordDecl *RD = RC->getDecl();
8342
8343 // C++ [lib.support.types]p5:
8344 // The macro offsetof accepts a restricted set of type arguments in this
8345 // International Standard. type shall be a POD structure or a POD union
8346 // (clause 9).
8347 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8348 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008349 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008350 PDiag(diag::warn_offsetof_non_pod_type)
8351 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8352 << CurrentType))
8353 DidWarnAboutNonPOD = true;
8354 }
8355
8356 // Look for the field.
8357 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8358 LookupQualifiedName(R, RD);
8359 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008360 IndirectFieldDecl *IndirectMemberDecl = 0;
8361 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008362 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008363 MemberDecl = IndirectMemberDecl->getAnonField();
8364 }
8365
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008366 if (!MemberDecl)
8367 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8368 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8369 OC.LocEnd));
8370
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008371 // C99 7.17p3:
8372 // (If the specified member is a bit-field, the behavior is undefined.)
8373 //
8374 // We diagnose this as an error.
8375 if (MemberDecl->getBitWidth()) {
8376 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8377 << MemberDecl->getDeclName()
8378 << SourceRange(BuiltinLoc, RParenLoc);
8379 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8380 return ExprError();
8381 }
Eli Friedman19410a72010-08-05 10:11:36 +00008382
8383 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008384 if (IndirectMemberDecl)
8385 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008386
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008387 // If the member was found in a base class, introduce OffsetOfNodes for
8388 // the base class indirections.
8389 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8390 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008391 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008392 CXXBasePath &Path = Paths.front();
8393 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8394 B != BEnd; ++B)
8395 Comps.push_back(OffsetOfNode(B->Base));
8396 }
Eli Friedman19410a72010-08-05 10:11:36 +00008397
Francois Pichet87c2e122010-11-21 06:08:52 +00008398 if (IndirectMemberDecl) {
8399 for (IndirectFieldDecl::chain_iterator FI =
8400 IndirectMemberDecl->chain_begin(),
8401 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8402 assert(isa<FieldDecl>(*FI));
8403 Comps.push_back(OffsetOfNode(OC.LocStart,
8404 cast<FieldDecl>(*FI), OC.LocEnd));
8405 }
8406 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008407 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008408
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008409 CurrentType = MemberDecl->getType().getNonReferenceType();
8410 }
8411
8412 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8413 TInfo, Comps.data(), Comps.size(),
8414 Exprs.data(), Exprs.size(), RParenLoc));
8415}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008416
John McCall60d7b3a2010-08-24 06:29:42 +00008417ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008418 SourceLocation BuiltinLoc,
8419 SourceLocation TypeLoc,
8420 ParsedType argty,
8421 OffsetOfComponent *CompPtr,
8422 unsigned NumComponents,
8423 SourceLocation RPLoc) {
8424
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008425 TypeSourceInfo *ArgTInfo;
8426 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8427 if (ArgTy.isNull())
8428 return ExprError();
8429
Eli Friedman5a15dc12010-08-05 10:15:45 +00008430 if (!ArgTInfo)
8431 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8432
8433 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8434 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008435}
8436
8437
John McCall60d7b3a2010-08-24 06:29:42 +00008438ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008439 Expr *CondExpr,
8440 Expr *LHSExpr, Expr *RHSExpr,
8441 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008442 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8443
John McCallf89e55a2010-11-18 06:31:45 +00008444 ExprValueKind VK = VK_RValue;
8445 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008446 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008447 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008448 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008449 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008450 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008451 } else {
8452 // The conditional expression is required to be a constant expression.
8453 llvm::APSInt condEval(32);
8454 SourceLocation ExpLoc;
8455 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008456 return ExprError(Diag(ExpLoc,
8457 diag::err_typecheck_choose_expr_requires_constant)
8458 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008459
Sebastian Redl28507842009-02-26 14:39:58 +00008460 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008461 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8462
8463 resType = ActiveExpr->getType();
8464 ValueDependent = ActiveExpr->isValueDependent();
8465 VK = ActiveExpr->getValueKind();
8466 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008467 }
8468
Sebastian Redlf53597f2009-03-15 17:47:39 +00008469 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008470 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008471 resType->isDependentType(),
8472 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008473}
8474
Steve Naroff4eb206b2008-09-03 18:15:37 +00008475//===----------------------------------------------------------------------===//
8476// Clang Extensions.
8477//===----------------------------------------------------------------------===//
8478
8479/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008480void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008481 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8482 PushBlockScope(BlockScope, Block);
8483 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008484 if (BlockScope)
8485 PushDeclContext(BlockScope, Block);
8486 else
8487 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008488}
8489
Mike Stump98eb8a72009-02-04 22:31:32 +00008490void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008491 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008492 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008493 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008494
John McCallbf1a0282010-06-04 23:28:52 +00008495 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008496 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008497
John McCall711c52b2011-01-05 12:14:39 +00008498 // GetTypeForDeclarator always produces a function type for a block
8499 // literal signature. Furthermore, it is always a FunctionProtoType
8500 // unless the function was written with a typedef.
8501 assert(T->isFunctionType() &&
8502 "GetTypeForDeclarator made a non-function block signature");
8503
8504 // Look for an explicit signature in that function type.
8505 FunctionProtoTypeLoc ExplicitSignature;
8506
8507 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8508 if (isa<FunctionProtoTypeLoc>(tmp)) {
8509 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8510
8511 // Check whether that explicit signature was synthesized by
8512 // GetTypeForDeclarator. If so, don't save that as part of the
8513 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008514 if (ExplicitSignature.getLocalRangeBegin() ==
8515 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008516 // This would be much cheaper if we stored TypeLocs instead of
8517 // TypeSourceInfos.
8518 TypeLoc Result = ExplicitSignature.getResultLoc();
8519 unsigned Size = Result.getFullDataSize();
8520 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8521 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8522
8523 ExplicitSignature = FunctionProtoTypeLoc();
8524 }
John McCall82dc0092010-06-04 11:21:44 +00008525 }
Mike Stump1eb44332009-09-09 15:08:12 +00008526
John McCall711c52b2011-01-05 12:14:39 +00008527 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8528 CurBlock->FunctionType = T;
8529
8530 const FunctionType *Fn = T->getAs<FunctionType>();
8531 QualType RetTy = Fn->getResultType();
8532 bool isVariadic =
8533 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8534
John McCallc71a4912010-06-04 19:02:56 +00008535 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008536
John McCall82dc0092010-06-04 11:21:44 +00008537 // Don't allow returning a objc interface by value.
8538 if (RetTy->isObjCObjectType()) {
8539 Diag(ParamInfo.getSourceRange().getBegin(),
8540 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8541 return;
8542 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008543
John McCall82dc0092010-06-04 11:21:44 +00008544 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008545 // return type. TODO: what should we do with declarators like:
8546 // ^ * { ... }
8547 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008548 if (RetTy != Context.DependentTy)
8549 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008550
John McCall82dc0092010-06-04 11:21:44 +00008551 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008552 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008553 if (ExplicitSignature) {
8554 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8555 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008556 if (Param->getIdentifier() == 0 &&
8557 !Param->isImplicit() &&
8558 !Param->isInvalidDecl() &&
8559 !getLangOptions().CPlusPlus)
8560 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008561 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008562 }
John McCall82dc0092010-06-04 11:21:44 +00008563
8564 // Fake up parameter variables if we have a typedef, like
8565 // ^ fntype { ... }
8566 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8567 for (FunctionProtoType::arg_type_iterator
8568 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8569 ParmVarDecl *Param =
8570 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8571 ParamInfo.getSourceRange().getBegin(),
8572 *I);
John McCallc71a4912010-06-04 19:02:56 +00008573 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008574 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008575 }
John McCall82dc0092010-06-04 11:21:44 +00008576
John McCallc71a4912010-06-04 19:02:56 +00008577 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008578 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008579 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008580 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8581 CurBlock->TheDecl->param_end(),
8582 /*CheckParameterNames=*/false);
8583 }
8584
John McCall82dc0092010-06-04 11:21:44 +00008585 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008586 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008587
John McCallc71a4912010-06-04 19:02:56 +00008588 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008589 Diag(ParamInfo.getAttributes()->getLoc(),
8590 diag::warn_attribute_sentinel_not_variadic) << 1;
8591 // FIXME: remove the attribute.
8592 }
8593
8594 // Put the parameter variables in scope. We can bail out immediately
8595 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008596 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008597 return;
8598
Steve Naroff090276f2008-10-10 01:28:17 +00008599 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008600 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8601 (*AI)->setOwningFunction(CurBlock->TheDecl);
8602
Steve Naroff090276f2008-10-10 01:28:17 +00008603 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008604 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008605 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008606
Steve Naroff090276f2008-10-10 01:28:17 +00008607 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008608 }
John McCall7a9813c2010-01-22 00:28:27 +00008609 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008610}
8611
8612/// ActOnBlockError - If there is an error parsing a block, this callback
8613/// is invoked to pop the information about the block from the action impl.
8614void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008615 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008616 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008617 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008618}
8619
8620/// ActOnBlockStmtExpr - This is called when the body of a block statement
8621/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008622ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008623 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008624 // If blocks are disabled, emit an error.
8625 if (!LangOpts.Blocks)
8626 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008627
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008628 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008629
Steve Naroff090276f2008-10-10 01:28:17 +00008630 PopDeclContext();
8631
Steve Naroff4eb206b2008-09-03 18:15:37 +00008632 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008633 if (!BSI->ReturnType.isNull())
8634 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008635
Mike Stump56925862009-07-28 22:04:01 +00008636 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008637 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008638
John McCall469a1eb2011-02-02 13:00:07 +00008639 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008640 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8641 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008642
John McCallc71a4912010-06-04 19:02:56 +00008643 // If the user wrote a function type in some form, try to use that.
8644 if (!BSI->FunctionType.isNull()) {
8645 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8646
8647 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8648 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8649
8650 // Turn protoless block types into nullary block types.
8651 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008652 FunctionProtoType::ExtProtoInfo EPI;
8653 EPI.ExtInfo = Ext;
8654 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008655
8656 // Otherwise, if we don't need to change anything about the function type,
8657 // preserve its sugar structure.
8658 } else if (FTy->getResultType() == RetTy &&
8659 (!NoReturn || FTy->getNoReturnAttr())) {
8660 BlockTy = BSI->FunctionType;
8661
8662 // Otherwise, make the minimal modifications to the function type.
8663 } else {
8664 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008665 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8666 EPI.TypeQuals = 0; // FIXME: silently?
8667 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008668 BlockTy = Context.getFunctionType(RetTy,
8669 FPT->arg_type_begin(),
8670 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008671 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008672 }
8673
8674 // If we don't have a function type, just build one from nothing.
8675 } else {
John McCalle23cf432010-12-14 08:05:40 +00008676 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008677 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008678 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008679 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008680
John McCallc71a4912010-06-04 19:02:56 +00008681 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8682 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008683 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008684
Chris Lattner17a78302009-04-19 05:28:12 +00008685 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008686 if (getCurFunction()->NeedsScopeChecking() &&
8687 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008688 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008689
Chris Lattnere476bdc2011-02-17 23:58:47 +00008690 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008691
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008692 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8693 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8694 const VarDecl *variable = ci->getVariable();
8695 QualType T = variable->getType();
8696 QualType::DestructionKind destructKind = T.isDestructedType();
8697 if (destructKind != QualType::DK_none)
8698 getCurFunction()->setHasBranchProtectedScope();
8699 }
8700
Benjamin Kramerd2486192011-07-12 14:11:05 +00008701 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8702 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8703 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8704
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008705 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008706}
8707
John McCall60d7b3a2010-08-24 06:29:42 +00008708ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008709 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008710 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008711 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008712 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008713 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008714}
8715
John McCall60d7b3a2010-08-24 06:29:42 +00008716ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008717 Expr *E, TypeSourceInfo *TInfo,
8718 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008719 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008720
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008721 // Get the va_list type
8722 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008723 if (VaListType->isArrayType()) {
8724 // Deal with implicit array decay; for example, on x86-64,
8725 // va_list is an array, but it's supposed to decay to
8726 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008727 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008728 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008729 ExprResult Result = UsualUnaryConversions(E);
8730 if (Result.isInvalid())
8731 return ExprError();
8732 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008733 } else {
8734 // Otherwise, the va_list argument must be an l-value because
8735 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008736 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008737 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008738 return ExprError();
8739 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008740
Douglas Gregordd027302009-05-19 23:10:31 +00008741 if (!E->isTypeDependent() &&
8742 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008743 return ExprError(Diag(E->getLocStart(),
8744 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008745 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008746 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008747
David Majnemer0adde122011-06-14 05:17:32 +00008748 if (!TInfo->getType()->isDependentType()) {
8749 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8750 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8751 << TInfo->getTypeLoc().getSourceRange()))
8752 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008753
David Majnemer0adde122011-06-14 05:17:32 +00008754 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8755 TInfo->getType(),
8756 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8757 << TInfo->getTypeLoc().getSourceRange()))
8758 return ExprError();
8759
Douglas Gregor4eb75222011-07-30 06:45:27 +00008760 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008761 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008762 TInfo->getType()->isObjCLifetimeType()
8763 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8764 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008765 << TInfo->getType()
8766 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008767 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008768
8769 // Check for va_arg where arguments of the given type will be promoted
8770 // (i.e. this va_arg is guaranteed to have undefined behavior).
8771 QualType PromoteType;
8772 if (TInfo->getType()->isPromotableIntegerType()) {
8773 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8774 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8775 PromoteType = QualType();
8776 }
8777 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8778 PromoteType = Context.DoubleTy;
8779 if (!PromoteType.isNull())
8780 Diag(TInfo->getTypeLoc().getBeginLoc(),
8781 diag::warn_second_parameter_to_va_arg_never_compatible)
8782 << TInfo->getType()
8783 << PromoteType
8784 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008785 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008786
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008787 QualType T = TInfo->getType().getNonLValueExprType(Context);
8788 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008789}
8790
John McCall60d7b3a2010-08-24 06:29:42 +00008791ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008792 // The type of __null will be int or long, depending on the size of
8793 // pointers on the target.
8794 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008795 unsigned pw = Context.Target.getPointerWidth(0);
8796 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008797 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008798 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008799 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008800 else if (pw == Context.Target.getLongLongWidth())
8801 Ty = Context.LongLongTy;
8802 else {
8803 assert(!"I don't know size of pointer!");
8804 Ty = Context.IntTy;
8805 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008806
Sebastian Redlf53597f2009-03-15 17:47:39 +00008807 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008808}
8809
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008810static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008811 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008812 if (!SemaRef.getLangOptions().ObjC1)
8813 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008814
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008815 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8816 if (!PT)
8817 return;
8818
8819 // Check if the destination is of type 'id'.
8820 if (!PT->isObjCIdType()) {
8821 // Check if the destination is the 'NSString' interface.
8822 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8823 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8824 return;
8825 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008826
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008827 // Strip off any parens and casts.
8828 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008829 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008830 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008831
Douglas Gregor849b2432010-03-31 17:46:05 +00008832 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008833}
8834
Chris Lattner5cf216b2008-01-04 18:04:52 +00008835bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8836 SourceLocation Loc,
8837 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008838 Expr *SrcExpr, AssignmentAction Action,
8839 bool *Complained) {
8840 if (Complained)
8841 *Complained = false;
8842
Chris Lattner5cf216b2008-01-04 18:04:52 +00008843 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008844 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008845 bool isInvalid = false;
8846 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008847 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008848 ConversionFixItGenerator ConvHints;
8849 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008850
Chris Lattner5cf216b2008-01-04 18:04:52 +00008851 switch (ConvTy) {
8852 default: assert(0 && "Unknown conversion type");
8853 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008854 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008855 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008856 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8857 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008858 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008859 case IntToPointer:
8860 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008861 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8862 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008863 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008864 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008865 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008866 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008867 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8868 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008869 if (Hint.isNull() && !CheckInferredResultType) {
8870 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8871 }
8872 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008873 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008874 case IncompatiblePointerSign:
8875 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8876 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008877 case FunctionVoidPointer:
8878 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8879 break;
John McCall86c05f32011-02-01 00:10:29 +00008880 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008881 // Perform array-to-pointer decay if necessary.
8882 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8883
John McCall86c05f32011-02-01 00:10:29 +00008884 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8885 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8886 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8887 DiagKind = diag::err_typecheck_incompatible_address_space;
8888 break;
John McCallf85e1932011-06-15 23:02:42 +00008889
8890
8891 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008892 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008893 break;
John McCall86c05f32011-02-01 00:10:29 +00008894 }
8895
8896 llvm_unreachable("unknown error case for discarding qualifiers!");
8897 // fallthrough
8898 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008899 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008900 // If the qualifiers lost were because we were applying the
8901 // (deprecated) C++ conversion from a string literal to a char*
8902 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8903 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008904 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008905 // bit of refactoring (so that the second argument is an
8906 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008907 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008908 // C++ semantics.
8909 if (getLangOptions().CPlusPlus &&
8910 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8911 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008912 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8913 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008914 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008915 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008916 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008917 case IntToBlockPointer:
8918 DiagKind = diag::err_int_to_block_pointer;
8919 break;
8920 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008921 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008922 break;
Steve Naroff39579072008-10-14 22:18:38 +00008923 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008924 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008925 // it can give a more specific diagnostic.
8926 DiagKind = diag::warn_incompatible_qualified_id;
8927 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008928 case IncompatibleVectors:
8929 DiagKind = diag::warn_incompatible_vectors;
8930 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00008931 case IncompatibleObjCWeakRef:
8932 DiagKind = diag::err_arc_weak_unavailable_assign;
8933 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008934 case Incompatible:
8935 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00008936 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8937 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008938 isInvalid = true;
8939 break;
8940 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008941
Douglas Gregord4eea832010-04-09 00:35:39 +00008942 QualType FirstType, SecondType;
8943 switch (Action) {
8944 case AA_Assigning:
8945 case AA_Initializing:
8946 // The destination type comes first.
8947 FirstType = DstType;
8948 SecondType = SrcType;
8949 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008950
Douglas Gregord4eea832010-04-09 00:35:39 +00008951 case AA_Returning:
8952 case AA_Passing:
8953 case AA_Converting:
8954 case AA_Sending:
8955 case AA_Casting:
8956 // The source type comes first.
8957 FirstType = SrcType;
8958 SecondType = DstType;
8959 break;
8960 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008961
Anna Zaks67221552011-07-28 19:51:27 +00008962 PartialDiagnostic FDiag = PDiag(DiagKind);
8963 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8964
8965 // If we can fix the conversion, suggest the FixIts.
8966 assert(ConvHints.isNull() || Hint.isNull());
8967 if (!ConvHints.isNull()) {
8968 for (llvm::SmallVector<FixItHint, 1>::iterator
8969 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8970 HI != HE; ++HI)
8971 FDiag << *HI;
8972 } else {
8973 FDiag << Hint;
8974 }
8975 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8976
8977 Diag(Loc, FDiag);
8978
Douglas Gregor926df6c2011-06-11 01:09:30 +00008979 if (CheckInferredResultType)
8980 EmitRelatedResultTypeNote(SrcExpr);
8981
Douglas Gregora41a8c52010-04-22 00:20:18 +00008982 if (Complained)
8983 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008984 return isInvalid;
8985}
Anders Carlssone21555e2008-11-30 19:50:32 +00008986
Chris Lattner3bf68932009-04-25 21:59:05 +00008987bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008988 llvm::APSInt ICEResult;
8989 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8990 if (Result)
8991 *Result = ICEResult;
8992 return false;
8993 }
8994
Anders Carlssone21555e2008-11-30 19:50:32 +00008995 Expr::EvalResult EvalResult;
8996
Mike Stumpeed9cac2009-02-19 03:04:26 +00008997 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00008998 EvalResult.HasSideEffects) {
8999 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9000
9001 if (EvalResult.Diag) {
9002 // We only show the note if it's not the usual "invalid subexpression"
9003 // or if it's actually in a subexpression.
9004 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9005 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9006 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9007 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009008
Anders Carlssone21555e2008-11-30 19:50:32 +00009009 return true;
9010 }
9011
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009012 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9013 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009014
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009015 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009016 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9017 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009018 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009019
Anders Carlssone21555e2008-11-30 19:50:32 +00009020 if (Result)
9021 *Result = EvalResult.Val.getInt();
9022 return false;
9023}
Douglas Gregore0762c92009-06-19 23:52:42 +00009024
Douglas Gregor2afce722009-11-26 00:44:06 +00009025void
Mike Stump1eb44332009-09-09 15:08:12 +00009026Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009027 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009028 ExpressionEvaluationContextRecord(NewContext,
9029 ExprTemporaries.size(),
9030 ExprNeedsCleanups));
9031 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009032}
9033
Richard Trieu67e29332011-08-02 04:35:43 +00009034void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009035 // Pop the current expression evaluation context off the stack.
9036 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9037 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009038
Douglas Gregor06d33692009-12-12 07:57:52 +00009039 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9040 if (Rec.PotentiallyReferenced) {
9041 // Mark any remaining declarations in the current position of the stack
9042 // as "referenced". If they were not meant to be referenced, semantic
9043 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009044 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009045 I = Rec.PotentiallyReferenced->begin(),
9046 IEnd = Rec.PotentiallyReferenced->end();
9047 I != IEnd; ++I)
9048 MarkDeclarationReferenced(I->first, I->second);
9049 }
9050
9051 if (Rec.PotentiallyDiagnosed) {
9052 // Emit any pending diagnostics.
9053 for (PotentiallyEmittedDiagnostics::iterator
9054 I = Rec.PotentiallyDiagnosed->begin(),
9055 IEnd = Rec.PotentiallyDiagnosed->end();
9056 I != IEnd; ++I)
9057 Diag(I->first, I->second);
9058 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009059 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009060
9061 // When are coming out of an unevaluated context, clear out any
9062 // temporaries that we may have created as part of the evaluation of
9063 // the expression in that context: they aren't relevant because they
9064 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009065 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009066 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9067 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009068 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9069
9070 // Otherwise, merge the contexts together.
9071 } else {
9072 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9073 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009074
9075 // Destroy the popped expression evaluation record.
9076 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009077}
Douglas Gregore0762c92009-06-19 23:52:42 +00009078
John McCallf85e1932011-06-15 23:02:42 +00009079void Sema::DiscardCleanupsInEvaluationContext() {
9080 ExprTemporaries.erase(
9081 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9082 ExprTemporaries.end());
9083 ExprNeedsCleanups = false;
9084}
9085
Douglas Gregore0762c92009-06-19 23:52:42 +00009086/// \brief Note that the given declaration was referenced in the source code.
9087///
9088/// This routine should be invoke whenever a given declaration is referenced
9089/// in the source code, and where that reference occurred. If this declaration
9090/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9091/// C99 6.9p3), then the declaration will be marked as used.
9092///
9093/// \param Loc the location where the declaration was referenced.
9094///
9095/// \param D the declaration that has been referenced by the source code.
9096void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9097 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009098
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009099 D->setReferenced();
9100
Douglas Gregorc070cc62010-06-17 23:14:26 +00009101 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009102 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009103
Richard Trieu67e29332011-08-02 04:35:43 +00009104 // Mark a parameter or variable declaration "used", regardless of whether
9105 // we're in a template or not. The reason for this is that unevaluated
9106 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9107 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009108 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009109 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009110 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009111 return;
9112 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009113
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009114 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9115 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009116
Douglas Gregore0762c92009-06-19 23:52:42 +00009117 // Do not mark anything as "used" within a dependent context; wait for
9118 // an instantiation.
9119 if (CurContext->isDependentContext())
9120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009121
Douglas Gregor2afce722009-11-26 00:44:06 +00009122 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009123 case Unevaluated:
9124 // We are in an expression that is not potentially evaluated; do nothing.
9125 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009126
Douglas Gregorac7610d2009-06-22 20:57:11 +00009127 case PotentiallyEvaluated:
9128 // We are in a potentially-evaluated expression, so this declaration is
9129 // "used"; handle this below.
9130 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009131
Douglas Gregorac7610d2009-06-22 20:57:11 +00009132 case PotentiallyPotentiallyEvaluated:
9133 // We are in an expression that may be potentially evaluated; queue this
9134 // declaration reference until we know whether the expression is
9135 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009136 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009137 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009138
9139 case PotentiallyEvaluatedIfUsed:
9140 // Referenced declarations will only be used if the construct in the
9141 // containing expression is used.
9142 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009143 }
Mike Stump1eb44332009-09-09 15:08:12 +00009144
Douglas Gregore0762c92009-06-19 23:52:42 +00009145 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009146 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +00009147 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9148 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009149 return;
9150 if (!Constructor->isUsed(false))
9151 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +00009152 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +00009153 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009154 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +00009155 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009156 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009157
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009158 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009159 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009160 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009161 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009162 if (Destructor->isVirtual())
9163 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009164 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009165 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009166 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009167 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009168 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009169 } else if (MethodDecl->isVirtual())
9170 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009171 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009172 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009173 // Recursive functions should be marked when used from another function.
9174 if (CurContext == Function) return;
9175
Mike Stump1eb44332009-09-09 15:08:12 +00009176 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009177 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009178 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009179 bool AlreadyInstantiated = false;
9180 if (FunctionTemplateSpecializationInfo *SpecInfo
9181 = Function->getTemplateSpecializationInfo()) {
9182 if (SpecInfo->getPointOfInstantiation().isInvalid())
9183 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009184 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009185 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009186 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009187 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009188 = Function->getMemberSpecializationInfo()) {
9189 if (MSInfo->getPointOfInstantiation().isInvalid())
9190 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009191 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009192 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009193 AlreadyInstantiated = true;
9194 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009195
Douglas Gregor60406be2010-01-16 22:29:39 +00009196 if (!AlreadyInstantiated) {
9197 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9198 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9199 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9200 Loc));
9201 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009202 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009203 }
John McCall15e310a2011-02-19 02:53:41 +00009204 } else {
9205 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009206 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9207 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009208 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009209 MarkDeclarationReferenced(Loc, *i);
9210 }
John McCall15e310a2011-02-19 02:53:41 +00009211 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009212
John McCall15e310a2011-02-19 02:53:41 +00009213 // Keep track of used but undefined functions.
9214 if (!Function->isPure() && !Function->hasBody() &&
9215 Function->getLinkage() != ExternalLinkage) {
9216 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9217 if (old.isInvalid()) old = Loc;
9218 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009219
John McCall15e310a2011-02-19 02:53:41 +00009220 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009221 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009222 }
Mike Stump1eb44332009-09-09 15:08:12 +00009223
Douglas Gregore0762c92009-06-19 23:52:42 +00009224 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009225 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009226 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009227 Var->getInstantiatedFromStaticDataMember()) {
9228 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9229 assert(MSInfo && "Missing member specialization information?");
9230 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9231 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9232 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009233 // This is a modification of an existing AST node. Notify listeners.
9234 if (ASTMutationListener *L = getASTMutationListener())
9235 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009236 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009237 }
9238 }
Mike Stump1eb44332009-09-09 15:08:12 +00009239
John McCall77efc682011-02-21 19:25:48 +00009240 // Keep track of used but undefined variables. We make a hole in
9241 // the warning for static const data members with in-line
9242 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009243 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009244 && Var->getLinkage() != ExternalLinkage
9245 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009246 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9247 if (old.isInvalid()) old = Loc;
9248 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009249
Douglas Gregore0762c92009-06-19 23:52:42 +00009250 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009251 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009252 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009253}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009254
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009255namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009256 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009257 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009258 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009259 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9260 Sema &S;
9261 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009262
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009263 public:
9264 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009265
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009266 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009267
9268 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9269 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009270 };
9271}
9272
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009273bool MarkReferencedDecls::TraverseTemplateArgument(
9274 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009275 if (Arg.getKind() == TemplateArgument::Declaration) {
9276 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9277 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009278
9279 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009280}
9281
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009282bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009283 if (ClassTemplateSpecializationDecl *Spec
9284 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9285 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009286 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009287 }
9288
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009289 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009290}
9291
9292void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9293 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009294 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009295}
9296
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009297namespace {
9298 /// \brief Helper class that marks all of the declarations referenced by
9299 /// potentially-evaluated subexpressions as "referenced".
9300 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9301 Sema &S;
9302
9303 public:
9304 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9305
9306 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9307
9308 void VisitDeclRefExpr(DeclRefExpr *E) {
9309 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9310 }
9311
9312 void VisitMemberExpr(MemberExpr *E) {
9313 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009314 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009315 }
9316
9317 void VisitCXXNewExpr(CXXNewExpr *E) {
9318 if (E->getConstructor())
9319 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9320 if (E->getOperatorNew())
9321 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9322 if (E->getOperatorDelete())
9323 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009324 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009325 }
9326
9327 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9328 if (E->getOperatorDelete())
9329 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009330 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9331 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9332 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9333 S.MarkDeclarationReferenced(E->getLocStart(),
9334 S.LookupDestructor(Record));
9335 }
9336
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009337 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009338 }
9339
9340 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9341 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009342 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009343 }
9344
9345 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9346 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9347 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009348
9349 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9350 Visit(E->getExpr());
9351 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009352 };
9353}
9354
9355/// \brief Mark any declarations that appear within this expression or any
9356/// potentially-evaluated subexpressions as "referenced".
9357void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9358 EvaluatedExprMarker(*this).Visit(E);
9359}
9360
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009361/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9362/// of the program being compiled.
9363///
9364/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009365/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009366/// possibility that the code will actually be executable. Code in sizeof()
9367/// expressions, code used only during overload resolution, etc., are not
9368/// potentially evaluated. This routine will suppress such diagnostics or,
9369/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009370/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009371/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009372///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009373/// This routine should be used for all diagnostics that describe the run-time
9374/// behavior of a program, such as passing a non-POD value through an ellipsis.
9375/// Failure to do so will likely result in spurious diagnostics or failures
9376/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009377bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009378 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009379 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009380 case Unevaluated:
9381 // The argument will never be evaluated, so don't complain.
9382 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009383
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009384 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009385 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009386 if (stmt && getCurFunctionOrMethodDecl()) {
9387 FunctionScopes.back()->PossiblyUnreachableDiags.
9388 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9389 }
9390 else
9391 Diag(Loc, PD);
9392
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009393 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009394
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009395 case PotentiallyPotentiallyEvaluated:
9396 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9397 break;
9398 }
9399
9400 return false;
9401}
9402
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009403bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9404 CallExpr *CE, FunctionDecl *FD) {
9405 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9406 return false;
9407
9408 PartialDiagnostic Note =
9409 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9410 << FD->getDeclName() : PDiag();
9411 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009412
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009413 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009414 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009415 PDiag(diag::err_call_function_incomplete_return)
9416 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009417 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009418 << CE->getSourceRange(),
9419 std::make_pair(NoteLoc, Note)))
9420 return true;
9421
9422 return false;
9423}
9424
Douglas Gregor92c3a042011-01-19 16:50:08 +00009425// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009426// will prevent this condition from triggering, which is what we want.
9427void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9428 SourceLocation Loc;
9429
John McCalla52ef082009-11-11 02:41:58 +00009430 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009431 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009432
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009433 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009434 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009435 return;
9436
Douglas Gregor92c3a042011-01-19 16:50:08 +00009437 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9438
John McCallc8d8ac52009-11-12 00:06:05 +00009439 // Greylist some idioms by putting them into a warning subcategory.
9440 if (ObjCMessageExpr *ME
9441 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9442 Selector Sel = ME->getSelector();
9443
John McCallc8d8ac52009-11-12 00:06:05 +00009444 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009445 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009446 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9447
9448 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009449 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009450 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9451 }
John McCalla52ef082009-11-11 02:41:58 +00009452
John McCall5a881bb2009-10-12 21:59:07 +00009453 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009454 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009455 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009456 return;
9457
Douglas Gregor92c3a042011-01-19 16:50:08 +00009458 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009459 Loc = Op->getOperatorLoc();
9460 } else {
9461 // Not an assignment.
9462 return;
9463 }
9464
Douglas Gregor55b38842010-04-14 16:09:52 +00009465 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009466
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009467 SourceLocation Open = E->getSourceRange().getBegin();
9468 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9469 Diag(Loc, diag::note_condition_assign_silence)
9470 << FixItHint::CreateInsertion(Open, "(")
9471 << FixItHint::CreateInsertion(Close, ")");
9472
Douglas Gregor92c3a042011-01-19 16:50:08 +00009473 if (IsOrAssign)
9474 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9475 << FixItHint::CreateReplacement(Loc, "!=");
9476 else
9477 Diag(Loc, diag::note_condition_assign_to_comparison)
9478 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009479}
9480
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009481/// \brief Redundant parentheses over an equality comparison can indicate
9482/// that the user intended an assignment used as condition.
9483void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009484 // Don't warn if the parens came from a macro.
9485 SourceLocation parenLoc = parenE->getLocStart();
9486 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9487 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009488 // Don't warn for dependent expressions.
9489 if (parenE->isTypeDependent())
9490 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009491
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009492 Expr *E = parenE->IgnoreParens();
9493
9494 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009495 if (opE->getOpcode() == BO_EQ &&
9496 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9497 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009498 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009499
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009500 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009501 Diag(Loc, diag::note_equality_comparison_silence)
9502 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9503 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009504 Diag(Loc, diag::note_equality_comparison_to_assign)
9505 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009506 }
9507}
9508
John Wiegley429bb272011-04-08 18:41:53 +00009509ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009510 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009511 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9512 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009513
John McCall864c0412011-04-26 20:42:42 +00009514 ExprResult result = CheckPlaceholderExpr(E);
9515 if (result.isInvalid()) return ExprError();
9516 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009517
John McCall864c0412011-04-26 20:42:42 +00009518 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009519 if (getLangOptions().CPlusPlus)
9520 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9521
John Wiegley429bb272011-04-08 18:41:53 +00009522 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9523 if (ERes.isInvalid())
9524 return ExprError();
9525 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009526
9527 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009528 if (!T->isScalarType()) { // C99 6.8.4.1p1
9529 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9530 << T << E->getSourceRange();
9531 return ExprError();
9532 }
John McCall5a881bb2009-10-12 21:59:07 +00009533 }
9534
John Wiegley429bb272011-04-08 18:41:53 +00009535 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009536}
Douglas Gregor586596f2010-05-06 17:25:47 +00009537
John McCall60d7b3a2010-08-24 06:29:42 +00009538ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9539 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009540 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009541 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009542
9543 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009544}
John McCall2a984ca2010-10-12 00:20:44 +00009545
John McCall1de4d4e2011-04-07 08:22:57 +00009546namespace {
John McCall755d8492011-04-12 00:42:48 +00009547 /// A visitor for rebuilding a call to an __unknown_any expression
9548 /// to have an appropriate type.
9549 struct RebuildUnknownAnyFunction
9550 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9551
9552 Sema &S;
9553
9554 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9555
9556 ExprResult VisitStmt(Stmt *S) {
9557 llvm_unreachable("unexpected statement!");
9558 return ExprError();
9559 }
9560
9561 ExprResult VisitExpr(Expr *expr) {
9562 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9563 << expr->getSourceRange();
9564 return ExprError();
9565 }
9566
9567 /// Rebuild an expression which simply semantically wraps another
9568 /// expression which it shares the type and value kind of.
9569 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9570 ExprResult subResult = Visit(expr->getSubExpr());
9571 if (subResult.isInvalid()) return ExprError();
9572
9573 Expr *subExpr = subResult.take();
9574 expr->setSubExpr(subExpr);
9575 expr->setType(subExpr->getType());
9576 expr->setValueKind(subExpr->getValueKind());
9577 assert(expr->getObjectKind() == OK_Ordinary);
9578 return expr;
9579 }
9580
9581 ExprResult VisitParenExpr(ParenExpr *paren) {
9582 return rebuildSugarExpr(paren);
9583 }
9584
9585 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9586 return rebuildSugarExpr(op);
9587 }
9588
9589 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9590 ExprResult subResult = Visit(op->getSubExpr());
9591 if (subResult.isInvalid()) return ExprError();
9592
9593 Expr *subExpr = subResult.take();
9594 op->setSubExpr(subExpr);
9595 op->setType(S.Context.getPointerType(subExpr->getType()));
9596 assert(op->getValueKind() == VK_RValue);
9597 assert(op->getObjectKind() == OK_Ordinary);
9598 return op;
9599 }
9600
9601 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9602 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9603
9604 expr->setType(decl->getType());
9605
9606 assert(expr->getValueKind() == VK_RValue);
9607 if (S.getLangOptions().CPlusPlus &&
9608 !(isa<CXXMethodDecl>(decl) &&
9609 cast<CXXMethodDecl>(decl)->isInstance()))
9610 expr->setValueKind(VK_LValue);
9611
9612 return expr;
9613 }
9614
9615 ExprResult VisitMemberExpr(MemberExpr *mem) {
9616 return resolveDecl(mem, mem->getMemberDecl());
9617 }
9618
9619 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9620 return resolveDecl(ref, ref->getDecl());
9621 }
9622 };
9623}
9624
9625/// Given a function expression of unknown-any type, try to rebuild it
9626/// to have a function type.
9627static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9628 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9629 if (result.isInvalid()) return ExprError();
9630 return S.DefaultFunctionArrayConversion(result.take());
9631}
9632
9633namespace {
John McCall379b5152011-04-11 07:02:50 +00009634 /// A visitor for rebuilding an expression of type __unknown_anytype
9635 /// into one which resolves the type directly on the referring
9636 /// expression. Strict preservation of the original source
9637 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009638 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009639 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009640
9641 Sema &S;
9642
9643 /// The current destination type.
9644 QualType DestType;
9645
9646 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9647 : S(S), DestType(castType) {}
9648
John McCalla5fc4722011-04-09 22:50:59 +00009649 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009650 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009651 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009652 }
9653
John McCall379b5152011-04-11 07:02:50 +00009654 ExprResult VisitExpr(Expr *expr) {
9655 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9656 << expr->getSourceRange();
9657 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009658 }
9659
John McCall379b5152011-04-11 07:02:50 +00009660 ExprResult VisitCallExpr(CallExpr *call);
9661 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9662
John McCalla5fc4722011-04-09 22:50:59 +00009663 /// Rebuild an expression which simply semantically wraps another
9664 /// expression which it shares the type and value kind of.
9665 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9666 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009667 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009668 Expr *subExpr = subResult.take();
9669 expr->setSubExpr(subExpr);
9670 expr->setType(subExpr->getType());
9671 expr->setValueKind(subExpr->getValueKind());
9672 assert(expr->getObjectKind() == OK_Ordinary);
9673 return expr;
9674 }
John McCall1de4d4e2011-04-07 08:22:57 +00009675
John McCalla5fc4722011-04-09 22:50:59 +00009676 ExprResult VisitParenExpr(ParenExpr *paren) {
9677 return rebuildSugarExpr(paren);
9678 }
9679
9680 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9681 return rebuildSugarExpr(op);
9682 }
9683
John McCall755d8492011-04-12 00:42:48 +00009684 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9685 const PointerType *ptr = DestType->getAs<PointerType>();
9686 if (!ptr) {
9687 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9688 << op->getSourceRange();
9689 return ExprError();
9690 }
9691 assert(op->getValueKind() == VK_RValue);
9692 assert(op->getObjectKind() == OK_Ordinary);
9693 op->setType(DestType);
9694
9695 // Build the sub-expression as if it were an object of the pointee type.
9696 DestType = ptr->getPointeeType();
9697 ExprResult subResult = Visit(op->getSubExpr());
9698 if (subResult.isInvalid()) return ExprError();
9699 op->setSubExpr(subResult.take());
9700 return op;
9701 }
9702
John McCall379b5152011-04-11 07:02:50 +00009703 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009704
John McCall755d8492011-04-12 00:42:48 +00009705 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009706
John McCall755d8492011-04-12 00:42:48 +00009707 ExprResult VisitMemberExpr(MemberExpr *mem) {
9708 return resolveDecl(mem, mem->getMemberDecl());
9709 }
John McCalla5fc4722011-04-09 22:50:59 +00009710
9711 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009712 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009713 }
9714 };
9715}
9716
John McCall379b5152011-04-11 07:02:50 +00009717/// Rebuilds a call expression which yielded __unknown_anytype.
9718ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9719 Expr *callee = call->getCallee();
9720
9721 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009722 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009723 FK_FunctionPointer,
9724 FK_BlockPointer
9725 };
9726
9727 FnKind kind;
9728 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009729 if (type == S.Context.BoundMemberTy) {
9730 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9731 kind = FK_MemberFunction;
9732 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009733 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9734 type = ptr->getPointeeType();
9735 kind = FK_FunctionPointer;
9736 } else {
9737 type = type->castAs<BlockPointerType>()->getPointeeType();
9738 kind = FK_BlockPointer;
9739 }
9740 const FunctionType *fnType = type->castAs<FunctionType>();
9741
9742 // Verify that this is a legal result type of a function.
9743 if (DestType->isArrayType() || DestType->isFunctionType()) {
9744 unsigned diagID = diag::err_func_returning_array_function;
9745 if (kind == FK_BlockPointer)
9746 diagID = diag::err_block_returning_array_function;
9747
9748 S.Diag(call->getExprLoc(), diagID)
9749 << DestType->isFunctionType() << DestType;
9750 return ExprError();
9751 }
9752
9753 // Otherwise, go ahead and set DestType as the call's result.
9754 call->setType(DestType.getNonLValueExprType(S.Context));
9755 call->setValueKind(Expr::getValueKindForType(DestType));
9756 assert(call->getObjectKind() == OK_Ordinary);
9757
9758 // Rebuild the function type, replacing the result type with DestType.
9759 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9760 DestType = S.Context.getFunctionType(DestType,
9761 proto->arg_type_begin(),
9762 proto->getNumArgs(),
9763 proto->getExtProtoInfo());
9764 else
9765 DestType = S.Context.getFunctionNoProtoType(DestType,
9766 fnType->getExtInfo());
9767
9768 // Rebuild the appropriate pointer-to-function type.
9769 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009770 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009771 // Nothing to do.
9772 break;
9773
9774 case FK_FunctionPointer:
9775 DestType = S.Context.getPointerType(DestType);
9776 break;
9777
9778 case FK_BlockPointer:
9779 DestType = S.Context.getBlockPointerType(DestType);
9780 break;
9781 }
9782
9783 // Finally, we can recurse.
9784 ExprResult calleeResult = Visit(callee);
9785 if (!calleeResult.isUsable()) return ExprError();
9786 call->setCallee(calleeResult.take());
9787
9788 // Bind a temporary if necessary.
9789 return S.MaybeBindToTemporary(call);
9790}
9791
9792ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009793 // Verify that this is a legal result type of a call.
9794 if (DestType->isArrayType() || DestType->isFunctionType()) {
9795 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9796 << DestType->isFunctionType() << DestType;
9797 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009798 }
9799
John McCall48218c62011-07-13 17:56:40 +00009800 // Rewrite the method result type if available.
9801 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9802 assert(method->getResultType() == S.Context.UnknownAnyTy);
9803 method->setResultType(DestType);
9804 }
John McCall755d8492011-04-12 00:42:48 +00009805
John McCall379b5152011-04-11 07:02:50 +00009806 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009807 msg->setType(DestType.getNonReferenceType());
9808 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009809
John McCall755d8492011-04-12 00:42:48 +00009810 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009811}
9812
9813ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009814 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009815 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009816 assert(ice->getValueKind() == VK_RValue);
9817 assert(ice->getObjectKind() == OK_Ordinary);
9818
John McCall755d8492011-04-12 00:42:48 +00009819 ice->setType(DestType);
9820
John McCall379b5152011-04-11 07:02:50 +00009821 // Rebuild the sub-expression as the pointee (function) type.
9822 DestType = DestType->castAs<PointerType>()->getPointeeType();
9823
9824 ExprResult result = Visit(ice->getSubExpr());
9825 if (!result.isUsable()) return ExprError();
9826
9827 ice->setSubExpr(result.take());
9828 return S.Owned(ice);
9829}
9830
John McCall755d8492011-04-12 00:42:48 +00009831ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009832 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009833 QualType type = DestType;
9834
9835 // We know how to make this work for certain kinds of decls:
9836
9837 // - functions
John McCall755d8492011-04-12 00:42:48 +00009838 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCalla19950e2011-08-10 04:12:23 +00009839 if (const PointerType *ptr = type->getAs<PointerType>()) {
9840 DestType = ptr->getPointeeType();
9841 ExprResult result = resolveDecl(expr, decl);
9842 if (result.isInvalid()) return ExprError();
9843 return S.ImpCastExprToType(result.take(), type,
9844 CK_FunctionToPointerDecay, VK_RValue);
9845 }
9846
9847 if (!type->isFunctionType()) {
9848 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9849 << decl << expr->getSourceRange();
9850 return ExprError();
9851 }
John McCall379b5152011-04-11 07:02:50 +00009852
John McCallf5307512011-04-27 00:36:17 +00009853 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9854 if (method->isInstance()) {
9855 valueKind = VK_RValue;
9856 type = S.Context.BoundMemberTy;
9857 }
9858
John McCall379b5152011-04-11 07:02:50 +00009859 // Function references aren't l-values in C.
9860 if (!S.getLangOptions().CPlusPlus)
9861 valueKind = VK_RValue;
9862
9863 // - variables
9864 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009865 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9866 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009867 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009868 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9869 << decl << expr->getSourceRange();
9870 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009871 }
9872
9873 // - nothing else
9874 } else {
9875 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9876 << decl << expr->getSourceRange();
9877 return ExprError();
9878 }
9879
John McCall755d8492011-04-12 00:42:48 +00009880 decl->setType(DestType);
9881 expr->setType(type);
9882 expr->setValueKind(valueKind);
9883 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009884}
9885
John McCall1de4d4e2011-04-07 08:22:57 +00009886/// Check a cast of an unknown-any type. We intentionally only
9887/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009888ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9889 Expr *castExpr, CastKind &castKind,
9890 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009891 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009892 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9893 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009894
John McCalla5fc4722011-04-09 22:50:59 +00009895 castExpr = result.take();
9896 VK = castExpr->getValueKind();
9897 castKind = CK_NoOp;
9898
9899 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009900}
9901
9902static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9903 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009904 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009905 while (true) {
9906 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009907 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009908 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009909 diagID = diag::err_uncasted_call_of_unknown_any;
9910 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009911 break;
John McCall379b5152011-04-11 07:02:50 +00009912 }
John McCall1de4d4e2011-04-07 08:22:57 +00009913 }
9914
John McCall379b5152011-04-11 07:02:50 +00009915 SourceLocation loc;
9916 NamedDecl *d;
9917 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9918 loc = ref->getLocation();
9919 d = ref->getDecl();
9920 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9921 loc = mem->getMemberLoc();
9922 d = mem->getMemberDecl();
9923 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9924 diagID = diag::err_uncasted_call_of_unknown_any;
9925 loc = msg->getSelectorLoc();
9926 d = msg->getMethodDecl();
9927 assert(d && "unknown method returning __unknown_any?");
9928 } else {
9929 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9930 << e->getSourceRange();
9931 return ExprError();
9932 }
9933
9934 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +00009935
9936 // Never recoverable.
9937 return ExprError();
9938}
9939
John McCall2a984ca2010-10-12 00:20:44 +00009940/// Check for operands with placeholder types and complain if found.
9941/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +00009942ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +00009943 // Placeholder types are always *exactly* the appropriate builtin type.
9944 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +00009945
John McCall1de4d4e2011-04-07 08:22:57 +00009946 // Overloaded expressions.
9947 if (type == Context.OverloadTy)
9948 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +00009949 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +00009950 QualType(),
9951 diag::err_ovl_unresolvable);
9952
John McCall864c0412011-04-26 20:42:42 +00009953 // Bound member functions.
9954 if (type == Context.BoundMemberTy) {
9955 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9956 << E->getSourceRange();
9957 return ExprError();
9958 }
9959
John McCall1de4d4e2011-04-07 08:22:57 +00009960 // Expressions of unknown type.
9961 if (type == Context.UnknownAnyTy)
9962 return diagnoseUnknownAnyExpr(*this, E);
9963
9964 assert(!type->isPlaceholderType());
9965 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009966}
Richard Trieubb9b80c2011-04-21 21:44:26 +00009967
9968bool Sema::CheckCaseExpression(Expr *expr) {
9969 if (expr->isTypeDependent())
9970 return true;
9971 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9972 return expr->getType()->isIntegralOrEnumerationType();
9973 return false;
9974}