blob: 58b6258304428b36982227fac20ed04738c20730 [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
John McCall3323fad2011-09-09 07:56:05 +0000149/// DiagnoseSentinelCalls - This routine checks whether a call or
150/// message-send is to a declaration with the sentinel attribute, and
151/// if so, it checks that the requirements of the sentinel are
152/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +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
John McCall3323fad2011-09-09 07:56:05 +0000159 // The number of formal parameters of the declaration.
160 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000161
John McCall3323fad2011-09-09 07:56:05 +0000162 // The kind of declaration. This is also an index into a %select in
163 // the diagnostic.
164 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
165
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000166 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000167 numFormalParams = MD->param_size();
168 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000169 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000170 numFormalParams = FD->param_size();
171 calleeType = CT_Function;
172 } else if (isa<VarDecl>(D)) {
173 QualType type = cast<ValueDecl>(D)->getType();
174 const FunctionType *fn = 0;
175 if (const PointerType *ptr = type->getAs<PointerType>()) {
176 fn = ptr->getPointeeType()->getAs<FunctionType>();
177 if (!fn) return;
178 calleeType = CT_Function;
179 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
180 fn = ptr->getPointeeType()->castAs<FunctionType>();
181 calleeType = CT_Block;
182 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000183 return;
John McCall3323fad2011-09-09 07:56:05 +0000184 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000185
John McCall3323fad2011-09-09 07:56:05 +0000186 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
187 numFormalParams = proto->getNumArgs();
188 } else {
189 numFormalParams = 0;
190 }
191 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000192 return;
193 }
John McCall3323fad2011-09-09 07:56:05 +0000194
195 // "nullPos" is the number of formal parameters at the end which
196 // effectively count as part of the variadic arguments. This is
197 // useful if you would prefer to not have *any* formal parameters,
198 // but the language forces you to have at least one.
199 unsigned nullPos = attr->getNullPos();
200 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
201 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
202
203 // The number of arguments which should follow the sentinel.
204 unsigned numArgsAfterSentinel = attr->getSentinel();
205
206 // If there aren't enough arguments for all the formal parameters,
207 // the sentinel, and the args after the sentinel, complain.
208 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000209 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000210 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000211 return;
212 }
John McCall3323fad2011-09-09 07:56:05 +0000213
214 // Otherwise, find the sentinel expression.
215 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000216 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000217 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000218
219 // nullptr_t is always treated as null.
220 if (sentinelExpr->getType()->isNullPtrType()) return;
221
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000222 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000223 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
224 Expr::NPC_ValueDependentIsNull))
225 return;
226
227 // Unfortunately, __null has type 'int'.
228 if (isa<GNUNullExpr>(sentinelExpr)) return;
229
John McCall3323fad2011-09-09 07:56:05 +0000230 // Pick a reasonable string to insert. Optimistically use 'nil' or
231 // 'NULL' if those are actually defined in the context. Only use
232 // 'nil' for ObjC methods, where it's much more likely that the
233 // variadic arguments form a list of object pointers.
234 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000235 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
236 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000237 if (calleeType == CT_Method &&
238 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000239 NullValue = "nil";
240 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
241 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000242 else
John McCall3323fad2011-09-09 07:56:05 +0000243 NullValue = "(void*) 0";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000244
245 Diag(MissingNilLoc, diag::warn_missing_sentinel)
John McCall3323fad2011-09-09 07:56:05 +0000246 << calleeType
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000247 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000248 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000249}
250
Richard Trieuccd891a2011-09-09 01:45:06 +0000251SourceRange Sema::getExprRange(Expr *E) const {
252 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000253}
254
Chris Lattnere7a2e912008-07-25 21:10:04 +0000255//===----------------------------------------------------------------------===//
256// Standard Promotions and Conversions
257//===----------------------------------------------------------------------===//
258
Chris Lattnere7a2e912008-07-25 21:10:04 +0000259/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000260ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000261 QualType Ty = E->getType();
262 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
263
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000265 E = ImpCastExprToType(E, Context.getPointerType(Ty),
266 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000267 else if (Ty->isArrayType()) {
268 // In C90 mode, arrays only promote to pointers if the array expression is
269 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
270 // type 'array of type' is converted to an expression that has type 'pointer
271 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
272 // that has type 'array of type' ...". The relevant change is "an lvalue"
273 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000274 //
275 // C++ 4.2p1:
276 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
277 // T" can be converted to an rvalue of type "pointer to T".
278 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000279 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
281 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000282 }
John Wiegley429bb272011-04-08 18:41:53 +0000283 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284}
285
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000286static void CheckForNullPointerDereference(Sema &S, Expr *E) {
287 // Check to see if we are dereferencing a null pointer. If so,
288 // and if not volatile-qualified, this is undefined behavior that the
289 // optimizer will delete, so warn about it. People sometimes try to use this
290 // to get a deterministic trap and are surprised by clang's behavior. This
291 // only handles the pattern "*null", which is a very syntactic check.
292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
293 if (UO->getOpcode() == UO_Deref &&
294 UO->getSubExpr()->IgnoreParenCasts()->
295 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
296 !UO->getType().isVolatileQualified()) {
297 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
298 S.PDiag(diag::warn_indirection_through_null)
299 << UO->getSubExpr()->getSourceRange());
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::note_indirection_through_null));
302 }
303}
304
John Wiegley429bb272011-04-08 18:41:53 +0000305ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000306 // C++ [conv.lval]p1:
307 // A glvalue of a non-function, non-array type T can be
308 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000309 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000310
John McCall409fa9a2010-12-06 20:48:59 +0000311 QualType T = E->getType();
312 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000313
John McCall409fa9a2010-12-06 20:48:59 +0000314 // Create a load out of an ObjCProperty l-value, if necessary.
315 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000316 ExprResult Res = ConvertPropertyForRValue(E);
317 if (Res.isInvalid())
318 return Owned(E);
319 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000320 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000321 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000322 }
John McCall409fa9a2010-12-06 20:48:59 +0000323
324 // We don't want to throw lvalue-to-rvalue casts on top of
325 // expressions of certain types in C++.
326 if (getLangOptions().CPlusPlus &&
327 (E->getType() == Context.OverloadTy ||
328 T->isDependentType() ||
329 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000330 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000331
332 // The C standard is actually really unclear on this point, and
333 // DR106 tells us what the result should be but not why. It's
334 // generally best to say that void types just doesn't undergo
335 // lvalue-to-rvalue at all. Note that expressions of unqualified
336 // 'void' type are never l-values, but qualified void can be.
337 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000338 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000339
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000340 CheckForNullPointerDereference(*this, E);
341
John McCall409fa9a2010-12-06 20:48:59 +0000342 // C++ [conv.lval]p1:
343 // [...] If T is a non-class type, the type of the prvalue is the
344 // cv-unqualified version of T. Otherwise, the type of the
345 // rvalue is T.
346 //
347 // C99 6.3.2.1p2:
348 // If the lvalue has qualified type, the value has the unqualified
349 // version of the type of the lvalue; otherwise, the value has the
350 // type of the lvalue.
351 if (T.hasQualifiers())
352 T = T.getUnqualifiedType();
Ted Kremeneka0125d82011-02-16 01:57:07 +0000353
John Wiegley429bb272011-04-08 18:41:53 +0000354 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
355 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000356}
357
John Wiegley429bb272011-04-08 18:41:53 +0000358ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
359 ExprResult Res = DefaultFunctionArrayConversion(E);
360 if (Res.isInvalid())
361 return ExprError();
362 Res = DefaultLvalueConversion(Res.take());
363 if (Res.isInvalid())
364 return ExprError();
365 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000366}
367
368
Chris Lattnere7a2e912008-07-25 21:10:04 +0000369/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000370/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000371/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000372/// apply if the array is an argument to the sizeof or address (&) operators.
373/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000374ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000375 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000376 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
377 if (Res.isInvalid())
378 return Owned(E);
379 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000380
381 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000382 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000383
384 // Try to perform integral promotions if the object has a theoretically
385 // promotable type.
386 if (Ty->isIntegralOrUnscopedEnumerationType()) {
387 // C99 6.3.1.1p2:
388 //
389 // The following may be used in an expression wherever an int or
390 // unsigned int may be used:
391 // - an object or expression with an integer type whose integer
392 // conversion rank is less than or equal to the rank of int
393 // and unsigned int.
394 // - A bit-field of type _Bool, int, signed int, or unsigned int.
395 //
396 // If an int can represent all values of the original type, the
397 // value is converted to an int; otherwise, it is converted to an
398 // unsigned int. These are called the integer promotions. All
399 // other types are unchanged by the integer promotions.
400
401 QualType PTy = Context.isPromotableBitField(E);
402 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000403 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
404 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000405 }
406 if (Ty->isPromotableIntegerType()) {
407 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
409 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000410 }
Eli Friedman04e83572009-08-20 04:21:42 +0000411 }
John Wiegley429bb272011-04-08 18:41:53 +0000412 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000413}
414
Chris Lattner05faf172008-07-25 22:25:12 +0000415/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000416/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000417/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000418ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
419 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000420 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000421
John Wiegley429bb272011-04-08 18:41:53 +0000422 ExprResult Res = UsualUnaryConversions(E);
423 if (Res.isInvalid())
424 return Owned(E);
425 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000426
Chris Lattner05faf172008-07-25 22:25:12 +0000427 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000428 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000429 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
430
John McCall96a914a2011-08-27 22:06:17 +0000431 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000432 // promotion, even on class types, but note:
433 // C++11 [conv.lval]p2:
434 // When an lvalue-to-rvalue conversion occurs in an unevaluated
435 // operand or a subexpression thereof the value contained in the
436 // referenced object is not accessed. Otherwise, if the glvalue
437 // has a class type, the conversion copy-initializes a temporary
438 // of type T from the glvalue and the result of the conversion
439 // is a prvalue for the temporary.
440 // FIXME: add some way to gate this entire thing for correctness in
441 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000442 if (getLangOptions().CPlusPlus && E->isGLValue() &&
443 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000444 ExprResult Temp = PerformCopyInitialization(
445 InitializedEntity::InitializeTemporary(E->getType()),
446 E->getExprLoc(),
447 Owned(E));
448 if (Temp.isInvalid())
449 return ExprError();
450 E = Temp.get();
451 }
452
John Wiegley429bb272011-04-08 18:41:53 +0000453 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000454}
455
Chris Lattner312531a2009-04-12 08:11:20 +0000456/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
457/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000458/// interfaces passed by value.
459ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000460 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000461 ExprResult ExprRes = CheckPlaceholderExpr(E);
462 if (ExprRes.isInvalid())
463 return ExprError();
464
465 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000466 if (ExprRes.isInvalid())
467 return ExprError();
468 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000470 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000472 DiagRuntimeBehavior(E->getLocStart(), 0,
473 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
474 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000475 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000476
John McCallf85e1932011-06-15 23:02:42 +0000477 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000478 // C++0x [expr.call]p7:
479 // Passing a potentially-evaluated argument of class type (Clause 9)
480 // having a non-trivial copy constructor, a non-trivial move constructor,
481 // or a non-trivial destructor, with no corresponding parameter,
482 // is conditionally-supported with implementation-defined semantics.
483 bool TrivialEnough = false;
484 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
485 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
486 if (Record->hasTrivialCopyConstructor() &&
487 Record->hasTrivialMoveConstructor() &&
488 Record->hasTrivialDestructor())
489 TrivialEnough = true;
490 }
491 }
John McCallf85e1932011-06-15 23:02:42 +0000492
493 if (!TrivialEnough &&
494 getLangOptions().ObjCAutoRefCount &&
495 E->getType()->isObjCLifetimeType())
496 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000497
498 if (TrivialEnough) {
499 // Nothing to diagnose. This is okay.
500 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000501 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000502 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000503 << CT)) {
504 // Turn this into a trap.
505 CXXScopeSpec SS;
506 UnqualifiedId Name;
507 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
508 E->getLocStart());
509 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
510 if (TrapFn.isInvalid())
511 return ExprError();
512
513 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
514 MultiExprArg(), E->getLocEnd());
515 if (Call.isInvalid())
516 return ExprError();
517
518 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
519 Call.get(), E);
520 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000521 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000522 E = Comma.get();
523 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000524 }
525
John Wiegley429bb272011-04-08 18:41:53 +0000526 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000527}
528
Richard Trieu8289f492011-09-02 20:58:51 +0000529/// \brief Converts an integer to complex float type. Helper function of
530/// UsualArithmeticConversions()
531///
532/// \return false if the integer expression is an integer type and is
533/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000534static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
535 ExprResult &ComplexExpr,
536 QualType IntTy,
537 QualType ComplexTy,
538 bool SkipCast) {
539 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
540 if (SkipCast) return false;
541 if (IntTy->isIntegerType()) {
542 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
543 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
544 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000545 CK_FloatingRealToComplex);
546 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000547 assert(IntTy->isComplexIntegerType());
548 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000549 CK_IntegralComplexToFloatingComplex);
550 }
551 return false;
552}
553
554/// \brief Takes two complex float types and converts them to the same type.
555/// Helper function of UsualArithmeticConversions()
556static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000557handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
558 ExprResult &RHS, QualType LHSType,
559 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000560 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000561 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000562
563 if (order < 0) {
564 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000565 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000566 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
567 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000568 }
569 if (order > 0)
570 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000571 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
572 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000573}
574
575/// \brief Converts otherExpr to complex float and promotes complexExpr if
576/// necessary. Helper function of UsualArithmeticConversions()
577static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000578 ExprResult &ComplexExpr,
579 ExprResult &OtherExpr,
580 QualType ComplexTy,
581 QualType OtherTy,
582 bool ConvertComplexExpr,
583 bool ConvertOtherExpr) {
584 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000585
586 // If just the complexExpr is complex, the otherExpr needs to be converted,
587 // and the complexExpr might need to be promoted.
588 if (order > 0) { // complexExpr is wider
589 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000590 if (ConvertOtherExpr) {
591 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
592 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
593 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000594 CK_FloatingRealToComplex);
595 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000596 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000597 }
598
599 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000600 QualType result = (order == 0 ? ComplexTy :
601 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000602
603 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000604 if (ConvertOtherExpr)
605 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000606 CK_FloatingRealToComplex);
607
608 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000609 if (ConvertComplexExpr && order < 0)
610 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000611 CK_FloatingComplexCast);
612
613 return result;
614}
615
616/// \brief Handle arithmetic conversion with complex types. Helper function of
617/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000618static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
619 ExprResult &RHS, QualType LHSType,
620 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000621 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000622 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000623 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000624 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000625 return LHSType;
626 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000627 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000628 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000629
630 // This handles complex/complex, complex/float, or float/complex.
631 // When both operands are complex, the shorter operand is converted to the
632 // type of the longer, and that is the type of the result. This corresponds
633 // to what is done when combining two real floating-point operands.
634 // The fun begins when size promotion occur across type domains.
635 // From H&S 6.3.4: When one operand is complex and the other is a real
636 // floating-point type, the less precise type is converted, within it's
637 // real or complex domain, to the precision of the other type. For example,
638 // when combining a "long double" with a "double _Complex", the
639 // "double _Complex" is promoted to "long double _Complex".
640
Richard Trieucafd30b2011-09-06 18:25:09 +0000641 bool LHSComplexFloat = LHSType->isComplexType();
642 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000643
644 // If both are complex, just cast to the more precise type.
645 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000646 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
647 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000648 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000649
650 // If only one operand is complex, promote it if necessary and convert the
651 // other operand to complex.
652 if (LHSComplexFloat)
653 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000654 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000655 /*convertOtherExpr*/ true);
656
657 assert(RHSComplexFloat);
658 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000659 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000660 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000661}
662
663/// \brief Hande arithmetic conversion from integer to float. Helper function
664/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000665static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
666 ExprResult &IntExpr,
667 QualType FloatTy, QualType IntTy,
668 bool ConvertFloat, bool ConvertInt) {
669 if (IntTy->isIntegerType()) {
670 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000671 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000672 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000673 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000674 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000675 }
676
677 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000678 assert(IntTy->isComplexIntegerType());
679 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000680
681 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000682 if (ConvertInt)
683 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000684 CK_IntegralComplexToFloatingComplex);
685
686 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000687 if (ConvertFloat)
688 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000689 CK_FloatingRealToComplex);
690
691 return result;
692}
693
694/// \brief Handle arithmethic conversion with floating point types. Helper
695/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000696static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
697 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000698 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000699 bool LHSFloat = LHSType->isRealFloatingType();
700 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000701
702 // If we have two real floating types, convert the smaller operand
703 // to the bigger result.
704 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000705 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000706 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000707 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
708 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000709 }
710
711 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000712 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000713 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
714 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000715 }
716
717 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000718 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000719 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000720 /*convertInt=*/ true);
721 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000722 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000723 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000724 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000725}
726
727/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000728/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000729// FIXME: if the operands are (int, _Complex long), we currently
730// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000731static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
732 ExprResult &RHS, QualType LHSType,
733 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000734 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000735 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
736 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000737
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000738 if (LHSComplexInt && RHSComplexInt) {
739 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
740 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000741 assert(order && "inequal types with equal element ordering");
742 if (order > 0) {
743 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000744 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
745 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000746 }
747
Richard Trieuccd891a2011-09-09 01:45:06 +0000748 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000749 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
750 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000751 }
752
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000753 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000754 // int -> _Complex int
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000755 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
756 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000757 }
758
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000759 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000760 // int -> _Complex int
Richard Trieuccd891a2011-09-09 01:45:06 +0000761 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000762 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
763 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000764}
765
766/// \brief Handle integer arithmetic conversions. Helper function of
767/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000768static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
769 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000770 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000771 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000772 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
773 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
774 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
775 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000776 // Same signedness; use the higher-ranked type
777 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000778 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
779 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000780 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000781 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
782 return RHSType;
783 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000784 // The unsigned type has greater than or equal rank to the
785 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000786 if (RHSSigned) {
787 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
788 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000790 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
791 return RHSType;
792 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000793 // The two types are different widths; if we are here, that
794 // means the signed type is larger than the unsigned type, so
795 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000796 if (LHSSigned) {
797 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
798 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000799 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000800 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
801 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000802 } else {
803 // The signed type is higher-ranked than the unsigned type,
804 // but isn't actually any bigger (like unsigned int and long
805 // on most 32-bit systems). Use the unsigned type corresponding
806 // to the signed type.
807 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000808 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
809 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000811 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000812 return result;
813 }
814}
815
Chris Lattnere7a2e912008-07-25 21:10:04 +0000816/// UsualArithmeticConversions - Performs various conversions that are common to
817/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000818/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000819/// responsible for emitting appropriate error diagnostics.
820/// FIXME: verify the conversion rules for "complex int" are consistent with
821/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000822QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000823 bool IsCompAssign) {
824 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000825 LHS = UsualUnaryConversions(LHS.take());
826 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000827 return QualType();
828 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000829
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000830 RHS = UsualUnaryConversions(RHS.take());
831 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000832 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000833
Mike Stump1eb44332009-09-09 15:08:12 +0000834 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000835 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000836 QualType LHSType =
837 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
838 QualType RHSType =
839 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000840
841 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000842 if (LHSType == RHSType)
843 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000844
845 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
846 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000847 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
848 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000849
John McCallcf33b242010-11-13 08:17:45 +0000850 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000851 QualType LHSUnpromotedType = LHSType;
852 if (LHSType->isPromotableIntegerType())
853 LHSType = Context.getPromotedIntegerType(LHSType);
854 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000855 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000856 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000857 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000858 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000859
John McCallcf33b242010-11-13 08:17:45 +0000860 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000861 if (LHSType == RHSType)
862 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000863
864 // At this point, we have two different arithmetic types.
865
866 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000867 if (LHSType->isComplexType() || RHSType->isComplexType())
868 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000869 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000870
871 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000872 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
873 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000874 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000875
876 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000877 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000878 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000879 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000880
881 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000882 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000883 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000884}
885
Chris Lattnere7a2e912008-07-25 21:10:04 +0000886//===----------------------------------------------------------------------===//
887// Semantic Analysis for various Expression Types
888//===----------------------------------------------------------------------===//
889
890
Peter Collingbournef111d932011-04-15 00:35:48 +0000891ExprResult
892Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
893 SourceLocation DefaultLoc,
894 SourceLocation RParenLoc,
895 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000896 MultiTypeArg ArgTypes,
897 MultiExprArg ArgExprs) {
898 unsigned NumAssocs = ArgTypes.size();
899 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000900
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 ParsedType *ParsedTypes = ArgTypes.release();
902 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000903
904 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
905 for (unsigned i = 0; i < NumAssocs; ++i) {
906 if (ParsedTypes[i])
907 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
908 else
909 Types[i] = 0;
910 }
911
912 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
913 ControllingExpr, Types, Exprs,
914 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000915 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000916 return ER;
917}
918
919ExprResult
920Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
921 SourceLocation DefaultLoc,
922 SourceLocation RParenLoc,
923 Expr *ControllingExpr,
924 TypeSourceInfo **Types,
925 Expr **Exprs,
926 unsigned NumAssocs) {
927 bool TypeErrorFound = false,
928 IsResultDependent = ControllingExpr->isTypeDependent(),
929 ContainsUnexpandedParameterPack
930 = ControllingExpr->containsUnexpandedParameterPack();
931
932 for (unsigned i = 0; i < NumAssocs; ++i) {
933 if (Exprs[i]->containsUnexpandedParameterPack())
934 ContainsUnexpandedParameterPack = true;
935
936 if (Types[i]) {
937 if (Types[i]->getType()->containsUnexpandedParameterPack())
938 ContainsUnexpandedParameterPack = true;
939
940 if (Types[i]->getType()->isDependentType()) {
941 IsResultDependent = true;
942 } else {
943 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
944 // complete object type other than a variably modified type."
945 unsigned D = 0;
946 if (Types[i]->getType()->isIncompleteType())
947 D = diag::err_assoc_type_incomplete;
948 else if (!Types[i]->getType()->isObjectType())
949 D = diag::err_assoc_type_nonobject;
950 else if (Types[i]->getType()->isVariablyModifiedType())
951 D = diag::err_assoc_type_variably_modified;
952
953 if (D != 0) {
954 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
955 << Types[i]->getTypeLoc().getSourceRange()
956 << Types[i]->getType();
957 TypeErrorFound = true;
958 }
959
960 // C1X 6.5.1.1p2 "No two generic associations in the same generic
961 // selection shall specify compatible types."
962 for (unsigned j = i+1; j < NumAssocs; ++j)
963 if (Types[j] && !Types[j]->getType()->isDependentType() &&
964 Context.typesAreCompatible(Types[i]->getType(),
965 Types[j]->getType())) {
966 Diag(Types[j]->getTypeLoc().getBeginLoc(),
967 diag::err_assoc_compatible_types)
968 << Types[j]->getTypeLoc().getSourceRange()
969 << Types[j]->getType()
970 << Types[i]->getType();
971 Diag(Types[i]->getTypeLoc().getBeginLoc(),
972 diag::note_compat_assoc)
973 << Types[i]->getTypeLoc().getSourceRange()
974 << Types[i]->getType();
975 TypeErrorFound = true;
976 }
977 }
978 }
979 }
980 if (TypeErrorFound)
981 return ExprError();
982
983 // If we determined that the generic selection is result-dependent, don't
984 // try to compute the result expression.
985 if (IsResultDependent)
986 return Owned(new (Context) GenericSelectionExpr(
987 Context, KeyLoc, ControllingExpr,
988 Types, Exprs, NumAssocs, DefaultLoc,
989 RParenLoc, ContainsUnexpandedParameterPack));
990
Chris Lattner5f9e2722011-07-23 10:55:15 +0000991 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +0000992 unsigned DefaultIndex = -1U;
993 for (unsigned i = 0; i < NumAssocs; ++i) {
994 if (!Types[i])
995 DefaultIndex = i;
996 else if (Context.typesAreCompatible(ControllingExpr->getType(),
997 Types[i]->getType()))
998 CompatIndices.push_back(i);
999 }
1000
1001 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1002 // type compatible with at most one of the types named in its generic
1003 // association list."
1004 if (CompatIndices.size() > 1) {
1005 // We strip parens here because the controlling expression is typically
1006 // parenthesized in macro definitions.
1007 ControllingExpr = ControllingExpr->IgnoreParens();
1008 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1009 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1010 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001011 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001012 E = CompatIndices.end(); I != E; ++I) {
1013 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1014 diag::note_compat_assoc)
1015 << Types[*I]->getTypeLoc().getSourceRange()
1016 << Types[*I]->getType();
1017 }
1018 return ExprError();
1019 }
1020
1021 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1022 // its controlling expression shall have type compatible with exactly one of
1023 // the types named in its generic association list."
1024 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1025 // We strip parens here because the controlling expression is typically
1026 // parenthesized in macro definitions.
1027 ControllingExpr = ControllingExpr->IgnoreParens();
1028 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1029 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1030 return ExprError();
1031 }
1032
1033 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1034 // type name that is compatible with the type of the controlling expression,
1035 // then the result expression of the generic selection is the expression
1036 // in that generic association. Otherwise, the result expression of the
1037 // generic selection is the expression in the default generic association."
1038 unsigned ResultIndex =
1039 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1040
1041 return Owned(new (Context) GenericSelectionExpr(
1042 Context, KeyLoc, ControllingExpr,
1043 Types, Exprs, NumAssocs, DefaultLoc,
1044 RParenLoc, ContainsUnexpandedParameterPack,
1045 ResultIndex));
1046}
1047
Steve Narofff69936d2007-09-16 03:34:24 +00001048/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001049/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1050/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1051/// multiple tokens. However, the common case is that StringToks points to one
1052/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001053///
John McCall60d7b3a2010-08-24 06:29:42 +00001054ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001055Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 assert(NumStringToks && "Must have at least one string!");
1057
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001058 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001060 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001061
Chris Lattner5f9e2722011-07-23 10:55:15 +00001062 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 for (unsigned i = 0; i != NumStringToks; ++i)
1064 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001065
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001066 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001067 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001068 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001069 else if (Literal.isUTF16())
1070 StrTy = Context.Char16Ty;
1071 else if (Literal.isUTF32())
1072 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001073 else if (Literal.Pascal)
1074 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001075
Douglas Gregor5cee1192011-07-27 05:40:30 +00001076 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1077 if (Literal.isWide())
1078 Kind = StringLiteral::Wide;
1079 else if (Literal.isUTF8())
1080 Kind = StringLiteral::UTF8;
1081 else if (Literal.isUTF16())
1082 Kind = StringLiteral::UTF16;
1083 else if (Literal.isUTF32())
1084 Kind = StringLiteral::UTF32;
1085
Douglas Gregor77a52232008-09-12 00:47:35 +00001086 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001087 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001088 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001089
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001090 // Get an array type for the string, according to C99 6.4.5. This includes
1091 // the nul terminator character as well as the string length for pascal
1092 // strings.
1093 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001094 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001095 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001098 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001099 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001100 &StringTokLocs[0],
1101 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001102}
1103
John McCall469a1eb2011-02-02 13:00:07 +00001104enum CaptureResult {
1105 /// No capture is required.
1106 CR_NoCapture,
1107
1108 /// A capture is required.
1109 CR_Capture,
1110
John McCall6b5a61b2011-02-07 10:33:21 +00001111 /// A by-ref capture is required.
1112 CR_CaptureByRef,
1113
John McCall469a1eb2011-02-02 13:00:07 +00001114 /// An error occurred when trying to capture the given variable.
1115 CR_Error
1116};
1117
1118/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001119///
John McCall469a1eb2011-02-02 13:00:07 +00001120/// \param var - the variable referenced
1121/// \param DC - the context which we couldn't capture through
1122static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001123diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001124 VarDecl *var, DeclContext *DC) {
1125 switch (S.ExprEvalContexts.back().Context) {
1126 case Sema::Unevaluated:
1127 // The argument will never be evaluated, so don't complain.
1128 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCall469a1eb2011-02-02 13:00:07 +00001130 case Sema::PotentiallyEvaluated:
1131 case Sema::PotentiallyEvaluatedIfUsed:
1132 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001133
John McCall469a1eb2011-02-02 13:00:07 +00001134 case Sema::PotentiallyPotentiallyEvaluated:
1135 // FIXME: delay these!
1136 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001137 }
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John McCall469a1eb2011-02-02 13:00:07 +00001139 // Don't diagnose about capture if we're not actually in code right
1140 // now; in general, there are more appropriate places that will
1141 // diagnose this.
1142 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1143
John McCall4f38f412011-03-22 23:15:50 +00001144 // Certain madnesses can happen with parameter declarations, which
1145 // we want to ignore.
1146 if (isa<ParmVarDecl>(var)) {
1147 // - If the parameter still belongs to the translation unit, then
1148 // we're actually just using one parameter in the declaration of
1149 // the next. This is useful in e.g. VLAs.
1150 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1151 return CR_NoCapture;
1152
1153 // - This particular madness can happen in ill-formed default
1154 // arguments; claim it's okay and let downstream code handle it.
1155 if (S.CurContext == var->getDeclContext()->getParent())
1156 return CR_NoCapture;
1157 }
John McCall469a1eb2011-02-02 13:00:07 +00001158
1159 DeclarationName functionName;
1160 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1161 functionName = fn->getDeclName();
1162 // FIXME: variable from enclosing block that we couldn't capture from!
1163
1164 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1165 << var->getIdentifier() << functionName;
1166 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1167 << var->getIdentifier();
1168
1169 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001170}
1171
John McCall6b5a61b2011-02-07 10:33:21 +00001172/// There is a well-formed capture at a particular scope level;
1173/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001174static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1175 const BlockDecl::Capture &Capture) {
1176 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001177
1178 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001179 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001180 i != e; ++i) {
1181 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1182 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001183 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1184 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001185 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1186 }
1187
Richard Trieuccd891a2011-09-09 01:45:06 +00001188 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001189}
1190
1191/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001192/// given value in the current context requires a variable capture.
1193///
1194/// This also keeps the captures set in the BlockScopeInfo records
1195/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001196static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001197 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001198 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001199 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001200 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001201
1202 // Fast path: variables from the current context never require capture.
1203 DeclContext *DC = S.CurContext;
1204 if (var->getDeclContext() == DC) return CR_NoCapture;
1205
1206 // Only variables with local storage require capture.
1207 // FIXME: What about 'const' variables in C++?
1208 if (!var->hasLocalStorage()) return CR_NoCapture;
1209
1210 // Otherwise, we need to capture.
1211
1212 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001213 do {
1214 // Only blocks (and eventually C++0x closures) can capture; other
1215 // scopes don't work.
1216 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001217 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001218
1219 BlockScopeInfo *blockScope =
1220 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1221 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1222
John McCall6b5a61b2011-02-07 10:33:21 +00001223 // Check whether we've already captured it in this block. If so,
1224 // we're done.
1225 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1226 return propagateCapture(S, functionScopesIndex,
1227 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001228
1229 functionScopesIndex--;
1230 DC = cast<BlockDecl>(DC)->getDeclContext();
1231 } while (var->getDeclContext() != DC);
1232
John McCall6b5a61b2011-02-07 10:33:21 +00001233 // Okay, we descended all the way to the block that defines the variable.
1234 // Actually try to capture it.
1235 QualType type = var->getType();
1236
1237 // Prohibit variably-modified types.
1238 if (type->isVariablyModifiedType()) {
1239 S.Diag(loc, diag::err_ref_vm_type);
1240 S.Diag(var->getLocation(), diag::note_declared_at);
1241 return CR_Error;
1242 }
1243
1244 // Prohibit arrays, even in __block variables, but not references to
1245 // them.
1246 if (type->isArrayType()) {
1247 S.Diag(loc, diag::err_ref_array_type);
1248 S.Diag(var->getLocation(), diag::note_declared_at);
1249 return CR_Error;
1250 }
1251
1252 S.MarkDeclarationReferenced(loc, var);
1253
1254 // The BlocksAttr indicates the variable is bound by-reference.
1255 bool byRef = var->hasAttr<BlocksAttr>();
1256
1257 // Build a copy expression.
1258 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001259 const RecordType *rtype;
1260 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1261 (rtype = type->getAs<RecordType>())) {
1262
1263 // The capture logic needs the destructor, so make sure we mark it.
1264 // Usually this is unnecessary because most local variables have
1265 // their destructors marked at declaration time, but parameters are
1266 // an exception because it's technically only the call site that
1267 // actually requires the destructor.
1268 if (isa<ParmVarDecl>(var))
1269 S.FinalizeVarWithDestructor(var, rtype);
1270
John McCall6b5a61b2011-02-07 10:33:21 +00001271 // According to the blocks spec, the capture of a variable from
1272 // the stack requires a const copy constructor. This is not true
1273 // of the copy/move done to move a __block variable to the heap.
1274 type.addConst();
1275
1276 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1277 ExprResult result =
1278 S.PerformCopyInitialization(
1279 InitializedEntity::InitializeBlock(var->getLocation(),
1280 type, false),
1281 loc, S.Owned(declRef));
1282
1283 // Build a full-expression copy expression if initialization
1284 // succeeded and used a non-trivial constructor. Recover from
1285 // errors by pretending that the copy isn't necessary.
1286 if (!result.isInvalid() &&
1287 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1288 result = S.MaybeCreateExprWithCleanups(result);
1289 copyExpr = result.take();
1290 }
1291 }
1292
1293 // We're currently at the declarer; go back to the closure.
1294 functionScopesIndex++;
1295 BlockScopeInfo *blockScope =
1296 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1297
1298 // Build a valid capture in this scope.
1299 blockScope->Captures.push_back(
1300 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1301 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1302
1303 // Propagate that to inner captures if necessary.
1304 return propagateCapture(S, functionScopesIndex,
1305 blockScope->Captures.back());
1306}
1307
Richard Trieuccd891a2011-09-09 01:45:06 +00001308static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001309 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001310 bool ByRef) {
1311 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001312
Richard Trieuccd891a2011-09-09 01:45:06 +00001313 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001314 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001315 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001316
1317 QualType exprType = var->getType().getNonReferenceType();
1318
1319 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001320 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001321 // The variable will be bound by copy; make it const within the
1322 // closure, but record that this was done in the expression.
1323 bool constAdded = !exprType.isConstQualified();
1324 exprType.addConst();
1325
1326 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1327 NameInfo.getLoc(), false,
1328 constAdded);
1329 } else {
1330 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1331 NameInfo.getLoc(), true);
1332 }
1333
1334 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001335}
Chris Lattner639e2d32008-10-20 05:16:36 +00001336
John McCall60d7b3a2010-08-24 06:29:42 +00001337ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001338Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001339 SourceLocation Loc,
1340 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001341 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001342 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001343}
1344
John McCall76a40212011-02-09 01:13:10 +00001345/// BuildDeclRefExpr - Build an expression that references a
1346/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001347ExprResult
John McCall76a40212011-02-09 01:13:10 +00001348Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001349 const DeclarationNameInfo &NameInfo,
1350 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001351 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
John McCall7eb0a9e2010-11-24 05:12:34 +00001353 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001354 SS? SS->getWithLocInContext(Context)
1355 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001356 D, NameInfo, Ty, VK);
1357
1358 // Just in case we're building an illegal pointer-to-member.
1359 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1360 E->setObjectKind(OK_BitField);
1361
1362 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001363}
1364
Abramo Bagnara25777432010-08-11 22:01:17 +00001365/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001366/// possibly a list of template arguments.
1367///
1368/// If this produces template arguments, it is permitted to call
1369/// DecomposeTemplateName.
1370///
1371/// This actually loses a lot of source location information for
1372/// non-standard name kinds; we should consider preserving that in
1373/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001374void
1375Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1376 TemplateArgumentListInfo &Buffer,
1377 DeclarationNameInfo &NameInfo,
1378 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001379 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1380 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1381 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1382
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001383 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001384 Id.TemplateId->getTemplateArgs(),
1385 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001386 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001387 TemplateArgsPtr.release();
1388
John McCall2b5289b2010-08-23 07:28:44 +00001389 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001390 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001391 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001392 TemplateArgs = &Buffer;
1393 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001394 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001395 TemplateArgs = 0;
1396 }
1397}
1398
John McCall578b69b2009-12-16 08:11:27 +00001399/// Diagnose an empty lookup.
1400///
1401/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001402bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001403 CorrectTypoContext CTC,
1404 TemplateArgumentListInfo *ExplicitTemplateArgs,
1405 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001406 DeclarationName Name = R.getLookupName();
1407
John McCall578b69b2009-12-16 08:11:27 +00001408 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001409 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001410 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1411 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001412 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001413 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001414 diagnostic_suggest = diag::err_undeclared_use_suggest;
1415 }
John McCall578b69b2009-12-16 08:11:27 +00001416
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001417 // If the original lookup was an unqualified lookup, fake an
1418 // unqualified lookup. This is useful when (for example) the
1419 // original lookup would not have found something because it was a
1420 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001421 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001422 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001423 if (isa<CXXRecordDecl>(DC)) {
1424 LookupQualifiedName(R, DC);
1425
1426 if (!R.empty()) {
1427 // Don't give errors about ambiguities in this lookup.
1428 R.suppressDiagnostics();
1429
1430 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1431 bool isInstance = CurMethod &&
1432 CurMethod->isInstance() &&
1433 DC == CurMethod->getParent();
1434
1435 // Give a code modification hint to insert 'this->'.
1436 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1437 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001438 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001439 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1440 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001441 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001442 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001443 if (DepMethod) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00001444 if (getLangOptions().MicrosoftExt)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001445 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001446 Diag(R.getNameLoc(), diagnostic) << Name
1447 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1448 QualType DepThisType = DepMethod->getThisType(Context);
1449 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1450 R.getNameLoc(), DepThisType, false);
1451 TemplateArgumentListInfo TList;
1452 if (ULE->hasExplicitTemplateArgs())
1453 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001454
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001455 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001456 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001457 CXXDependentScopeMemberExpr *DepExpr =
1458 CXXDependentScopeMemberExpr::Create(
1459 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001460 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001461 R.getLookupNameInfo(),
1462 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001463 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001464 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001465 // FIXME: we should be able to handle this case too. It is correct
1466 // to add this-> here. This is a workaround for PR7947.
1467 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001468 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001469 } else {
John McCall578b69b2009-12-16 08:11:27 +00001470 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001471 }
John McCall578b69b2009-12-16 08:11:27 +00001472
1473 // Do we really want to note all of these?
1474 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1475 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1476
1477 // Tell the callee to try to recover.
1478 return false;
1479 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001480
1481 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001482 }
1483 }
1484
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001485 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001486 TypoCorrection Corrected;
1487 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1488 S, &SS, NULL, false, CTC))) {
1489 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1490 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1491 R.setLookupName(Corrected.getCorrection());
1492
Hans Wennborg701d1e72011-07-12 08:45:31 +00001493 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001494 if (Corrected.isOverloaded()) {
1495 OverloadCandidateSet OCS(R.getNameLoc());
1496 OverloadCandidateSet::iterator Best;
1497 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1498 CDEnd = Corrected.end();
1499 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001500 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001501 dyn_cast<FunctionTemplateDecl>(*CD))
1502 AddTemplateOverloadCandidate(
1503 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1504 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001505 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1506 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1507 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1508 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001509 }
1510 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1511 case OR_Success:
1512 ND = Best->Function;
1513 break;
1514 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001515 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001516 }
1517 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001518 R.addDecl(ND);
1519 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001520 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001521 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1522 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001523 else
1524 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 Gregord8bba9c2011-06-28 16:20:02 +00001527 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1528 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001529 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001530 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001531
1532 // Tell the callee to try to recover.
1533 return false;
1534 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001535
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001536 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001537 // FIXME: If we ended up with a typo for a type name or
1538 // Objective-C class name, we're in trouble because the parser
1539 // is in the wrong place to recover. Suggest the typo
1540 // correction, but don't make it a fix-it since we're not going
1541 // to recover well anyway.
1542 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001543 Diag(R.getNameLoc(), diagnostic_suggest)
1544 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001545 else
1546 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001547 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001548 << SS.getRange();
1549
1550 // Don't try to recover; it won't work.
1551 return true;
1552 }
1553 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001554 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001555 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001556 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001557 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001558 else
Douglas Gregord203a162010-01-01 00:15:04 +00001559 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001560 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001561 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001562 return true;
1563 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001564 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001565 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001566
1567 // Emit a special diagnostic for failed member lookups.
1568 // FIXME: computing the declaration context might fail here (?)
1569 if (!SS.isEmpty()) {
1570 Diag(R.getNameLoc(), diag::err_no_member)
1571 << Name << computeDeclContext(SS, false)
1572 << SS.getRange();
1573 return true;
1574 }
1575
John McCall578b69b2009-12-16 08:11:27 +00001576 // Give up, we can't recover.
1577 Diag(R.getNameLoc(), diagnostic) << Name;
1578 return true;
1579}
1580
John McCall60d7b3a2010-08-24 06:29:42 +00001581ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001582 CXXScopeSpec &SS,
1583 UnqualifiedId &Id,
1584 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001585 bool IsAddressOfOperand) {
1586 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001587 "cannot be direct & operand and have a trailing lparen");
1588
1589 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001590 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001591
John McCall129e2df2009-11-30 22:42:35 +00001592 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001593
1594 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001595 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001596 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001597 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001598
Abramo Bagnara25777432010-08-11 22:01:17 +00001599 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001600 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001601 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001602
John McCallf7a1a742009-11-24 19:00:30 +00001603 // C++ [temp.dep.expr]p3:
1604 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001605 // -- an identifier that was declared with a dependent type,
1606 // (note: handled after lookup)
1607 // -- a template-id that is dependent,
1608 // (note: handled in BuildTemplateIdExpr)
1609 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001610 // -- a nested-name-specifier that contains a class-name that
1611 // names a dependent type.
1612 // Determine whether this is a member of an unknown specialization;
1613 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001614 bool DependentID = false;
1615 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1616 Name.getCXXNameType()->isDependentType()) {
1617 DependentID = true;
1618 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001619 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001620 if (RequireCompleteDeclContext(SS, DC))
1621 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001622 } else {
1623 DependentID = true;
1624 }
1625 }
1626
Chris Lattner337e5502011-02-18 01:27:55 +00001627 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001628 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001629 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001630
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001631 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001632 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001633 LookupResult R(*this, NameInfo,
1634 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1635 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001636 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001637 // Lookup the template name again to correctly establish the context in
1638 // which it was found. This is really unfortunate as we already did the
1639 // lookup to determine that it was a template name in the first place. If
1640 // this becomes a performance hit, we can work harder to preserve those
1641 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001642 bool MemberOfUnknownSpecialization;
1643 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1644 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001645
1646 if (MemberOfUnknownSpecialization ||
1647 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001648 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001649 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001650 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001651 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001652 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001654 // If the result might be in a dependent base class, this is a dependent
1655 // id-expression.
1656 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001657 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001658 TemplateArgs);
1659
John McCallf7a1a742009-11-24 19:00:30 +00001660 // If this reference is in an Objective-C method, then we need to do
1661 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001662 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001663 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001664 if (E.isInvalid())
1665 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Chris Lattner337e5502011-02-18 01:27:55 +00001667 if (Expr *Ex = E.takeAs<Expr>())
1668 return Owned(Ex);
1669
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001670 // for further use, this must be set to false if in class method.
1671 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001672 }
Chris Lattner8a934232008-03-31 00:36:02 +00001673 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001674
John McCallf7a1a742009-11-24 19:00:30 +00001675 if (R.isAmbiguous())
1676 return ExprError();
1677
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001678 // Determine whether this name might be a candidate for
1679 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001680 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001681
John McCallf7a1a742009-11-24 19:00:30 +00001682 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001684 // in C90, extension in C99, forbidden in C++).
1685 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1686 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1687 if (D) R.addDecl(D);
1688 }
1689
1690 // If this name wasn't predeclared and if this is not a function
1691 // call, diagnose the problem.
1692 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001693 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001694 return ExprError();
1695
1696 assert(!R.empty() &&
1697 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001698
1699 // If we found an Objective-C instance variable, let
1700 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001701 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001702 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1703 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001704 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001705 assert(E.isInvalid() || E.get());
1706 return move(E);
1707 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 }
1709 }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
John McCallf7a1a742009-11-24 19:00:30 +00001711 // This is guaranteed from this point on.
1712 assert(!R.empty() || ADL);
1713
John McCallaa81e162009-12-01 22:10:20 +00001714 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001715 // C++ [class.mfct.non-static]p3:
1716 // When an id-expression that is not part of a class member access
1717 // syntax and not used to form a pointer to member is used in the
1718 // body of a non-static member function of class X, if name lookup
1719 // resolves the name in the id-expression to a non-static non-type
1720 // member of some class C, the id-expression is transformed into a
1721 // class member access expression using (*this) as the
1722 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001723 //
1724 // But we don't actually need to do this for '&' operands if R
1725 // resolved to a function or overloaded function set, because the
1726 // expression is ill-formed if it actually works out to be a
1727 // non-static member function:
1728 //
1729 // C++ [expr.ref]p4:
1730 // Otherwise, if E1.E2 refers to a non-static member function. . .
1731 // [t]he expression can be used only as the left-hand operand of a
1732 // member function call.
1733 //
1734 // There are other safeguards against such uses, but it's important
1735 // to get this right here so that we don't end up making a
1736 // spuriously dependent expression if we're inside a dependent
1737 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001738 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001739 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001740 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001741 MightBeImplicitMember = true;
1742 else if (!SS.isEmpty())
1743 MightBeImplicitMember = false;
1744 else if (R.isOverloadedResult())
1745 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001746 else if (R.isUnresolvableResult())
1747 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001748 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001749 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1750 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001751
1752 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001753 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001754 }
1755
John McCallf7a1a742009-11-24 19:00:30 +00001756 if (TemplateArgs)
1757 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001758
John McCallf7a1a742009-11-24 19:00:30 +00001759 return BuildDeclarationNameExpr(SS, R, ADL);
1760}
1761
John McCall129e2df2009-11-30 22:42:35 +00001762/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1763/// declaration name, generally during template instantiation.
1764/// There's a large number of things which don't need to be done along
1765/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001766ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001767Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001768 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001769 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001770 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001771 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001772
John McCall77bb1aa2010-05-01 00:40:08 +00001773 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001774 return ExprError();
1775
Abramo Bagnara25777432010-08-11 22:01:17 +00001776 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001777 LookupQualifiedName(R, DC);
1778
1779 if (R.isAmbiguous())
1780 return ExprError();
1781
1782 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001783 Diag(NameInfo.getLoc(), diag::err_no_member)
1784 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001785 return ExprError();
1786 }
1787
1788 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1789}
1790
1791/// LookupInObjCMethod - The parser has read a name in, and Sema has
1792/// detected that we're currently inside an ObjC method. Perform some
1793/// additional lookup.
1794///
1795/// Ideally, most of this would be done by lookup, but there's
1796/// actually quite a lot of extra work involved.
1797///
1798/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001799ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001800Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001801 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001802 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001803 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001804
John McCallf7a1a742009-11-24 19:00:30 +00001805 // There are two cases to handle here. 1) scoped lookup could have failed,
1806 // in which case we should look for an ivar. 2) scoped lookup could have
1807 // found a decl, but that decl is outside the current instance method (i.e.
1808 // a global variable). In these two cases, we do a lookup for an ivar with
1809 // this name, if the lookup sucedes, we replace it our current decl.
1810
1811 // If we're in a class method, we don't normally want to look for
1812 // ivars. But if we don't find anything else, and there's an
1813 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001814 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001815
1816 bool LookForIvars;
1817 if (Lookup.empty())
1818 LookForIvars = true;
1819 else if (IsClassMethod)
1820 LookForIvars = false;
1821 else
1822 LookForIvars = (Lookup.isSingleResult() &&
1823 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001824 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001825 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001826 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001827 ObjCInterfaceDecl *ClassDeclared;
1828 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1829 // Diagnose using an ivar in a class method.
1830 if (IsClassMethod)
1831 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1832 << IV->getDeclName());
1833
1834 // If we're referencing an invalid decl, just return this as a silent
1835 // error node. The error diagnostic was already emitted on the decl.
1836 if (IV->isInvalidDecl())
1837 return ExprError();
1838
1839 // Check if referencing a field with __attribute__((deprecated)).
1840 if (DiagnoseUseOfDecl(IV, Loc))
1841 return ExprError();
1842
1843 // Diagnose the use of an ivar outside of the declaring class.
1844 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1845 ClassDeclared != IFace)
1846 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1847
1848 // FIXME: This should use a new expr for a direct reference, don't
1849 // turn this into Self->ivar, just return a BareIVarExpr or something.
1850 IdentifierInfo &II = Context.Idents.get("self");
1851 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001852 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001853 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001854 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001855 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001856 SelfName, false, false);
1857 if (SelfExpr.isInvalid())
1858 return ExprError();
1859
John Wiegley429bb272011-04-08 18:41:53 +00001860 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1861 if (SelfExpr.isInvalid())
1862 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001863
John McCallf7a1a742009-11-24 19:00:30 +00001864 MarkDeclarationReferenced(Loc, IV);
1865 return Owned(new (Context)
1866 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001867 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001868 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001869 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001870 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001871 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001872 ObjCInterfaceDecl *ClassDeclared;
1873 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1874 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1875 IFace == ClassDeclared)
1876 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1877 }
1878 }
1879
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001880 if (Lookup.empty() && II && AllowBuiltinCreation) {
1881 // FIXME. Consolidate this with similar code in LookupName.
1882 if (unsigned BuiltinID = II->getBuiltinID()) {
1883 if (!(getLangOptions().CPlusPlus &&
1884 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1885 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1886 S, Lookup.isForRedeclaration(),
1887 Lookup.getNameLoc());
1888 if (D) Lookup.addDecl(D);
1889 }
1890 }
1891 }
John McCallf7a1a742009-11-24 19:00:30 +00001892 // Sentinel value saying that we didn't do anything special.
1893 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001894}
John McCallba135432009-11-21 08:51:07 +00001895
John McCall6bb80172010-03-30 21:47:33 +00001896/// \brief Cast a base object to a member's actual type.
1897///
1898/// Logically this happens in three phases:
1899///
1900/// * First we cast from the base type to the naming class.
1901/// The naming class is the class into which we were looking
1902/// when we found the member; it's the qualifier type if a
1903/// qualifier was provided, and otherwise it's the base type.
1904///
1905/// * Next we cast from the naming class to the declaring class.
1906/// If the member we found was brought into a class's scope by
1907/// a using declaration, this is that class; otherwise it's
1908/// the class declaring the member.
1909///
1910/// * Finally we cast from the declaring class to the "true"
1911/// declaring class of the member. This conversion does not
1912/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001913ExprResult
1914Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001915 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001916 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001917 NamedDecl *Member) {
1918 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1919 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001920 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001921
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922 QualType DestRecordType;
1923 QualType DestType;
1924 QualType FromRecordType;
1925 QualType FromType = From->getType();
1926 bool PointerConversions = false;
1927 if (isa<FieldDecl>(Member)) {
1928 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001929
Douglas Gregor5fccd362010-03-03 23:55:11 +00001930 if (FromType->getAs<PointerType>()) {
1931 DestType = Context.getPointerType(DestRecordType);
1932 FromRecordType = FromType->getPointeeType();
1933 PointerConversions = true;
1934 } else {
1935 DestType = DestRecordType;
1936 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001937 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001938 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1939 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001940 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001941
Douglas Gregor5fccd362010-03-03 23:55:11 +00001942 DestType = Method->getThisType(Context);
1943 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001944
Douglas Gregor5fccd362010-03-03 23:55:11 +00001945 if (FromType->getAs<PointerType>()) {
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 FromRecordType = FromType;
1950 DestType = DestRecordType;
1951 }
1952 } else {
1953 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001954 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001955 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001956
Douglas Gregor5fccd362010-03-03 23:55:11 +00001957 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00001958 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001959
Douglas Gregor5fccd362010-03-03 23:55:11 +00001960 // If the unqualified types are the same, no conversion is necessary.
1961 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00001962 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001963
John McCall6bb80172010-03-30 21:47:33 +00001964 SourceRange FromRange = From->getSourceRange();
1965 SourceLocation FromLoc = FromRange.getBegin();
1966
John McCall5baba9d2010-08-25 10:28:54 +00001967 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001968
Douglas Gregor5fccd362010-03-03 23:55:11 +00001969 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001970 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001971 // class name.
1972 //
1973 // If the member was a qualified name and the qualified referred to a
1974 // specific base subobject type, we'll cast to that intermediate type
1975 // first and then to the object in which the member is declared. That allows
1976 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1977 //
1978 // class Base { public: int x; };
1979 // class Derived1 : public Base { };
1980 // class Derived2 : public Base { };
1981 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1982 //
1983 // void VeryDerived::f() {
1984 // x = 17; // error: ambiguous base subobjects
1985 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1986 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001987 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001988 QualType QType = QualType(Qualifier->getAsType(), 0);
1989 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1990 assert(QType->isRecordType() && "lookup done with non-record type");
1991
1992 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1993
1994 // In C++98, the qualifier type doesn't actually have to be a base
1995 // type of the object type, in which case we just ignore it.
1996 // Otherwise build the appropriate casts.
1997 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001998 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001999 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002000 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002001 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002002
Douglas Gregor5fccd362010-03-03 23:55:11 +00002003 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002004 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002005 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2006 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002007
2008 FromType = QType;
2009 FromRecordType = QRecordType;
2010
2011 // If the qualifier type was the same as the destination type,
2012 // we're done.
2013 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002014 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002015 }
2016 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002017
John McCall6bb80172010-03-30 21:47:33 +00002018 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002019
John McCall6bb80172010-03-30 21:47:33 +00002020 // If we actually found the member through a using declaration, cast
2021 // down to the using declaration's type.
2022 //
2023 // Pointer equality is fine here because only one declaration of a
2024 // class ever has member declarations.
2025 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2026 assert(isa<UsingShadowDecl>(FoundDecl));
2027 QualType URecordType = Context.getTypeDeclType(
2028 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2029
2030 // We only need to do this if the naming-class to declaring-class
2031 // conversion is non-trivial.
2032 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2033 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002034 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002035 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002036 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002037 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002038
John McCall6bb80172010-03-30 21:47:33 +00002039 QualType UType = URecordType;
2040 if (PointerConversions)
2041 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002042 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2043 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002044 FromType = UType;
2045 FromRecordType = URecordType;
2046 }
2047
2048 // We don't do access control for the conversion from the
2049 // declaring class to the true declaring class.
2050 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002051 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002052
John McCallf871d0c2010-08-07 06:22:56 +00002053 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2055 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002056 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002057 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002058
John Wiegley429bb272011-04-08 18:41:53 +00002059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2060 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002061}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002062
John McCallf7a1a742009-11-24 19:00:30 +00002063bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002064 const LookupResult &R,
2065 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002066 // Only when used directly as the postfix-expression of a call.
2067 if (!HasTrailingLParen)
2068 return false;
2069
2070 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002071 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002072 return false;
2073
2074 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002075 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002076 return false;
2077
2078 // Turn off ADL when we find certain kinds of declarations during
2079 // normal lookup:
2080 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2081 NamedDecl *D = *I;
2082
2083 // C++0x [basic.lookup.argdep]p3:
2084 // -- a declaration of a class member
2085 // Since using decls preserve this property, we check this on the
2086 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002087 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002088 return false;
2089
2090 // C++0x [basic.lookup.argdep]p3:
2091 // -- a block-scope function declaration that is not a
2092 // using-declaration
2093 // NOTE: we also trigger this for function templates (in fact, we
2094 // don't check the decl type at all, since all other decl types
2095 // turn off ADL anyway).
2096 if (isa<UsingShadowDecl>(D))
2097 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2098 else if (D->getDeclContext()->isFunctionOrMethod())
2099 return false;
2100
2101 // C++0x [basic.lookup.argdep]p3:
2102 // -- a declaration that is neither a function or a function
2103 // template
2104 // And also for builtin functions.
2105 if (isa<FunctionDecl>(D)) {
2106 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2107
2108 // But also builtin functions.
2109 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2110 return false;
2111 } else if (!isa<FunctionTemplateDecl>(D))
2112 return false;
2113 }
2114
2115 return true;
2116}
2117
2118
John McCallba135432009-11-21 08:51:07 +00002119/// Diagnoses obvious problems with the use of the given declaration
2120/// as an expression. This is only actually called for lookups that
2121/// were not overloaded, and it doesn't promise that the declaration
2122/// will in fact be used.
2123static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002124 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2126 return true;
2127 }
2128
2129 if (isa<ObjCInterfaceDecl>(D)) {
2130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2131 return true;
2132 }
2133
2134 if (isa<NamespaceDecl>(D)) {
2135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2136 return true;
2137 }
2138
2139 return false;
2140}
2141
John McCall60d7b3a2010-08-24 06:29:42 +00002142ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002143Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002144 LookupResult &R,
2145 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002146 // If this is a single, fully-resolved result and we don't need ADL,
2147 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002148 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002149 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2150 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002151
2152 // We only need to check the declaration if there's exactly one
2153 // result, because in the overloaded case the results can only be
2154 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002155 if (R.isSingleResult() &&
2156 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002157 return ExprError();
2158
John McCallc373d482010-01-27 01:50:18 +00002159 // Otherwise, just build an unresolved lookup expression. Suppress
2160 // any lookup-related diagnostics; we'll hash these out later, when
2161 // we've picked a target.
2162 R.suppressDiagnostics();
2163
John McCallba135432009-11-21 08:51:07 +00002164 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002165 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002166 SS.getWithLocInContext(Context),
2167 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002168 NeedsADL, R.isOverloadedResult(),
2169 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002170
2171 return Owned(ULE);
2172}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002173
John McCallba135432009-11-21 08:51:07 +00002174/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002175ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002176Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002177 const DeclarationNameInfo &NameInfo,
2178 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002179 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002180 assert(!isa<FunctionTemplateDecl>(D) &&
2181 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002182
Abramo Bagnara25777432010-08-11 22:01:17 +00002183 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002184 if (CheckDeclInExpr(*this, Loc, D))
2185 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002186
Douglas Gregor9af2f522009-12-01 16:58:18 +00002187 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2188 // Specifically diagnose references to class templates that are missing
2189 // a template argument list.
2190 Diag(Loc, diag::err_template_decl_ref)
2191 << Template << SS.getRange();
2192 Diag(Template->getLocation(), diag::note_template_decl_here);
2193 return ExprError();
2194 }
2195
2196 // Make sure that we're referring to a value.
2197 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2198 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002199 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002200 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002201 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002202 return ExprError();
2203 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002204
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002205 // Check whether this declaration can be used. Note that we suppress
2206 // this check when we're going to perform argument-dependent lookup
2207 // on this function name, because this might not be the function
2208 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002209 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002210 return ExprError();
2211
Steve Naroffdd972f22008-09-05 22:11:13 +00002212 // Only create DeclRefExpr's for valid Decl's.
2213 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002214 return ExprError();
2215
John McCall5808ce42011-02-03 08:15:49 +00002216 // Handle members of anonymous structs and unions. If we got here,
2217 // and the reference is to a class member indirect field, then this
2218 // must be the subject of a pointer-to-member expression.
2219 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2220 if (!indirectField->isCXXClassMember())
2221 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2222 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002223
Chris Lattner639e2d32008-10-20 05:16:36 +00002224 // If the identifier reference is inside a block, and it refers to a value
2225 // that is outside the block, create a BlockDeclRefExpr instead of a
2226 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2227 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002228 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002229 // We do not do this for things like enum constants, global variables, etc,
2230 // as they do not get snapshotted.
2231 //
John McCall6b5a61b2011-02-07 10:33:21 +00002232 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002233 case CR_Error:
2234 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002235
John McCall469a1eb2011-02-02 13:00:07 +00002236 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002237 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2238 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2239
2240 case CR_CaptureByRef:
2241 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2242 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002243
2244 case CR_NoCapture: {
2245 // If this reference is not in a block or if the referenced
2246 // variable is within the block, create a normal DeclRefExpr.
2247
2248 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002249 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002250
2251 switch (D->getKind()) {
2252 // Ignore all the non-ValueDecl kinds.
2253#define ABSTRACT_DECL(kind)
2254#define VALUE(type, base)
2255#define DECL(type, base) \
2256 case Decl::type:
2257#include "clang/AST/DeclNodes.inc"
2258 llvm_unreachable("invalid value decl kind");
2259 return ExprError();
2260
2261 // These shouldn't make it here.
2262 case Decl::ObjCAtDefsField:
2263 case Decl::ObjCIvar:
2264 llvm_unreachable("forming non-member reference to ivar?");
2265 return ExprError();
2266
2267 // Enum constants are always r-values and never references.
2268 // Unresolved using declarations are dependent.
2269 case Decl::EnumConstant:
2270 case Decl::UnresolvedUsingValue:
2271 valueKind = VK_RValue;
2272 break;
2273
2274 // Fields and indirect fields that got here must be for
2275 // pointer-to-member expressions; we just call them l-values for
2276 // internal consistency, because this subexpression doesn't really
2277 // exist in the high-level semantics.
2278 case Decl::Field:
2279 case Decl::IndirectField:
2280 assert(getLangOptions().CPlusPlus &&
2281 "building reference to field in C?");
2282
2283 // These can't have reference type in well-formed programs, but
2284 // for internal consistency we do this anyway.
2285 type = type.getNonReferenceType();
2286 valueKind = VK_LValue;
2287 break;
2288
2289 // Non-type template parameters are either l-values or r-values
2290 // depending on the type.
2291 case Decl::NonTypeTemplateParm: {
2292 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2293 type = reftype->getPointeeType();
2294 valueKind = VK_LValue; // even if the parameter is an r-value reference
2295 break;
2296 }
2297
2298 // For non-references, we need to strip qualifiers just in case
2299 // the template parameter was declared as 'const int' or whatever.
2300 valueKind = VK_RValue;
2301 type = type.getUnqualifiedType();
2302 break;
2303 }
2304
2305 case Decl::Var:
2306 // In C, "extern void blah;" is valid and is an r-value.
2307 if (!getLangOptions().CPlusPlus &&
2308 !type.hasQualifiers() &&
2309 type->isVoidType()) {
2310 valueKind = VK_RValue;
2311 break;
2312 }
2313 // fallthrough
2314
2315 case Decl::ImplicitParam:
2316 case Decl::ParmVar:
2317 // These are always l-values.
2318 valueKind = VK_LValue;
2319 type = type.getNonReferenceType();
2320 break;
2321
2322 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002323 const FunctionType *fty = type->castAs<FunctionType>();
2324
2325 // If we're referring to a function with an __unknown_anytype
2326 // result type, make the entire expression __unknown_anytype.
2327 if (fty->getResultType() == Context.UnknownAnyTy) {
2328 type = Context.UnknownAnyTy;
2329 valueKind = VK_RValue;
2330 break;
2331 }
2332
John McCall76a40212011-02-09 01:13:10 +00002333 // Functions are l-values in C++.
2334 if (getLangOptions().CPlusPlus) {
2335 valueKind = VK_LValue;
2336 break;
2337 }
2338
2339 // C99 DR 316 says that, if a function type comes from a
2340 // function definition (without a prototype), that type is only
2341 // used for checking compatibility. Therefore, when referencing
2342 // the function, we pretend that we don't have the full function
2343 // type.
John McCall755d8492011-04-12 00:42:48 +00002344 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2345 isa<FunctionProtoType>(fty))
2346 type = Context.getFunctionNoProtoType(fty->getResultType(),
2347 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002348
2349 // Functions are r-values in C.
2350 valueKind = VK_RValue;
2351 break;
2352 }
2353
2354 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002355 // If we're referring to a method with an __unknown_anytype
2356 // result type, make the entire expression __unknown_anytype.
2357 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002358 if (const FunctionProtoType *proto
2359 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002360 if (proto->getResultType() == Context.UnknownAnyTy) {
2361 type = Context.UnknownAnyTy;
2362 valueKind = VK_RValue;
2363 break;
2364 }
2365
John McCall76a40212011-02-09 01:13:10 +00002366 // C++ methods are l-values if static, r-values if non-static.
2367 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2368 valueKind = VK_LValue;
2369 break;
2370 }
2371 // fallthrough
2372
2373 case Decl::CXXConversion:
2374 case Decl::CXXDestructor:
2375 case Decl::CXXConstructor:
2376 valueKind = VK_RValue;
2377 break;
2378 }
2379
2380 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2381 }
2382
John McCall469a1eb2011-02-02 13:00:07 +00002383 }
John McCallf89e55a2010-11-18 06:31:45 +00002384
John McCall6b5a61b2011-02-07 10:33:21 +00002385 llvm_unreachable("unknown capture result");
2386 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002387}
2388
John McCall755d8492011-04-12 00:42:48 +00002389ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002390 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002391
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002393 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002394 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2395 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2396 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002398
Chris Lattnerfa28b302008-01-12 08:14:25 +00002399 // Pre-defined identifiers are of type char[x], where x is the length of the
2400 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Anders Carlsson3a082d82009-09-08 18:24:21 +00002402 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002403 if (!currentDecl && getCurBlock())
2404 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002405 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002406 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002407 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002408 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002409
Anders Carlsson773f3972009-09-11 01:22:35 +00002410 QualType ResTy;
2411 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2412 ResTy = Context.DependentTy;
2413 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002414 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002415
Anders Carlsson773f3972009-09-11 01:22:35 +00002416 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002417 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002418 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2419 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002420 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002421}
2422
John McCall60d7b3a2010-08-24 06:29:42 +00002423ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002425 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002426 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002427 if (Invalid)
2428 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002429
Benjamin Kramerddeea562010-02-27 13:44:12 +00002430 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002431 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002433 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002434
Chris Lattnere8337df2009-12-30 21:19:39 +00002435 QualType Ty;
2436 if (!getLangOptions().CPlusPlus)
2437 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2438 else if (Literal.isWide())
2439 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002440 else if (Literal.isUTF16())
2441 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2442 else if (Literal.isUTF32())
2443 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002444 else if (Literal.isMultiChar())
2445 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002446 else
2447 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002448
Douglas Gregor5cee1192011-07-27 05:40:30 +00002449 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2450 if (Literal.isWide())
2451 Kind = CharacterLiteral::Wide;
2452 else if (Literal.isUTF16())
2453 Kind = CharacterLiteral::UTF16;
2454 else if (Literal.isUTF32())
2455 Kind = CharacterLiteral::UTF32;
2456
2457 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2458 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002459}
2460
John McCall60d7b3a2010-08-24 06:29:42 +00002461ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002462 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2464 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002465 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002466 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002467 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002468 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 }
Ted Kremenek28396602009-01-13 23:19:12 +00002470
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002472 // Add padding so that NumericLiteralParser can overread by one character.
2473 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002474 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002475
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002477 bool Invalid = false;
2478 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2479 if (Invalid)
2480 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002481
Mike Stump1eb44332009-09-09 15:08:12 +00002482 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 Tok.getLocation(), PP);
2484 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002485 return ExprError();
2486
Chris Lattner5d661452007-08-26 03:42:43 +00002487 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002488
Chris Lattner5d661452007-08-26 03:42:43 +00002489 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002490 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002491 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002492 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002493 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002494 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002495 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002496 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002497
2498 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2499
John McCall94c939d2009-12-24 09:08:04 +00002500 using llvm::APFloat;
2501 APFloat Val(Format);
2502
2503 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002504
2505 // Overflow is always an error, but underflow is only an error if
2506 // we underflowed to zero (APFloat reports denormals as underflow).
2507 if ((result & APFloat::opOverflow) ||
2508 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002509 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002510 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002511 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002512 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002513 APFloat::getLargest(Format).toString(buffer);
2514 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002515 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002516 APFloat::getSmallest(Format).toString(buffer);
2517 }
2518
2519 Diag(Tok.getLocation(), diagnostic)
2520 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002521 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002522 }
2523
2524 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002525 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002526
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002527 if (Ty == Context.DoubleTy) {
2528 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002529 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002530 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2531 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002532 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002533 }
2534 }
Chris Lattner5d661452007-08-26 03:42:43 +00002535 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002536 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002537 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002538 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002539
Neil Boothb9449512007-08-29 22:00:19 +00002540 // long long is a C99 feature.
2541 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002542 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002543 Diag(Tok.getLocation(), diag::ext_longlong);
2544
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002546 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002547
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 if (Literal.GetIntegerValue(ResultVal)) {
2549 // If this value didn't fit into uintmax_t, warn and force to ull.
2550 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002551 Ty = Context.UnsignedLongLongTy;
2552 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002553 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 } else {
2555 // If this value fits into a ULL, try to figure out what else it fits into
2556 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002557
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2559 // be an unsigned int.
2560 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2561
2562 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002563 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002564 if (!Literal.isLong && !Literal.isLongLong) {
2565 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002566 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002567
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 // Does it fit in a unsigned int?
2569 if (ResultVal.isIntN(IntSize)) {
2570 // Does it fit in a signed int?
2571 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002572 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002574 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002575 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002578
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002580 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002581 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002582
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 // Does it fit in a unsigned long?
2584 if (ResultVal.isIntN(LongSize)) {
2585 // Does it fit in a signed long?
2586 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002587 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002589 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002590 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002592 }
2593
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002595 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002596 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002597
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 // Does it fit in a unsigned long long?
2599 if (ResultVal.isIntN(LongLongSize)) {
2600 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002601 // To be compatible with MSVC, hex integer literals ending with the
2602 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002603 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet62ec1f22011-09-17 17:15:52 +00002604 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002605 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002607 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002608 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002609 }
2610 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // If we still couldn't decide a type, we probably have something that
2613 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002614 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002616 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002617 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002620 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002621 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002623 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002625
Chris Lattner5d661452007-08-26 03:42:43 +00002626 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2627 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002628 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002629 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002630
2631 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002632}
2633
Richard Trieuccd891a2011-09-09 01:45:06 +00002634ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002635 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002636 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002637}
2638
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002639static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2640 SourceLocation Loc,
2641 SourceRange ArgRange) {
2642 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2643 // scalar or vector data type argument..."
2644 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2645 // type (C99 6.2.5p18) or void.
2646 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2647 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2648 << T << ArgRange;
2649 return true;
2650 }
2651
2652 assert((T->isVoidType() || !T->isIncompleteType()) &&
2653 "Scalar types should always be complete");
2654 return false;
2655}
2656
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002657static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2658 SourceLocation Loc,
2659 SourceRange ArgRange,
2660 UnaryExprOrTypeTrait TraitKind) {
2661 // C99 6.5.3.4p1:
2662 if (T->isFunctionType()) {
2663 // alignof(function) is allowed as an extension.
2664 if (TraitKind == UETT_SizeOf)
2665 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2666 return false;
2667 }
2668
2669 // Allow sizeof(void)/alignof(void) as an extension.
2670 if (T->isVoidType()) {
2671 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2672 return false;
2673 }
2674
2675 return true;
2676}
2677
2678static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2679 SourceLocation Loc,
2680 SourceRange ArgRange,
2681 UnaryExprOrTypeTrait TraitKind) {
2682 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2683 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2684 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2685 << T << (TraitKind == UETT_SizeOf)
2686 << ArgRange;
2687 return true;
2688 }
2689
2690 return false;
2691}
2692
Chandler Carruth9d342d02011-05-26 08:53:10 +00002693/// \brief Check the constrains on expression operands to unary type expression
2694/// and type traits.
2695///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002696/// Completes any types necessary and validates the constraints on the operand
2697/// expression. The logic mostly mirrors the type-based overload, but may modify
2698/// the expression as it completes the type for that expression through template
2699/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002700bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002701 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002702 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002703
2704 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2705 // the result is the size of the referenced type."
2706 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2707 // result shall be the alignment of the referenced type."
2708 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2709 ExprTy = Ref->getPointeeType();
2710
2711 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002712 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2713 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002714
2715 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002716 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2717 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002718 return false;
2719
Richard Trieuccd891a2011-09-09 01:45:06 +00002720 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002721 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002722 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002723 std::make_pair(SourceLocation(), PDiag(0))))
2724 return true;
2725
2726 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002727 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002728 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2729 ExprTy = Ref->getPointeeType();
2730
Richard Trieuccd891a2011-09-09 01:45:06 +00002731 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2732 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002733 return true;
2734
Nico Webercf739922011-06-15 02:47:03 +00002735 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002736 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002737 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2738 QualType OType = PVD->getOriginalType();
2739 QualType Type = PVD->getType();
2740 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002741 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002742 << Type << OType;
2743 Diag(PVD->getLocation(), diag::note_declared_at);
2744 }
2745 }
2746 }
2747 }
2748
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002749 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002750}
2751
2752/// \brief Check the constraints on operands to unary expression and type
2753/// traits.
2754///
2755/// This will complete any types necessary, and validate the various constraints
2756/// on those operands.
2757///
Reid Spencer5f016e22007-07-11 17:01:13 +00002758/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002759/// C99 6.3.2.1p[2-4] all state:
2760/// Except when it is the operand of the sizeof operator ...
2761///
2762/// C++ [expr.sizeof]p4
2763/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2764/// standard conversions are not applied to the operand of sizeof.
2765///
2766/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002767bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002768 SourceLocation OpLoc,
2769 SourceRange ExprRange,
2770 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002771 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002772 return false;
2773
Sebastian Redl5d484e82009-11-23 17:18:46 +00002774 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2775 // the result is the size of the referenced type."
2776 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2777 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002778 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2779 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002780
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002781 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002782 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002783
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002784 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002785 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002786 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002787 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Richard Trieuccd891a2011-09-09 01:45:06 +00002789 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002790 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002791 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002792 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Richard Trieuccd891a2011-09-09 01:45:06 +00002794 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002795 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002796 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Chris Lattner1efaa952009-04-24 00:30:45 +00002798 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002799}
2800
Chandler Carruth9d342d02011-05-26 08:53:10 +00002801static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002802 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002803
Mike Stump1eb44332009-09-09 15:08:12 +00002804 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002805 if (isa<DeclRefExpr>(E))
2806 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002807
2808 // Cannot know anything else if the expression is dependent.
2809 if (E->isTypeDependent())
2810 return false;
2811
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002812 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002813 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2814 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002815 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002816 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002817
2818 // Alignment of a field access is always okay, so long as it isn't a
2819 // bit-field.
2820 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002821 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002822 return false;
2823
Chandler Carruth9d342d02011-05-26 08:53:10 +00002824 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002825}
2826
Chandler Carruth9d342d02011-05-26 08:53:10 +00002827bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002828 E = E->IgnoreParens();
2829
2830 // Cannot know anything else if the expression is dependent.
2831 if (E->isTypeDependent())
2832 return false;
2833
Chandler Carruth9d342d02011-05-26 08:53:10 +00002834 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002835}
2836
Douglas Gregorba498172009-03-13 21:01:28 +00002837/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002838ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002839Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2840 SourceLocation OpLoc,
2841 UnaryExprOrTypeTrait ExprKind,
2842 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002843 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002844 return ExprError();
2845
John McCalla93c9342009-12-07 02:54:59 +00002846 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002847
Douglas Gregorba498172009-03-13 21:01:28 +00002848 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002849 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002850 return ExprError();
2851
2852 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002853 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2854 Context.getSizeType(),
2855 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002856}
2857
2858/// \brief Build a sizeof or alignof expression given an expression
2859/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002860ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002861Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2862 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002863 ExprResult PE = CheckPlaceholderExpr(E);
2864 if (PE.isInvalid())
2865 return ExprError();
2866
2867 E = PE.get();
2868
Douglas Gregorba498172009-03-13 21:01:28 +00002869 // Verify that the operand is valid.
2870 bool isInvalid = false;
2871 if (E->isTypeDependent()) {
2872 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002873 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002874 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002875 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002876 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002877 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002878 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002879 isInvalid = true;
2880 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002881 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002882 }
2883
2884 if (isInvalid)
2885 return ExprError();
2886
2887 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002888 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002889 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002890 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002891}
2892
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002893/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2894/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002895/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002896ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002897Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002898 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002899 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002901 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002902
Richard Trieuccd891a2011-09-09 01:45:06 +00002903 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00002904 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002905 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002906 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002907 }
Sebastian Redl05189992008-11-11 17:56:53 +00002908
Douglas Gregorba498172009-03-13 21:01:28 +00002909 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002910 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002911 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002912}
2913
John Wiegley429bb272011-04-08 18:41:53 +00002914static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002915 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002916 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002917 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002918
John McCallf6a16482010-12-04 03:47:34 +00002919 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002920 if (V.get()->getObjectKind() != OK_Ordinary) {
2921 V = S.DefaultLvalueConversion(V.take());
2922 if (V.isInvalid())
2923 return QualType();
2924 }
John McCallf6a16482010-12-04 03:47:34 +00002925
Chris Lattnercc26ed72007-08-26 05:39:26 +00002926 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002927 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002928 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Chris Lattnercc26ed72007-08-26 05:39:26 +00002930 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002931 if (V.get()->getType()->isArithmeticType())
2932 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002933
John McCall2cd11fe2010-10-12 02:09:17 +00002934 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002935 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002936 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002937 if (PR.get() != V.get()) {
2938 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00002939 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002940 }
2941
Chris Lattnercc26ed72007-08-26 05:39:26 +00002942 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002943 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00002944 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002945 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002946}
2947
2948
Reid Spencer5f016e22007-07-11 17:01:13 +00002949
John McCall60d7b3a2010-08-24 06:29:42 +00002950ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002951Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002952 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002953 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 switch (Kind) {
2955 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002956 case tok::plusplus: Opc = UO_PostInc; break;
2957 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002959
John McCall9ae2f072010-08-23 23:25:46 +00002960 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002961}
2962
John McCall60d7b3a2010-08-24 06:29:42 +00002963ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002964Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2965 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002966 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002967 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002968 if (Result.isInvalid()) return ExprError();
2969 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002970
John McCall9ae2f072010-08-23 23:25:46 +00002971 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Douglas Gregor337c6b92008-11-19 17:17:41 +00002973 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002974 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002975 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002976 Context.DependentTy,
2977 VK_LValue, OK_Ordinary,
2978 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002979 }
2980
Mike Stump1eb44332009-09-09 15:08:12 +00002981 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002982 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002983 LHSExp->getType()->isEnumeralType() ||
2984 RHSExp->getType()->isRecordType() ||
2985 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002986 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002987 }
2988
John McCall9ae2f072010-08-23 23:25:46 +00002989 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002990}
2991
2992
John McCall60d7b3a2010-08-24 06:29:42 +00002993ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002994Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002995 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00002996 Expr *LHSExp = Base;
2997 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002998
Chris Lattner12d9ff62007-07-16 00:14:47 +00002999 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003000 if (!LHSExp->getType()->getAs<VectorType>()) {
3001 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3002 if (Result.isInvalid())
3003 return ExprError();
3004 LHSExp = Result.take();
3005 }
3006 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3007 if (Result.isInvalid())
3008 return ExprError();
3009 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003010
Chris Lattner12d9ff62007-07-16 00:14:47 +00003011 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003012 ExprValueKind VK = VK_LValue;
3013 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003014
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003016 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003017 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003019 Expr *BaseExpr, *IndexExpr;
3020 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003021 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3022 BaseExpr = LHSExp;
3023 IndexExpr = RHSExp;
3024 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003025 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003026 BaseExpr = LHSExp;
3027 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003028 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003029 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003030 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003031 BaseExpr = RHSExp;
3032 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003033 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003034 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003035 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003036 BaseExpr = LHSExp;
3037 IndexExpr = RHSExp;
3038 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003039 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003040 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003041 // Handle the uncommon case of "123[Ptr]".
3042 BaseExpr = RHSExp;
3043 IndexExpr = LHSExp;
3044 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003045 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003046 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003047 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003048 VK = LHSExp->getValueKind();
3049 if (VK != VK_RValue)
3050 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003051
Chris Lattner12d9ff62007-07-16 00:14:47 +00003052 // FIXME: need to deal with const...
3053 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003054 } else if (LHSTy->isArrayType()) {
3055 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003056 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003057 // wasn't promoted because of the C90 rule that doesn't
3058 // allow promoting non-lvalue arrays. Warn, then
3059 // force the promotion here.
3060 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3061 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003062 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3063 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003064 LHSTy = LHSExp->getType();
3065
3066 BaseExpr = LHSExp;
3067 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003068 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003069 } else if (RHSTy->isArrayType()) {
3070 // Same as previous, except for 123[f().a] case
3071 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3072 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003073 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3074 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003075 RHSTy = RHSExp->getType();
3076
3077 BaseExpr = RHSExp;
3078 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003079 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003080 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003081 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3082 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003083 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003084 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003085 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003086 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3087 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003088
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003089 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003090 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3091 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003092 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3093
Douglas Gregore7450f52009-03-24 19:52:54 +00003094 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003095 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3096 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003097 // incomplete types are not object types.
3098 if (ResultType->isFunctionType()) {
3099 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3100 << ResultType << BaseExpr->getSourceRange();
3101 return ExprError();
3102 }
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Abramo Bagnara46358452010-09-13 06:50:07 +00003104 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3105 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003106 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3107 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003108
3109 // C forbids expressions of unqualified void type from being l-values.
3110 // See IsCForbiddenLValueType.
3111 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003112 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003113 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003114 PDiag(diag::err_subscript_incomplete_type)
3115 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003116 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Chris Lattner1efaa952009-04-24 00:30:45 +00003118 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003119 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003120 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3121 << ResultType << BaseExpr->getSourceRange();
3122 return ExprError();
3123 }
Mike Stump1eb44332009-09-09 15:08:12 +00003124
John McCall09431682010-11-18 19:01:18 +00003125 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003126 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003127
Mike Stumpeed9cac2009-02-19 03:04:26 +00003128 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003129 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003130}
3131
John McCall60d7b3a2010-08-24 06:29:42 +00003132ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003133 FunctionDecl *FD,
3134 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003135 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003136 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003137 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003138 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003139 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003140 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003141 return ExprError();
3142 }
3143
3144 if (Param->hasUninstantiatedDefaultArg()) {
3145 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003146
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003147 // Instantiate the expression.
3148 MultiLevelTemplateArgumentList ArgList
3149 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003150
Nico Weber08e41a62010-11-29 18:19:25 +00003151 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003152 = ArgList.getInnermost();
3153 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3154 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003155
Nico Weber08e41a62010-11-29 18:19:25 +00003156 ExprResult Result;
3157 {
3158 // C++ [dcl.fct.default]p5:
3159 // The names in the [default argument] expression are bound, and
3160 // the semantic constraints are checked, at the point where the
3161 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003162 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003163 Result = SubstExpr(UninstExpr, ArgList);
3164 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003165 if (Result.isInvalid())
3166 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003168 // Check the expression as an initializer for the parameter.
3169 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003170 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003171 InitializationKind Kind
3172 = InitializationKind::CreateCopy(Param->getLocation(),
3173 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3174 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003175
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003176 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3177 Result = InitSeq.Perform(*this, Entity, Kind,
3178 MultiExprArg(*this, &ResultE, 1));
3179 if (Result.isInvalid())
3180 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003181
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003182 // Build the default argument expression.
3183 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3184 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003185 }
3186
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003187 // If the default expression creates temporaries, we need to
3188 // push them to the current stack of expression temporaries so they'll
3189 // be properly destroyed.
3190 // FIXME: We should really be rebuilding the default argument with new
3191 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003192 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3193 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3194 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3195 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3196 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003197 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003198 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003199
3200 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003201 // Just mark all of the declarations in this potentially-evaluated expression
3202 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003203 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003204 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003205}
3206
Douglas Gregor88a35142008-12-22 05:46:06 +00003207/// ConvertArgumentsForCall - Converts the arguments specified in
3208/// Args/NumArgs to the parameter types of the function FDecl with
3209/// function prototype Proto. Call is the call expression itself, and
3210/// Fn is the function expression. For a C++ member function, this
3211/// routine does not attempt to convert the object argument. Returns
3212/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003213bool
3214Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003215 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003216 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003217 Expr **Args, unsigned NumArgs,
3218 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003219 // Bail out early if calling a builtin with custom typechecking.
3220 // We don't need to do this in the
3221 if (FDecl)
3222 if (unsigned ID = FDecl->getBuiltinID())
3223 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3224 return false;
3225
Mike Stumpeed9cac2009-02-19 03:04:26 +00003226 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003227 // assignment, to the types of the corresponding parameter, ...
3228 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003229 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003230
Douglas Gregor88a35142008-12-22 05:46:06 +00003231 // If too few arguments are available (and we don't have default
3232 // arguments for the remaining parameters), don't make the call.
3233 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003234 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3235 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003236 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003237 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003238
3239 // Emit the location of the prototype.
3240 if (FDecl && !FDecl->getBuiltinID())
3241 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3242 << FDecl;
3243
3244 return true;
3245 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003246 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003247 }
3248
3249 // If too many are passed and not variadic, error on the extras and drop
3250 // them.
3251 if (NumArgs > NumArgsInProto) {
3252 if (!Proto->isVariadic()) {
3253 Diag(Args[NumArgsInProto]->getLocStart(),
3254 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003255 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003256 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003257 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3258 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003259
3260 // Emit the location of the prototype.
3261 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003262 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3263 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003264
Douglas Gregor88a35142008-12-22 05:46:06 +00003265 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003266 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003267 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003268 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003269 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003270 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003271 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003272 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3273 if (Fn->getType()->isBlockPointerType())
3274 CallType = VariadicBlock; // Block
3275 else if (isa<MemberExpr>(Fn))
3276 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003277 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003278 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003279 if (Invalid)
3280 return true;
3281 unsigned TotalNumArgs = AllArgs.size();
3282 for (unsigned i = 0; i < TotalNumArgs; ++i)
3283 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003284
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003285 return false;
3286}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003287
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003288bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3289 FunctionDecl *FDecl,
3290 const FunctionProtoType *Proto,
3291 unsigned FirstProtoArg,
3292 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003293 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003294 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003295 unsigned NumArgsInProto = Proto->getNumArgs();
3296 unsigned NumArgsToCheck = NumArgs;
3297 bool Invalid = false;
3298 if (NumArgs != NumArgsInProto)
3299 // Use default arguments for missing arguments
3300 NumArgsToCheck = NumArgsInProto;
3301 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003302 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003303 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003304 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003305
Douglas Gregor88a35142008-12-22 05:46:06 +00003306 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003307 if (ArgIx < NumArgs) {
3308 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003309
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003310 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3311 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003312 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003313 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003314 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003315
Douglas Gregora188ff22009-12-22 16:09:06 +00003316 // Pass the argument
3317 ParmVarDecl *Param = 0;
3318 if (FDecl && i < FDecl->getNumParams())
3319 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003320
Douglas Gregora188ff22009-12-22 16:09:06 +00003321 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003322 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003323 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3324 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003325 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003326 SourceLocation(),
3327 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003328 if (ArgE.isInvalid())
3329 return true;
3330
3331 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003332 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003333 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003334
John McCall60d7b3a2010-08-24 06:29:42 +00003335 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003336 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003337 if (ArgExpr.isInvalid())
3338 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003339
Anders Carlsson56c5e332009-08-25 03:49:14 +00003340 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003341 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003342
3343 // Check for array bounds violations for each argument to the call. This
3344 // check only triggers warnings when the argument isn't a more complex Expr
3345 // with its own checking, such as a BinaryOperator.
3346 CheckArrayAccess(Arg);
3347
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003348 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003349 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003350
Douglas Gregor88a35142008-12-22 05:46:06 +00003351 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003352 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003353
3354 // Assume that extern "C" functions with variadic arguments that
3355 // return __unknown_anytype aren't *really* variadic.
3356 if (Proto->getResultType() == Context.UnknownAnyTy &&
3357 FDecl && FDecl->isExternC()) {
3358 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3359 ExprResult arg;
3360 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3361 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3362 else
3363 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3364 Invalid |= arg.isInvalid();
3365 AllArgs.push_back(arg.take());
3366 }
3367
3368 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3369 } else {
3370 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003371 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3372 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003373 Invalid |= Arg.isInvalid();
3374 AllArgs.push_back(Arg.take());
3375 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003376 }
3377 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003378 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003379}
3380
John McCall755d8492011-04-12 00:42:48 +00003381/// Given a function expression of unknown-any type, try to rebuild it
3382/// to have a function type.
3383static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3384
Steve Narofff69936d2007-09-16 03:34:24 +00003385/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003386/// This provides the location of the left/right parens and a list of comma
3387/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003388ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003389Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003390 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003391 Expr *ExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003392 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003393
3394 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003395 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003396 if (Result.isInvalid()) return ExprError();
3397 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Richard Trieuccd891a2011-09-09 01:45:06 +00003399 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Douglas Gregor88a35142008-12-22 05:46:06 +00003401 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003402 // If this is a pseudo-destructor expression, build the call immediately.
3403 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3404 if (NumArgs > 0) {
3405 // Pseudo-destructor calls should not have any arguments.
3406 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003407 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003408 SourceRange(Args[0]->getLocStart(),
3409 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003410
Douglas Gregora71d8192009-09-04 17:36:40 +00003411 NumArgs = 0;
3412 }
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Douglas Gregora71d8192009-09-04 17:36:40 +00003414 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003415 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003416 }
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Douglas Gregor17330012009-02-04 15:01:18 +00003418 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003419 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003420 // FIXME: Will need to cache the results of name lookup (including ADL) in
3421 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003422 bool Dependent = false;
3423 if (Fn->isTypeDependent())
3424 Dependent = true;
3425 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3426 Dependent = true;
3427
Peter Collingbournee08ce652011-02-09 21:07:24 +00003428 if (Dependent) {
3429 if (ExecConfig) {
3430 return Owned(new (Context) CUDAKernelCallExpr(
3431 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3432 Context.DependentTy, VK_RValue, RParenLoc));
3433 } else {
3434 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3435 Context.DependentTy, VK_RValue,
3436 RParenLoc));
3437 }
3438 }
Douglas Gregor17330012009-02-04 15:01:18 +00003439
3440 // Determine whether this is a call to an object (C++ [over.call.object]).
3441 if (Fn->getType()->isRecordType())
3442 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003443 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003444
John McCall755d8492011-04-12 00:42:48 +00003445 if (Fn->getType() == Context.UnknownAnyTy) {
3446 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3447 if (result.isInvalid()) return ExprError();
3448 Fn = result.take();
3449 }
3450
John McCall864c0412011-04-26 20:42:42 +00003451 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003452 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003453 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003454 }
John McCall864c0412011-04-26 20:42:42 +00003455 }
John McCall129e2df2009-11-30 22:42:35 +00003456
John McCall864c0412011-04-26 20:42:42 +00003457 // Check for overloaded calls. This can happen even in C due to extensions.
3458 if (Fn->getType() == Context.OverloadTy) {
3459 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3460
3461 // We aren't supposed to apply this logic if there's an '&' involved.
3462 if (!find.IsAddressOfOperand) {
3463 OverloadExpr *ovl = find.Expression;
3464 if (isa<UnresolvedLookupExpr>(ovl)) {
3465 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3466 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3467 RParenLoc, ExecConfig);
3468 } else {
John McCallaa81e162009-12-01 22:10:20 +00003469 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003470 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003471 }
3472 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003473 }
3474
Douglas Gregorfa047642009-02-04 00:32:51 +00003475 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003476
Eli Friedmanefa42f72009-12-26 03:35:45 +00003477 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003478
John McCall3b4294e2009-12-16 12:17:52 +00003479 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003480 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3481 if (UnOp->getOpcode() == UO_AddrOf)
3482 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3483
John McCall3b4294e2009-12-16 12:17:52 +00003484 if (isa<DeclRefExpr>(NakedFn))
3485 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003486 else if (isa<MemberExpr>(NakedFn))
3487 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003488
Peter Collingbournee08ce652011-02-09 21:07:24 +00003489 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3490 ExecConfig);
3491}
3492
3493ExprResult
3494Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003495 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003496 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3497 if (!ConfigDecl)
3498 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3499 << "cudaConfigureCall");
3500 QualType ConfigQTy = ConfigDecl->getType();
3501
3502 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3503 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3504
Richard Trieuccd891a2011-09-09 01:45:06 +00003505 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003506}
3507
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003508/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3509///
3510/// __builtin_astype( value, dst type )
3511///
Richard Trieuccd891a2011-09-09 01:45:06 +00003512ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003513 SourceLocation BuiltinLoc,
3514 SourceLocation RParenLoc) {
3515 ExprValueKind VK = VK_RValue;
3516 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003517 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3518 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003519 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3520 return ExprError(Diag(BuiltinLoc,
3521 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003522 << DstTy
3523 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003524 << E->getSourceRange());
3525 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003526 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003527}
3528
John McCall3b4294e2009-12-16 12:17:52 +00003529/// BuildResolvedCallExpr - Build a call to a resolved expression,
3530/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003531/// unary-convert to an expression of function-pointer or
3532/// block-pointer type.
3533///
3534/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003535ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003536Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3537 SourceLocation LParenLoc,
3538 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003539 SourceLocation RParenLoc,
3540 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003541 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3542
Chris Lattner04421082008-04-08 04:40:51 +00003543 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003544 ExprResult Result = UsualUnaryConversions(Fn);
3545 if (Result.isInvalid())
3546 return ExprError();
3547 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003548
Chris Lattner925e60d2007-12-28 05:29:59 +00003549 // Make the call expr early, before semantic checks. This guarantees cleanup
3550 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003551 CallExpr *TheCall;
3552 if (Config) {
3553 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3554 cast<CallExpr>(Config),
3555 Args, NumArgs,
3556 Context.BoolTy,
3557 VK_RValue,
3558 RParenLoc);
3559 } else {
3560 TheCall = new (Context) CallExpr(Context, Fn,
3561 Args, NumArgs,
3562 Context.BoolTy,
3563 VK_RValue,
3564 RParenLoc);
3565 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003566
John McCall8e10f3b2011-02-26 05:39:39 +00003567 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3568
3569 // Bail out early if calling a builtin with custom typechecking.
3570 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3571 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3572
John McCall1de4d4e2011-04-07 08:22:57 +00003573 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003574 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003575 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003576 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3577 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003578 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003579 if (FuncT == 0)
3580 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3581 << Fn->getType() << Fn->getSourceRange());
3582 } else if (const BlockPointerType *BPT =
3583 Fn->getType()->getAs<BlockPointerType>()) {
3584 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3585 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003586 // Handle calls to expressions of unknown-any type.
3587 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003588 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003589 if (rewrite.isInvalid()) return ExprError();
3590 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003591 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003592 goto retry;
3593 }
3594
Sebastian Redl0eb23302009-01-19 00:08:26 +00003595 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3596 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003597 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003598
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003599 if (getLangOptions().CUDA) {
3600 if (Config) {
3601 // CUDA: Kernel calls must be to global functions
3602 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3603 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3604 << FDecl->getName() << Fn->getSourceRange());
3605
3606 // CUDA: Kernel function must have 'void' return type
3607 if (!FuncT->getResultType()->isVoidType())
3608 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3609 << Fn->getType() << Fn->getSourceRange());
3610 }
3611 }
3612
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003613 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003614 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003615 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003616 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003617 return ExprError();
3618
Chris Lattner925e60d2007-12-28 05:29:59 +00003619 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003620 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003621 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003622
Douglas Gregor72564e72009-02-26 23:50:07 +00003623 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003624 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003625 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003626 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003627 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003628 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003629
Douglas Gregor74734d52009-04-02 15:37:10 +00003630 if (FDecl) {
3631 // Check if we have too few/too many template arguments, based
3632 // on our knowledge of the function definition.
3633 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003634 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003635 const FunctionProtoType *Proto
3636 = Def->getType()->getAs<FunctionProtoType>();
3637 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003638 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3639 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003640 }
Douglas Gregor46542412010-10-25 20:39:23 +00003641
3642 // If the function we're calling isn't a function prototype, but we have
3643 // a function prototype from a prior declaratiom, use that prototype.
3644 if (!FDecl->hasPrototype())
3645 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003646 }
3647
Steve Naroffb291ab62007-08-28 23:30:39 +00003648 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003649 for (unsigned i = 0; i != NumArgs; i++) {
3650 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003651
3652 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003653 InitializedEntity Entity
3654 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003655 Proto->getArgType(i),
3656 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003657 ExprResult ArgE = PerformCopyInitialization(Entity,
3658 SourceLocation(),
3659 Owned(Arg));
3660 if (ArgE.isInvalid())
3661 return true;
3662
3663 Arg = ArgE.takeAs<Expr>();
3664
3665 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003666 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3667
3668 if (ArgE.isInvalid())
3669 return true;
3670
3671 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003672 }
3673
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003674 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3675 Arg->getType(),
3676 PDiag(diag::err_call_incomplete_argument)
3677 << Arg->getSourceRange()))
3678 return ExprError();
3679
Chris Lattner925e60d2007-12-28 05:29:59 +00003680 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003681 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003682 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003683
Douglas Gregor88a35142008-12-22 05:46:06 +00003684 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3685 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003686 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3687 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003688
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003689 // Check for sentinels
3690 if (NDecl)
3691 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Chris Lattner59907c42007-08-10 20:18:51 +00003693 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003694 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003695 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003696 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003697
John McCall8e10f3b2011-02-26 05:39:39 +00003698 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003699 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003700 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003701 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003702 return ExprError();
3703 }
Chris Lattner59907c42007-08-10 20:18:51 +00003704
John McCall9ae2f072010-08-23 23:25:46 +00003705 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003706}
3707
John McCall60d7b3a2010-08-24 06:29:42 +00003708ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003709Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003710 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003711 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003712 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003713 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003714
3715 TypeSourceInfo *TInfo;
3716 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3717 if (!TInfo)
3718 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3719
John McCall9ae2f072010-08-23 23:25:46 +00003720 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003721}
3722
John McCall60d7b3a2010-08-24 06:29:42 +00003723ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003724Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003725 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003726 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003727
Eli Friedman6223c222008-05-20 05:22:08 +00003728 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003729 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3730 PDiag(diag::err_illegal_decl_array_incomplete_type)
3731 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003732 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003733 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003734 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003735 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003736 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003737 } else if (!literalType->isDependentType() &&
3738 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003739 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003740 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003741 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003742 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003743
Douglas Gregor99a2e602009-12-16 01:38:02 +00003744 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003745 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003746 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003747 = InitializationKind::CreateCStyleCast(LParenLoc,
3748 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003749 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003750 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003751 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003752 &literalType);
3753 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003754 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003755 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003756
Chris Lattner371f2582008-12-04 23:50:19 +00003757 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003758 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003759 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003760 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003761 }
Eli Friedman08544622009-12-22 02:35:53 +00003762
John McCallf89e55a2010-11-18 06:31:45 +00003763 // In C, compound literals are l-values for some reason.
3764 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3765
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003766 return MaybeBindToTemporary(
3767 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003768 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003769}
3770
John McCall60d7b3a2010-08-24 06:29:42 +00003771ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00003772Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003773 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003774 unsigned NumInit = InitArgList.size();
3775 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003776
Steve Naroff08d92e42007-09-15 18:49:24 +00003777 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003778 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003779
Ted Kremenek709210f2010-04-13 23:39:13 +00003780 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3781 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003782 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003783 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003784}
3785
John McCalldc05b112011-09-10 01:16:55 +00003786/// Do an explicit extend of the given block pointer if we're in ARC.
3787static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3788 assert(E.get()->getType()->isBlockPointerType());
3789 assert(E.get()->isRValue());
3790
3791 // Only do this in an r-value context.
3792 if (!S.getLangOptions().ObjCAutoRefCount) return;
3793
3794 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00003795 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00003796 /*base path*/ 0, VK_RValue);
3797 S.ExprNeedsCleanups = true;
3798}
3799
3800/// Prepare a conversion of the given expression to an ObjC object
3801/// pointer type.
3802CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3803 QualType type = E.get()->getType();
3804 if (type->isObjCObjectPointerType()) {
3805 return CK_BitCast;
3806 } else if (type->isBlockPointerType()) {
3807 maybeExtendBlockObject(*this, E);
3808 return CK_BlockPointerToObjCPointerCast;
3809 } else {
3810 assert(type->isPointerType());
3811 return CK_CPointerToObjCPointerCast;
3812 }
3813}
3814
John McCallf3ea8cf2010-11-14 08:17:51 +00003815/// Prepares for a scalar cast, performing all the necessary stages
3816/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003817static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003818 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3819 // Also, callers should have filtered out the invalid cases with
3820 // pointers. Everything else should be possible.
3821
John Wiegley429bb272011-04-08 18:41:53 +00003822 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003823 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003824 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003825
John McCall1d9b3b22011-09-09 05:25:32 +00003826 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00003827 case Type::STK_MemberPointer:
3828 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003829
John McCall1d9b3b22011-09-09 05:25:32 +00003830 case Type::STK_CPointer:
3831 case Type::STK_BlockPointer:
3832 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003833 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003834 case Type::STK_CPointer:
3835 return CK_BitCast;
3836 case Type::STK_BlockPointer:
3837 return (SrcKind == Type::STK_BlockPointer
3838 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3839 case Type::STK_ObjCObjectPointer:
3840 if (SrcKind == Type::STK_ObjCObjectPointer)
3841 return CK_BitCast;
3842 else if (SrcKind == Type::STK_CPointer)
3843 return CK_CPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003844 else {
3845 maybeExtendBlockObject(S, Src);
John McCall1d9b3b22011-09-09 05:25:32 +00003846 return CK_BlockPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003847 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003848 case Type::STK_Bool:
3849 return CK_PointerToBoolean;
3850 case Type::STK_Integral:
3851 return CK_PointerToIntegral;
3852 case Type::STK_Floating:
3853 case Type::STK_FloatingComplex:
3854 case Type::STK_IntegralComplex:
3855 case Type::STK_MemberPointer:
3856 llvm_unreachable("illegal cast from pointer");
3857 }
3858 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003859
John McCalldaa8e4e2010-11-15 09:13:47 +00003860 case Type::STK_Bool: // casting from bool is like casting from an integer
3861 case Type::STK_Integral:
3862 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003863 case Type::STK_CPointer:
3864 case Type::STK_ObjCObjectPointer:
3865 case Type::STK_BlockPointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003866 if (Src.get()->isNullPointerConstant(S.Context,
3867 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003868 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003869 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003870 case Type::STK_Bool:
3871 return CK_IntegralToBoolean;
3872 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003873 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003874 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003875 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003876 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003877 Src = S.ImpCastExprToType(Src.take(),
3878 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003879 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003880 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003881 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003882 Src = S.ImpCastExprToType(Src.take(),
3883 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003884 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003885 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003886 case Type::STK_MemberPointer:
3887 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003888 }
3889 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003890
John McCalldaa8e4e2010-11-15 09:13:47 +00003891 case Type::STK_Floating:
3892 switch (DestTy->getScalarTypeKind()) {
3893 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003894 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003895 case Type::STK_Bool:
3896 return CK_FloatingToBoolean;
3897 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003898 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003899 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003900 Src = S.ImpCastExprToType(Src.take(),
3901 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003902 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003903 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003904 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003905 Src = S.ImpCastExprToType(Src.take(),
3906 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003907 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003908 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00003909 case Type::STK_CPointer:
3910 case Type::STK_ObjCObjectPointer:
3911 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003912 llvm_unreachable("valid float->pointer cast?");
3913 case Type::STK_MemberPointer:
3914 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003915 }
3916 break;
3917
John McCalldaa8e4e2010-11-15 09:13:47 +00003918 case Type::STK_FloatingComplex:
3919 switch (DestTy->getScalarTypeKind()) {
3920 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003921 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003922 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003923 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003924 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003925 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003926 if (S.Context.hasSameType(ET, DestTy))
3927 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003928 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003929 return CK_FloatingCast;
3930 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003931 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003932 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003933 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003934 Src = S.ImpCastExprToType(Src.take(),
3935 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003936 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003937 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00003938 case Type::STK_CPointer:
3939 case Type::STK_ObjCObjectPointer:
3940 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003941 llvm_unreachable("valid complex float->pointer cast?");
3942 case Type::STK_MemberPointer:
3943 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003944 }
3945 break;
3946
John McCalldaa8e4e2010-11-15 09:13:47 +00003947 case Type::STK_IntegralComplex:
3948 switch (DestTy->getScalarTypeKind()) {
3949 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003950 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003951 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003952 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003953 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003954 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003955 if (S.Context.hasSameType(ET, DestTy))
3956 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003957 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003958 return CK_IntegralCast;
3959 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003960 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003961 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003962 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003963 Src = S.ImpCastExprToType(Src.take(),
3964 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003965 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003966 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00003967 case Type::STK_CPointer:
3968 case Type::STK_ObjCObjectPointer:
3969 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003970 llvm_unreachable("valid complex int->pointer cast?");
3971 case Type::STK_MemberPointer:
3972 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003973 }
3974 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003975 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003976
John McCallf3ea8cf2010-11-14 08:17:51 +00003977 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00003978}
3979
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003980/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuccd891a2011-09-09 01:45:06 +00003981ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
3982 SourceRange TypeRange, QualType CastType,
3983 Expr *CastExpr, CastKind &Kind,
3984 ExprValueKind &VK, CXXCastPath &BasePath,
3985 bool FunctionalStyle) {
3986 if (CastExpr->getType() == Context.UnknownAnyTy)
3987 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
3988 BasePath);
John McCall1de4d4e2011-04-07 08:22:57 +00003989
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003990 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003991 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003992 CastExpr->getLocEnd()),
3993 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003994 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003995
Richard Trieuccd891a2011-09-09 01:45:06 +00003996 assert(!CastExpr->getType()->isPlaceholderType());
John McCallfb8721c2011-04-10 19:13:55 +00003997
John McCallf89e55a2010-11-18 06:31:45 +00003998 // We only support r-value casts in C.
3999 VK = VK_RValue;
4000
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004001 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4002 // type needs to be scalar.
Richard Trieuccd891a2011-09-09 01:45:06 +00004003 if (CastType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004004 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuccd891a2011-09-09 01:45:06 +00004005 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004006 if (castExprRes.isInvalid())
4007 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004008 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004009
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004010 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004011 Kind = CK_ToVoid;
Richard Trieuccd891a2011-09-09 01:45:06 +00004012 return Owned(CastExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004013 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004014
Richard Trieuccd891a2011-09-09 01:45:06 +00004015 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004016 if (castExprRes.isInvalid())
4017 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004018 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004019
Richard Trieuccd891a2011-09-09 01:45:06 +00004020 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedman8d438082010-07-17 20:43:49 +00004021 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004022 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004023
Richard Trieuccd891a2011-09-09 01:45:06 +00004024 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4025 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4026 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004027 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004028 // FIXME: Check that the cast destination type is complete.
Richard Trieuccd891a2011-09-09 01:45:06 +00004029 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4030 << CastType << CastExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004031 Kind = CK_NoOp;
Richard Trieuccd891a2011-09-09 01:45:06 +00004032 return Owned(CastExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004033 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004034
Richard Trieuccd891a2011-09-09 01:45:06 +00004035 if (CastType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004036 // GCC cast to union extension
Richard Trieuccd891a2011-09-09 01:45:06 +00004037 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004038 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004039 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004040 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004041 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004042 CastExpr->getType()) &&
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004043 !Field->isUnnamedBitfield()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004044 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4045 << CastExpr->getSourceRange();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004046 break;
4047 }
4048 }
John Wiegley429bb272011-04-08 18:41:53 +00004049 if (Field == FieldEnd) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004050 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4051 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004052 return ExprError();
4053 }
John McCall2de56d12010-08-25 11:45:40 +00004054 Kind = CK_ToUnion;
Richard Trieuccd891a2011-09-09 01:45:06 +00004055 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004056 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004057
Anders Carlssonc3516322009-10-16 02:48:28 +00004058 // Reject any other conversions to non-scalar types.
Richard Trieuccd891a2011-09-09 01:45:06 +00004059 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4060 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004061 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004062 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004063
John McCallf3ea8cf2010-11-14 08:17:51 +00004064 // The type we're casting to is known to be a scalar or vector.
4065
4066 // Require the operand to be a scalar or vector.
Richard Trieuccd891a2011-09-09 01:45:06 +00004067 if (!CastExpr->getType()->isScalarType() &&
4068 !CastExpr->getType()->isVectorType()) {
4069 Diag(CastExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004070 diag::err_typecheck_expect_scalar_operand)
Richard Trieuccd891a2011-09-09 01:45:06 +00004071 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004072 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004073 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004074
Richard Trieuccd891a2011-09-09 01:45:06 +00004075 if (CastType->isExtVectorType())
4076 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004077
Richard Trieuccd891a2011-09-09 01:45:06 +00004078 if (CastType->isVectorType()) {
4079 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsevd06fea82011-03-27 09:32:40 +00004080 VectorType::AltiVecVector &&
Richard Trieuccd891a2011-09-09 01:45:06 +00004081 (CastExpr->getType()->isIntegerType() ||
4082 CastExpr->getType()->isFloatingType())) {
Anton Yartsevd06fea82011-03-27 09:32:40 +00004083 Kind = CK_VectorSplat;
Richard Trieuccd891a2011-09-09 01:45:06 +00004084 return Owned(CastExpr);
4085 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4086 Kind)) {
John Wiegley429bb272011-04-08 18:41:53 +00004087 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004088 } else
Richard Trieuccd891a2011-09-09 01:45:06 +00004089 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004090 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004091 if (CastExpr->getType()->isVectorType()) {
4092 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley429bb272011-04-08 18:41:53 +00004093 return ExprError();
4094 else
Richard Trieuccd891a2011-09-09 01:45:06 +00004095 return Owned(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004096 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004097
John McCallf3ea8cf2010-11-14 08:17:51 +00004098 // The source and target types are both scalars, i.e.
4099 // - arithmetic types (fundamental, enum, and complex)
4100 // - all kinds of pointers
4101 // Note that member pointers were filtered out with C++, above.
4102
Richard Trieuccd891a2011-09-09 01:45:06 +00004103 if (isa<ObjCSelectorExpr>(CastExpr)) {
4104 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley429bb272011-04-08 18:41:53 +00004105 return ExprError();
4106 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004107
John McCallf3ea8cf2010-11-14 08:17:51 +00004108 // If either type is a pointer, the other type has to be either an
4109 // integer or a pointer.
Richard Trieuccd891a2011-09-09 01:45:06 +00004110 QualType CastExprType = CastExpr->getType();
4111 if (!CastType->isArithmeticType()) {
4112 if (!CastExprType->isIntegralType(Context) &&
4113 CastExprType->isArithmeticType()) {
4114 Diag(CastExpr->getLocStart(),
John Wiegley429bb272011-04-08 18:41:53 +00004115 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuccd891a2011-09-09 01:45:06 +00004116 << CastExprType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004117 return ExprError();
4118 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004119 } else if (!CastExpr->getType()->isArithmeticType()) {
4120 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4121 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4122 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004123 return ExprError();
4124 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004125 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004126
John McCallf85e1932011-06-15 23:02:42 +00004127 if (getLangOptions().ObjCAutoRefCount) {
4128 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuccd891a2011-09-09 01:45:06 +00004129 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4130 CastType, CastExpr, CCK_CStyleCast);
John McCallf85e1932011-06-15 23:02:42 +00004131
Richard Trieuccd891a2011-09-09 01:45:06 +00004132 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4133 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCallf85e1932011-06-15 23:02:42 +00004134 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4135 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4136 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4137 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4138 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004139 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004140 diag::err_typecheck_incompatible_ownership)
Richard Trieuccd891a2011-09-09 01:45:06 +00004141 << CastExprType << CastType << AA_Casting
4142 << CastExpr->getSourceRange();
John McCallf85e1932011-06-15 23:02:42 +00004143
4144 return ExprError();
4145 }
4146 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004147 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004148 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4149 Diag(CastExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004150 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuccd891a2011-09-09 01:45:06 +00004151 << CastExprType << CastType
4152 << CastExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004153 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004154 }
4155 }
4156
Richard Trieuccd891a2011-09-09 01:45:06 +00004157 castExprRes = Owned(CastExpr);
4158 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley429bb272011-04-08 18:41:53 +00004159 if (castExprRes.isInvalid())
4160 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004161 CastExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004162
John McCallf3ea8cf2010-11-14 08:17:51 +00004163 if (Kind == CK_BitCast)
Richard Trieuccd891a2011-09-09 01:45:06 +00004164 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCallb7f4ffe2010-08-12 21:44:57 +00004165
Richard Trieuccd891a2011-09-09 01:45:06 +00004166 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004167}
4168
Anders Carlssonc3516322009-10-16 02:48:28 +00004169bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004170 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004171 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004172
Anders Carlssona64db8f2007-11-27 05:51:55 +00004173 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004174 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004175 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004176 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004177 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004178 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004179 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004180 } else
4181 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004182 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004183 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004184
John McCall2de56d12010-08-25 11:45:40 +00004185 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004186 return false;
4187}
4188
John Wiegley429bb272011-04-08 18:41:53 +00004189ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4190 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004191 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004192
Anders Carlsson16a89042009-10-16 05:23:41 +00004193 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004194
Nate Begeman9b10da62009-06-27 22:05:55 +00004195 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4196 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004197 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004198 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4199 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004200 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004201 return ExprError();
4202 }
John McCall2de56d12010-08-25 11:45:40 +00004203 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004204 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004205 }
4206
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004207 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004208 // conversion will take place first from scalar to elt type, and then
4209 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004210 if (SrcTy->isPointerType())
4211 return Diag(R.getBegin(),
4212 diag::err_invalid_conversion_between_vector_and_scalar)
4213 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004214
4215 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004216 ExprResult CastExprRes = Owned(CastExpr);
4217 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4218 if (CastExprRes.isInvalid())
4219 return ExprError();
4220 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004221
John McCall2de56d12010-08-25 11:45:40 +00004222 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004223 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004224}
4225
John McCall60d7b3a2010-08-24 06:29:42 +00004226ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004227Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4228 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004229 SourceLocation RParenLoc, Expr *CastExpr) {
4230 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004231 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004232
Richard Trieuccd891a2011-09-09 01:45:06 +00004233 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004234 if (D.isInvalidType())
4235 return ExprError();
4236
4237 if (getLangOptions().CPlusPlus) {
4238 // Check that there are no default arguments (C++ only).
4239 CheckExtraCXXDefaultArguments(D);
4240 }
4241
4242 QualType castType = castTInfo->getType();
4243 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004244
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004245 bool isVectorLiteral = false;
4246
4247 // Check for an altivec or OpenCL literal,
4248 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004249 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4250 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser37c31c22011-09-21 18:28:29 +00004251 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4252 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004253 if (PLE && PLE->getNumExprs() == 0) {
4254 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4255 return ExprError();
4256 }
4257 if (PE || PLE->getNumExprs() == 1) {
4258 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4259 if (!E->getType()->isVectorType())
4260 isVectorLiteral = true;
4261 }
4262 else
4263 isVectorLiteral = true;
4264 }
4265
4266 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4267 // then handle it as such.
4268 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004269 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004270
Nate Begeman2ef13e52009-08-10 23:49:36 +00004271 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004272 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4273 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004274 if (isa<ParenListExpr>(CastExpr)) {
4275 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004276 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004277 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004278 }
John McCallb042fdf2010-01-15 18:56:44 +00004279
Richard Trieuccd891a2011-09-09 01:45:06 +00004280 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004281}
4282
John McCall60d7b3a2010-08-24 06:29:42 +00004283ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004284Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004285 SourceLocation RParenLoc, Expr *CastExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004286 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004287 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004288 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004289 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004290 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004291 CastExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004292 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004293 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004294 CastExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004295
Richard Trieu67e29332011-08-02 04:35:43 +00004296 return Owned(CStyleCastExpr::Create(
Richard Trieuccd891a2011-09-09 01:45:06 +00004297 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieu67e29332011-08-02 04:35:43 +00004298 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004299}
4300
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004301ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4302 SourceLocation RParenLoc, Expr *E,
4303 TypeSourceInfo *TInfo) {
4304 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4305 "Expected paren or paren list expression");
4306
4307 Expr **exprs;
4308 unsigned numExprs;
4309 Expr *subExpr;
4310 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4311 exprs = PE->getExprs();
4312 numExprs = PE->getNumExprs();
4313 } else {
4314 subExpr = cast<ParenExpr>(E)->getSubExpr();
4315 exprs = &subExpr;
4316 numExprs = 1;
4317 }
4318
4319 QualType Ty = TInfo->getType();
4320 assert(Ty->isVectorType() && "Expected vector type");
4321
Chris Lattner5f9e2722011-07-23 10:55:15 +00004322 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004323 const VectorType *VTy = Ty->getAs<VectorType>();
4324 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4325
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004326 // '(...)' form of vector initialization in AltiVec: the number of
4327 // initializers must be one or must match the size of the vector.
4328 // If a single value is specified in the initializer then it will be
4329 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004330 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004331 // The number of initializers must be one or must match the size of the
4332 // vector. If a single value is specified in the initializer then it will
4333 // be replicated to all the components of the vector
4334 if (numExprs == 1) {
4335 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4336 ExprResult Literal = Owned(exprs[0]);
4337 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4338 PrepareScalarCast(*this, Literal, ElemTy));
4339 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4340 }
4341 else if (numExprs < numElems) {
4342 Diag(E->getExprLoc(),
4343 diag::err_incorrect_number_of_vector_initializers);
4344 return ExprError();
4345 }
4346 else
4347 for (unsigned i = 0, e = numExprs; i != e; ++i)
4348 initExprs.push_back(exprs[i]);
4349 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004350 else {
4351 // For OpenCL, when the number of initializers is a single value,
4352 // it will be replicated to all components of the vector.
4353 if (getLangOptions().OpenCL &&
4354 VTy->getVectorKind() == VectorType::GenericVector &&
4355 numExprs == 1) {
4356 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4357 ExprResult Literal = Owned(exprs[0]);
4358 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4359 PrepareScalarCast(*this, Literal, ElemTy));
4360 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4361 }
4362
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004363 for (unsigned i = 0, e = numExprs; i != e; ++i)
4364 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004365 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004366 // FIXME: This means that pretty-printing the final AST will produce curly
4367 // braces instead of the original commas.
4368 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4369 &initExprs[0],
4370 initExprs.size(), RParenLoc);
4371 initE->setType(Ty);
4372 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4373}
4374
Nate Begeman2ef13e52009-08-10 23:49:36 +00004375/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4376/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004377ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004378Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4379 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004380 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004381 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004382
John McCall60d7b3a2010-08-24 06:29:42 +00004383 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Nate Begeman2ef13e52009-08-10 23:49:36 +00004385 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004386 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4387 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004388
John McCall9ae2f072010-08-23 23:25:46 +00004389 if (Result.isInvalid()) return ExprError();
4390
4391 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004392}
4393
John McCall60d7b3a2010-08-24 06:29:42 +00004394ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004395 SourceLocation R,
4396 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004397 unsigned nexprs = Val.size();
4398 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004399 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4400 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004401 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004402 expr = new (Context) ParenExpr(L, R, exprs[0]);
4403 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004404 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4405 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004406 return Owned(expr);
4407}
4408
Chandler Carruth82214a82011-02-18 23:54:50 +00004409/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004410/// constant and the other is not a pointer. Returns true if a diagnostic is
4411/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004412bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004413 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004414 Expr *NullExpr = LHSExpr;
4415 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004416 Expr::NullPointerConstantKind NullKind =
4417 NullExpr->isNullPointerConstant(Context,
4418 Expr::NPC_ValueDependentIsNotNull);
4419
4420 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004421 NullExpr = RHSExpr;
4422 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004423 NullKind =
4424 NullExpr->isNullPointerConstant(Context,
4425 Expr::NPC_ValueDependentIsNotNull);
4426 }
4427
4428 if (NullKind == Expr::NPCK_NotNull)
4429 return false;
4430
4431 if (NullKind == Expr::NPCK_ZeroInteger) {
4432 // In this case, check to make sure that we got here from a "NULL"
4433 // string in the source code.
4434 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004435 SourceLocation loc = NullExpr->getExprLoc();
4436 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004437 return false;
4438 }
4439
4440 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4441 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4442 << NonPointerExpr->getType() << DiagType
4443 << NonPointerExpr->getSourceRange();
4444 return true;
4445}
4446
Richard Trieu26f96072011-09-02 01:51:02 +00004447/// \brief Return false if the condition expression is valid, true otherwise.
4448static bool checkCondition(Sema &S, Expr *Cond) {
4449 QualType CondTy = Cond->getType();
4450
4451 // C99 6.5.15p2
4452 if (CondTy->isScalarType()) return false;
4453
4454 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4455 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4456 return false;
4457
4458 // Emit the proper error message.
4459 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4460 diag::err_typecheck_cond_expect_scalar :
4461 diag::err_typecheck_cond_expect_scalar_or_vector)
4462 << CondTy;
4463 return true;
4464}
4465
4466/// \brief Return false if the two expressions can be converted to a vector,
4467/// true otherwise
4468static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4469 ExprResult &RHS,
4470 QualType CondTy) {
4471 // Both operands should be of scalar type.
4472 if (!LHS.get()->getType()->isScalarType()) {
4473 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4474 << CondTy;
4475 return true;
4476 }
4477 if (!RHS.get()->getType()->isScalarType()) {
4478 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4479 << CondTy;
4480 return true;
4481 }
4482
4483 // Implicity convert these scalars to the type of the condition.
4484 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4485 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4486 return false;
4487}
4488
4489/// \brief Handle when one or both operands are void type.
4490static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4491 ExprResult &RHS) {
4492 Expr *LHSExpr = LHS.get();
4493 Expr *RHSExpr = RHS.get();
4494
4495 if (!LHSExpr->getType()->isVoidType())
4496 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4497 << RHSExpr->getSourceRange();
4498 if (!RHSExpr->getType()->isVoidType())
4499 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4500 << LHSExpr->getSourceRange();
4501 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4502 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4503 return S.Context.VoidTy;
4504}
4505
4506/// \brief Return false if the NullExpr can be promoted to PointerTy,
4507/// true otherwise.
4508static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4509 QualType PointerTy) {
4510 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4511 !NullExpr.get()->isNullPointerConstant(S.Context,
4512 Expr::NPC_ValueDependentIsNull))
4513 return true;
4514
4515 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4516 return false;
4517}
4518
4519/// \brief Checks compatibility between two pointers and return the resulting
4520/// type.
4521static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4522 ExprResult &RHS,
4523 SourceLocation Loc) {
4524 QualType LHSTy = LHS.get()->getType();
4525 QualType RHSTy = RHS.get()->getType();
4526
4527 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4528 // Two identical pointers types are always compatible.
4529 return LHSTy;
4530 }
4531
4532 QualType lhptee, rhptee;
4533
4534 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004535 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4536 lhptee = LHSBTy->getPointeeType();
4537 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004538 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004539 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4540 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004541 }
4542
4543 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4544 rhptee.getUnqualifiedType())) {
4545 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4546 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4547 << RHS.get()->getSourceRange();
4548 // In this situation, we assume void* type. No especially good
4549 // reason, but this is what gcc does, and we do have to pick
4550 // to get a consistent AST.
4551 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4552 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4553 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4554 return incompatTy;
4555 }
4556
4557 // The pointer types are compatible.
4558 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4559 // differently qualified versions of compatible types, the result type is
4560 // a pointer to an appropriately qualified version of the *composite*
4561 // type.
4562 // FIXME: Need to calculate the composite type.
4563 // FIXME: Need to add qualifiers
4564
4565 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4566 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4567 return LHSTy;
4568}
4569
4570/// \brief Return the resulting type when the operands are both block pointers.
4571static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4572 ExprResult &LHS,
4573 ExprResult &RHS,
4574 SourceLocation Loc) {
4575 QualType LHSTy = LHS.get()->getType();
4576 QualType RHSTy = RHS.get()->getType();
4577
4578 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4579 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4580 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4581 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4582 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4583 return destType;
4584 }
4585 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4586 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4587 << RHS.get()->getSourceRange();
4588 return QualType();
4589 }
4590
4591 // We have 2 block pointer types.
4592 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4593}
4594
4595/// \brief Return the resulting type when the operands are both pointers.
4596static QualType
4597checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4598 ExprResult &RHS,
4599 SourceLocation Loc) {
4600 // get the pointer types
4601 QualType LHSTy = LHS.get()->getType();
4602 QualType RHSTy = RHS.get()->getType();
4603
4604 // get the "pointed to" types
4605 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4606 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4607
4608 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4609 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4610 // Figure out necessary qualifiers (C99 6.5.15p6)
4611 QualType destPointee
4612 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4613 QualType destType = S.Context.getPointerType(destPointee);
4614 // Add qualifiers if necessary.
4615 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4616 // Promote to void*.
4617 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4618 return destType;
4619 }
4620 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4621 QualType destPointee
4622 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4623 QualType destType = S.Context.getPointerType(destPointee);
4624 // Add qualifiers if necessary.
4625 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4626 // Promote to void*.
4627 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4628 return destType;
4629 }
4630
4631 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4632}
4633
4634/// \brief Return false if the first expression is not an integer and the second
4635/// expression is not a pointer, true otherwise.
4636static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4637 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004638 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004639 if (!PointerExpr->getType()->isPointerType() ||
4640 !Int.get()->getType()->isIntegerType())
4641 return false;
4642
Richard Trieuccd891a2011-09-09 01:45:06 +00004643 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4644 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004645
4646 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4647 << Expr1->getType() << Expr2->getType()
4648 << Expr1->getSourceRange() << Expr2->getSourceRange();
4649 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4650 CK_IntegralToPointer);
4651 return true;
4652}
4653
Richard Trieu33fc7572011-09-06 20:06:39 +00004654/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4655/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004656/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004657QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4658 ExprResult &RHS, ExprValueKind &VK,
4659 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004660 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004661
Richard Trieu33fc7572011-09-06 20:06:39 +00004662 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4663 if (!LHSResult.isUsable()) return QualType();
4664 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004665
Richard Trieu33fc7572011-09-06 20:06:39 +00004666 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4667 if (!RHSResult.isUsable()) return QualType();
4668 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004669
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004670 // C++ is sufficiently different to merit its own checker.
4671 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004672 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004673
4674 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004675 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004676
John Wiegley429bb272011-04-08 18:41:53 +00004677 Cond = UsualUnaryConversions(Cond.take());
4678 if (Cond.isInvalid())
4679 return QualType();
4680 LHS = UsualUnaryConversions(LHS.take());
4681 if (LHS.isInvalid())
4682 return QualType();
4683 RHS = UsualUnaryConversions(RHS.take());
4684 if (RHS.isInvalid())
4685 return QualType();
4686
4687 QualType CondTy = Cond.get()->getType();
4688 QualType LHSTy = LHS.get()->getType();
4689 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004690
Reid Spencer5f016e22007-07-11 17:01:13 +00004691 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004692 if (checkCondition(*this, Cond.get()))
4693 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004694
Chris Lattner70d67a92008-01-06 22:42:25 +00004695 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004696 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004697 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004698
Nate Begeman6155d732010-09-20 22:41:17 +00004699 // OpenCL: If the condition is a vector, and both operands are scalar,
4700 // attempt to implicity convert them to the vector type to act like the
4701 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004702 if (getLangOptions().OpenCL && CondTy->isVectorType())
4703 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004704 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004705
Chris Lattner70d67a92008-01-06 22:42:25 +00004706 // If both operands have arithmetic type, do the usual arithmetic conversions
4707 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004708 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4709 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004710 if (LHS.isInvalid() || RHS.isInvalid())
4711 return QualType();
4712 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004713 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004714
Chris Lattner70d67a92008-01-06 22:42:25 +00004715 // If both operands are the same structure or union type, the result is that
4716 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004717 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4718 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004719 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004720 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004721 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004722 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004723 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004724 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004725
Chris Lattner70d67a92008-01-06 22:42:25 +00004726 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004727 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004728 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004729 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004730 }
Richard Trieu26f96072011-09-02 01:51:02 +00004731
Steve Naroffb6d54e52008-01-08 01:11:38 +00004732 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4733 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004734 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4735 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004736
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004737 // All objective-c pointer type analysis is done here.
4738 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4739 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004740 if (LHS.isInvalid() || RHS.isInvalid())
4741 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004742 if (!compositeType.isNull())
4743 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004744
4745
Steve Naroff7154a772009-07-01 14:36:47 +00004746 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004747 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4748 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4749 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004750
Steve Naroff7154a772009-07-01 14:36:47 +00004751 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004752 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4753 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4754 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004755
John McCall404cd162010-11-13 01:35:44 +00004756 // GCC compatibility: soften pointer/integer mismatch. Note that
4757 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004758 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4759 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004760 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004761 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4762 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004763 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004764
Chandler Carruth82214a82011-02-18 23:54:50 +00004765 // Emit a better diagnostic if one of the expressions is a null pointer
4766 // constant and the other is not a pointer type. In this case, the user most
4767 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004768 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004769 return QualType();
4770
Chris Lattner70d67a92008-01-06 22:42:25 +00004771 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004772 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004773 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4774 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004775 return QualType();
4776}
4777
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004778/// FindCompositeObjCPointerType - Helper method to find composite type of
4779/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004780QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004781 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004782 QualType LHSTy = LHS.get()->getType();
4783 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004784
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004785 // Handle things like Class and struct objc_class*. Here we case the result
4786 // to the pseudo-builtin, because that will be implicitly cast back to the
4787 // redefinition type if an attempt is made to access its fields.
4788 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004789 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004790 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004791 return LHSTy;
4792 }
4793 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004794 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004795 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004796 return RHSTy;
4797 }
4798 // And the same for struct objc_object* / id
4799 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004800 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004801 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004802 return LHSTy;
4803 }
4804 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004805 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004806 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004807 return RHSTy;
4808 }
4809 // And the same for struct objc_selector* / SEL
4810 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004811 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004812 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004813 return LHSTy;
4814 }
4815 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004816 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004817 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004818 return RHSTy;
4819 }
4820 // Check constraints for Objective-C object pointers types.
4821 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004822
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004823 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4824 // Two identical object pointer types are always compatible.
4825 return LHSTy;
4826 }
John McCall1d9b3b22011-09-09 05:25:32 +00004827 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4828 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004829 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004830
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004831 // If both operands are interfaces and either operand can be
4832 // assigned to the other, use that type as the composite
4833 // type. This allows
4834 // xxx ? (A*) a : (B*) b
4835 // where B is a subclass of A.
4836 //
4837 // Additionally, as for assignment, if either type is 'id'
4838 // allow silent coercion. Finally, if the types are
4839 // incompatible then make sure to use 'id' as the composite
4840 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004841
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004842 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4843 // It could return the composite type.
4844 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4845 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4846 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4847 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4848 } else if ((LHSTy->isObjCQualifiedIdType() ||
4849 RHSTy->isObjCQualifiedIdType()) &&
4850 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4851 // Need to handle "id<xx>" explicitly.
4852 // GCC allows qualified id and any Objective-C type to devolve to
4853 // id. Currently localizing to here until clear this should be
4854 // part of ObjCQualifiedIdTypesAreCompatible.
4855 compositeType = Context.getObjCIdType();
4856 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4857 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004858 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004859 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4860 ;
4861 else {
4862 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4863 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004864 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004865 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004866 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4867 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004868 return incompatTy;
4869 }
4870 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004871 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4872 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004873 return compositeType;
4874 }
4875 // Check Objective-C object pointer types and 'void *'
4876 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4877 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4878 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4879 QualType destPointee
4880 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4881 QualType destType = Context.getPointerType(destPointee);
4882 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004883 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004884 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004885 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004886 return destType;
4887 }
4888 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4889 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4890 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4891 QualType destPointee
4892 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4893 QualType destType = Context.getPointerType(destPointee);
4894 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004895 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004896 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004897 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004898 return destType;
4899 }
4900 return QualType();
4901}
4902
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004903/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004904/// ParenRange in parentheses.
4905static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004906 const PartialDiagnostic &Note,
4907 SourceRange ParenRange) {
4908 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4909 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4910 EndLoc.isValid()) {
4911 Self.Diag(Loc, Note)
4912 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4913 << FixItHint::CreateInsertion(EndLoc, ")");
4914 } else {
4915 // We can't display the parentheses, so just show the bare note.
4916 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004917 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004918}
4919
4920static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4921 return Opc >= BO_Mul && Opc <= BO_Shr;
4922}
4923
Hans Wennborg2f072b42011-06-09 17:06:51 +00004924/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4925/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00004926/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4927/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00004928static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00004929 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004930 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4931 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004932 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004933 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004934
4935 // Built-in binary operator.
4936 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4937 if (IsArithmeticOp(OP->getOpcode())) {
4938 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00004939 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004940 return true;
4941 }
4942 }
4943
4944 // Overloaded operator.
4945 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4946 if (Call->getNumArgs() != 2)
4947 return false;
4948
4949 // Make sure this is really a binary operator that is safe to pass into
4950 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4951 OverloadedOperatorKind OO = Call->getOperator();
4952 if (OO < OO_Plus || OO > OO_Arrow)
4953 return false;
4954
4955 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4956 if (IsArithmeticOp(OpKind)) {
4957 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00004958 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00004959 return true;
4960 }
4961 }
4962
4963 return false;
4964}
4965
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004966static bool IsLogicOp(BinaryOperatorKind Opc) {
4967 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4968}
4969
Hans Wennborg2f072b42011-06-09 17:06:51 +00004970/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4971/// or is a logical expression such as (x==y) which has int type, but is
4972/// commonly interpreted as boolean.
4973static bool ExprLooksBoolean(Expr *E) {
4974 E = E->IgnoreParenImpCasts();
4975
4976 if (E->getType()->isBooleanType())
4977 return true;
4978 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4979 return IsLogicOp(OP->getOpcode());
4980 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4981 return OP->getOpcode() == UO_LNot;
4982
4983 return false;
4984}
4985
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004986/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4987/// and binary operator are mixed in a way that suggests the programmer assumed
4988/// the conditional operator has higher precedence, for example:
4989/// "int x = a + someBinaryCondition ? 1 : 2".
4990static void DiagnoseConditionalPrecedence(Sema &Self,
4991 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004992 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00004993 Expr *LHSExpr,
4994 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004995 BinaryOperatorKind CondOpcode;
4996 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004997
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004998 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004999 return;
5000 if (!ExprLooksBoolean(CondRHS))
5001 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005002
Hans Wennborg2f072b42011-06-09 17:06:51 +00005003 // The condition is an arithmetic binary expression, with a right-
5004 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005005
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005006 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005007 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005008 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005009
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005010 SuggestParentheses(Self, OpLoc,
5011 Self.PDiag(diag::note_precedence_conditional_silence)
5012 << BinaryOperator::getOpcodeStr(CondOpcode),
5013 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005014
5015 SuggestParentheses(Self, OpLoc,
5016 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005017 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005018}
5019
Steve Narofff69936d2007-09-16 03:34:24 +00005020/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005021/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005022ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005023 SourceLocation ColonLoc,
5024 Expr *CondExpr, Expr *LHSExpr,
5025 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005026 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5027 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005028 OpaqueValueExpr *opaqueValue = 0;
5029 Expr *commonExpr = 0;
5030 if (LHSExpr == 0) {
5031 commonExpr = CondExpr;
5032
5033 // We usually want to apply unary conversions *before* saving, except
5034 // in the special case of a C++ l-value conditional.
5035 if (!(getLangOptions().CPlusPlus
5036 && !commonExpr->isTypeDependent()
5037 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5038 && commonExpr->isGLValue()
5039 && commonExpr->isOrdinaryOrBitFieldObject()
5040 && RHSExpr->isOrdinaryOrBitFieldObject()
5041 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005042 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5043 if (commonRes.isInvalid())
5044 return ExprError();
5045 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005046 }
5047
5048 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5049 commonExpr->getType(),
5050 commonExpr->getValueKind(),
5051 commonExpr->getObjectKind());
5052 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005053 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005054
John McCallf89e55a2010-11-18 06:31:45 +00005055 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005056 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005057 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5058 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005059 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005060 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5061 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005062 return ExprError();
5063
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005064 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5065 RHS.get());
5066
John McCall56ca35d2011-02-17 10:25:35 +00005067 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005068 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5069 LHS.take(), ColonLoc,
5070 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005071
5072 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005073 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005074 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5075 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005076}
5077
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005078/// ConvertObjCSelfToClassRootType - convet type of 'self' in class method
Fariborz Jahanian1d4e8e92011-09-17 19:23:40 +00005079/// to pointer to root of method's class.
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005080static QualType
5081ConvertObjCSelfToClassRootType(Sema &S, Expr *selfExpr) {
5082 QualType SelfType;
Fariborz Jahanian1d4e8e92011-09-17 19:23:40 +00005083 if (const ObjCMethodDecl *MD = S.GetMethodIfSelfExpr(selfExpr))
5084 if (MD->isClassMethod()) {
5085 const ObjCInterfaceDecl *Root = 0;
5086 if (const ObjCInterfaceDecl * IDecl = MD->getClassInterface())
5087 do {
5088 Root = IDecl;
5089 } while ((IDecl = IDecl->getSuperClass()));
5090 if (Root)
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005091 SelfType = S.Context.getObjCObjectPointerType(
5092 S.Context.getObjCInterfaceType(Root));
Fariborz Jahanian1d4e8e92011-09-17 19:23:40 +00005093 }
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005094 return SelfType;
Fariborz Jahanian1d4e8e92011-09-17 19:23:40 +00005095}
5096
John McCalle4be87e2011-01-31 23:13:11 +00005097// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005098// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005099// routine is it effectively iqnores the qualifiers on the top level pointee.
5100// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5101// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005102static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005103checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5104 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5105 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005106
Reid Spencer5f016e22007-07-11 17:01:13 +00005107 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005108 const Type *lhptee, *rhptee;
5109 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005110 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5111 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005112
John McCalle4be87e2011-01-31 23:13:11 +00005113 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005114
5115 // C99 6.5.16.1p1: This following citation is common to constraints
5116 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5117 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005118 Qualifiers lq;
5119
John McCallf85e1932011-06-15 23:02:42 +00005120 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5121 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5122 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5123 // Ignore lifetime for further calculation.
5124 lhq.removeObjCLifetime();
5125 rhq.removeObjCLifetime();
5126 }
5127
John McCall86c05f32011-02-01 00:10:29 +00005128 if (!lhq.compatiblyIncludes(rhq)) {
5129 // Treat address-space mismatches as fatal. TODO: address subspaces
5130 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5131 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5132
John McCallf85e1932011-06-15 23:02:42 +00005133 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005134 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005135 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5136 .compatiblyIncludes(
5137 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005138 && (lhptee->isVoidType() || rhptee->isVoidType()))
5139 ; // keep old
5140
John McCallf85e1932011-06-15 23:02:42 +00005141 // Treat lifetime mismatches as fatal.
5142 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5143 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5144
John McCall86c05f32011-02-01 00:10:29 +00005145 // For GCC compatibility, other qualifier mismatches are treated
5146 // as still compatible in C.
5147 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005149
Mike Stumpeed9cac2009-02-19 03:04:26 +00005150 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5151 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005152 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005153 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005154 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005155 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005156
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005157 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005158 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005159 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005160 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005161
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005162 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005163 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005164 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005165
5166 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005167 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005168 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005169 }
John McCall86c05f32011-02-01 00:10:29 +00005170
Mike Stumpeed9cac2009-02-19 03:04:26 +00005171 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005172 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005173 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5174 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005175 // Check if the pointee types are compatible ignoring the sign.
5176 // We explicitly check for char so that we catch "char" vs
5177 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005178 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005179 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005180 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005181 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005182
Chris Lattner6a2b9262009-10-17 20:33:28 +00005183 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005184 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005185 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005186 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005187
John McCall86c05f32011-02-01 00:10:29 +00005188 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005189 // Types are compatible ignoring the sign. Qualifier incompatibility
5190 // takes priority over sign incompatibility because the sign
5191 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005192 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005193 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005194
John McCalle4be87e2011-01-31 23:13:11 +00005195 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005196 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005197
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005198 // If we are a multi-level pointer, it's possible that our issue is simply
5199 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5200 // the eventual target type is the same and the pointers have the same
5201 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005202 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005203 do {
John McCall86c05f32011-02-01 00:10:29 +00005204 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5205 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005206 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005207
John McCall86c05f32011-02-01 00:10:29 +00005208 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005209 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005210 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005211
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005212 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005213 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005214 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005215 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005216}
5217
John McCalle4be87e2011-01-31 23:13:11 +00005218/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005219/// block pointer types are compatible or whether a block and normal pointer
5220/// are compatible. It is more restrict than comparing two function pointer
5221// types.
John McCalle4be87e2011-01-31 23:13:11 +00005222static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005223checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5224 QualType RHSType) {
5225 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5226 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005227
Steve Naroff1c7d0672008-09-04 15:10:53 +00005228 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005229
Steve Naroff1c7d0672008-09-04 15:10:53 +00005230 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005231 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5232 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005233
John McCalle4be87e2011-01-31 23:13:11 +00005234 // In C++, the types have to match exactly.
5235 if (S.getLangOptions().CPlusPlus)
5236 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005237
John McCalle4be87e2011-01-31 23:13:11 +00005238 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005239
Steve Naroff1c7d0672008-09-04 15:10:53 +00005240 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005241 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5242 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005243
Richard Trieu1da27a12011-09-06 20:21:22 +00005244 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005245 return Sema::IncompatibleBlockPointer;
5246
Steve Naroff1c7d0672008-09-04 15:10:53 +00005247 return ConvTy;
5248}
5249
John McCalle4be87e2011-01-31 23:13:11 +00005250/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005251/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005252static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005253checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5254 QualType RHSType) {
5255 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5256 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005257
Richard Trieu1da27a12011-09-06 20:21:22 +00005258 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005259 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005260 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5261 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005262 return Sema::IncompatiblePointer;
5263 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005264 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005265 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005266 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5267 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005268 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005269 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005270 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005271 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5272 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005273
John McCalle4be87e2011-01-31 23:13:11 +00005274 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5275 return Sema::CompatiblePointerDiscardsQualifiers;
5276
Richard Trieu1da27a12011-09-06 20:21:22 +00005277 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005278 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005279 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005280 return Sema::IncompatibleObjCQualifiedId;
5281 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005282}
5283
John McCall1c23e912010-11-16 02:32:08 +00005284Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005285Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005286 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005287 // Fake up an opaque expression. We don't actually care about what
5288 // cast operations are required, so if CheckAssignmentConstraints
5289 // adds casts to this they'll be wasted, but fortunately that doesn't
5290 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005291 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5292 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005293 CastKind K = CK_Invalid;
5294
Richard Trieu1da27a12011-09-06 20:21:22 +00005295 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005296}
5297
Mike Stumpeed9cac2009-02-19 03:04:26 +00005298/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5299/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005300/// pointers. Here are some objectionable examples that GCC considers warnings:
5301///
5302/// int a, *pint;
5303/// short *pshort;
5304/// struct foo *pfoo;
5305///
5306/// pint = pshort; // warning: assignment from incompatible pointer type
5307/// a = pint; // warning: assignment makes integer from pointer without a cast
5308/// pint = a; // warning: assignment makes pointer from integer without a cast
5309/// pint = pfoo; // warning: assignment from incompatible pointer type
5310///
5311/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005312/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005313///
John McCalldaa8e4e2010-11-15 09:13:47 +00005314/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005315Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005316Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005317 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005318 QualType RHSType = RHS.get()->getType();
5319 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005320
Chris Lattnerfc144e22008-01-04 23:18:45 +00005321 // Get canonical types. We're not formatting these types, just comparing
5322 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005323 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5324 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005325
John McCallb6cfa242011-01-31 22:28:28 +00005326 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005327 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005328 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005329 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005330 }
5331
Douglas Gregor9d293df2008-10-28 00:22:11 +00005332 // If the left-hand side is a reference type, then we are in a
5333 // (rare!) case where we've allowed the use of references in C,
5334 // e.g., as a parameter type in a built-in function. In this case,
5335 // just make sure that the type referenced is compatible with the
5336 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005337 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005338 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005339 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5340 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005341 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005342 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005343 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005344 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005345 }
John McCallb6cfa242011-01-31 22:28:28 +00005346
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005347 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5348 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005349 if (LHSType->isExtVectorType()) {
5350 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005351 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005352 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005353 // CK_VectorSplat does T -> vector T, so first cast to the
5354 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005355 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5356 if (elType != RHSType) {
5357 Kind = PrepareScalarCast(*this, RHS, elType);
5358 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005359 }
5360 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005361 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005363 }
Mike Stump1eb44332009-09-09 15:08:12 +00005364
John McCallb6cfa242011-01-31 22:28:28 +00005365 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005366 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5367 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005368 // Allow assignments of an AltiVec vector type to an equivalent GCC
5369 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005370 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005371 Kind = CK_BitCast;
5372 return Compatible;
5373 }
5374
Douglas Gregor255210e2010-08-06 10:14:59 +00005375 // If we are allowing lax vector conversions, and LHS and RHS are both
5376 // vectors, the total size only needs to be the same. This is a bitcast;
5377 // no bits are changed but the result type is different.
5378 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005379 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005380 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005381 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005382 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005383 }
5384 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005385 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005386
John McCallb6cfa242011-01-31 22:28:28 +00005387 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005388 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5389 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5390 Kind = PrepareScalarCast(*this, RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005391 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005392 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005393
John McCallb6cfa242011-01-31 22:28:28 +00005394 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005395 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005396 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005397 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005398 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005399 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005400 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005401
John McCallb6cfa242011-01-31 22:28:28 +00005402 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005403 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005404 Kind = CK_IntegralToPointer; // FIXME: null?
5405 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005406 }
John McCallb6cfa242011-01-31 22:28:28 +00005407
5408 // C pointers are not compatible with ObjC object pointers,
5409 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005410 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005411 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005412 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005413 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005414 return Compatible;
5415 }
5416
5417 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005418 if (RHSType->isObjCClassType() &&
5419 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005420 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005421 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005422 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005423 }
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005424
John McCallb6cfa242011-01-31 22:28:28 +00005425 Kind = CK_BitCast;
5426 return IncompatiblePointer;
5427 }
5428
5429 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005430 if (RHSType->getAs<BlockPointerType>()) {
5431 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005432 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005433 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005434 }
Steve Naroffb4406862008-09-29 18:10:17 +00005435 }
John McCallb6cfa242011-01-31 22:28:28 +00005436
Steve Naroff1c7d0672008-09-04 15:10:53 +00005437 return Incompatible;
5438 }
5439
John McCallb6cfa242011-01-31 22:28:28 +00005440 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005441 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005442 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005443 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005444 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005445 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005446 }
5447
5448 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005449 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005450 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005451 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005452 }
5453
John McCallb6cfa242011-01-31 22:28:28 +00005454 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005455 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005456 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005457 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005458 }
Steve Naroffb4406862008-09-29 18:10:17 +00005459
John McCallb6cfa242011-01-31 22:28:28 +00005460 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005461 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005462 if (RHSPT->getPointeeType()->isVoidType()) {
5463 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005464 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005465 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005466
Chris Lattnerfc144e22008-01-04 23:18:45 +00005467 return Incompatible;
5468 }
5469
John McCallb6cfa242011-01-31 22:28:28 +00005470 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005471 if (isa<ObjCObjectPointerType>(LHSType)) {
Fariborz Jahanian71ac1e02011-09-19 18:06:07 +00005472 QualType RHSQT = ConvertObjCSelfToClassRootType(*this, RHS.get());
5473 if (!RHSQT.isNull())
5474 RHSType = RHSQT;
John McCallb6cfa242011-01-31 22:28:28 +00005475 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005476 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005477 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005478 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005479 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005480 if (getLangOptions().ObjCAutoRefCount &&
5481 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005482 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005483 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005484 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005485 }
5486
5487 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005488 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005489 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005490 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005491 }
5492
John McCallb6cfa242011-01-31 22:28:28 +00005493 // In general, C pointers are not compatible with ObjC object pointers,
5494 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005495 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005496 Kind = CK_CPointerToObjCPointerCast;
5497
John McCallb6cfa242011-01-31 22:28:28 +00005498 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005499 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005500 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005501 }
5502
5503 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005504 if (LHSType->isObjCClassType() &&
5505 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005506 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005507 return Compatible;
5508 }
5509
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005510 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005511 }
John McCallb6cfa242011-01-31 22:28:28 +00005512
5513 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005514 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005515 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005516 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005517 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005518 }
5519
Steve Naroff14108da2009-07-10 23:34:53 +00005520 return Incompatible;
5521 }
John McCallb6cfa242011-01-31 22:28:28 +00005522
5523 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005524 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005525 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005526 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005527 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005528 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005529 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005530
John McCallb6cfa242011-01-31 22:28:28 +00005531 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005532 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005533 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005534 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005535 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005536
Chris Lattnerfc144e22008-01-04 23:18:45 +00005537 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005538 }
John McCallb6cfa242011-01-31 22:28:28 +00005539
5540 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005541 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005542 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005543 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005544 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005545 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005546 }
Steve Naroff14108da2009-07-10 23:34:53 +00005547
John McCallb6cfa242011-01-31 22:28:28 +00005548 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005549 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005550 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005551 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005552 }
5553
Steve Naroff14108da2009-07-10 23:34:53 +00005554 return Incompatible;
5555 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005556
John McCallb6cfa242011-01-31 22:28:28 +00005557 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005558 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5559 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005560 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005561 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005562 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005563 }
John McCallb6cfa242011-01-31 22:28:28 +00005564
Reid Spencer5f016e22007-07-11 17:01:13 +00005565 return Incompatible;
5566}
5567
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005568/// \brief Constructs a transparent union from an expression that is
5569/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005570static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5571 ExprResult &EResult, QualType UnionType,
5572 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005573 // Build an initializer list that designates the appropriate member
5574 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005575 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005576 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005577 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005578 SourceLocation());
5579 Initializer->setType(UnionType);
5580 Initializer->setInitializedFieldInUnion(Field);
5581
5582 // Build a compound literal constructing a value of the transparent
5583 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005584 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005585 EResult = S.Owned(
5586 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5587 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005588}
5589
5590Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005591Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005592 ExprResult &RHS) {
5593 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005594
Mike Stump1eb44332009-09-09 15:08:12 +00005595 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005596 // transparent_union GCC extension.
5597 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005598 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005599 return Incompatible;
5600
5601 // The field to initialize within the transparent union.
5602 RecordDecl *UD = UT->getDecl();
5603 FieldDecl *InitField = 0;
5604 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005605 for (RecordDecl::field_iterator it = UD->field_begin(),
5606 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005607 it != itend; ++it) {
5608 if (it->getType()->isPointerType()) {
5609 // If the transparent union contains a pointer type, we allow:
5610 // 1) void pointer
5611 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005612 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005613 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005614 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005615 InitField = *it;
5616 break;
5617 }
Mike Stump1eb44332009-09-09 15:08:12 +00005618
Richard Trieuf7720da2011-09-06 20:40:12 +00005619 if (RHS.get()->isNullPointerConstant(Context,
5620 Expr::NPC_ValueDependentIsNull)) {
5621 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5622 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005623 InitField = *it;
5624 break;
5625 }
5626 }
5627
John McCalldaa8e4e2010-11-15 09:13:47 +00005628 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005629 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005630 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005631 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005632 InitField = *it;
5633 break;
5634 }
5635 }
5636
5637 if (!InitField)
5638 return Incompatible;
5639
Richard Trieuf7720da2011-09-06 20:40:12 +00005640 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005641 return Compatible;
5642}
5643
Chris Lattner5cf216b2008-01-04 18:04:52 +00005644Sema::AssignConvertType
Richard Trieuf7720da2011-09-06 20:40:12 +00005645Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005646 if (getLangOptions().CPlusPlus) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005647 if (!LHSType->isRecordType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005648 // C++ 5.17p3: If the left operand is not of class type, the
5649 // expression is implicitly converted (C++ 4) to the
5650 // cv-unqualified type of the left operand.
Richard Trieuf7720da2011-09-06 20:40:12 +00005651 ExprResult Res = PerformImplicitConversion(RHS.get(),
5652 LHSType.getUnqualifiedType(),
John Wiegley429bb272011-04-08 18:41:53 +00005653 AA_Assigning);
5654 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005655 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005656 Sema::AssignConvertType result = Compatible;
5657 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005658 !CheckObjCARCUnavailableWeakConversion(LHSType,
5659 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005660 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005661 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005662 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005663 }
5664
5665 // FIXME: Currently, we fall through and treat C++ classes like C
5666 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005667 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005668
Steve Naroff529a4ad2007-11-27 17:58:44 +00005669 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5670 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005671 if ((LHSType->isPointerType() ||
5672 LHSType->isObjCObjectPointerType() ||
5673 LHSType->isBlockPointerType())
5674 && RHS.get()->isNullPointerConstant(Context,
5675 Expr::NPC_ValueDependentIsNull)) {
5676 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005677 return Compatible;
5678 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005679
Chris Lattner943140e2007-10-16 02:55:40 +00005680 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005681 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005682 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005683 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005684 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005685 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005686 if (!LHSType->isReferenceType()) {
5687 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5688 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005689 return Incompatible;
5690 }
Steve Narofff1120de2007-08-24 22:33:52 +00005691
John McCalldaa8e4e2010-11-15 09:13:47 +00005692 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005693 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005694 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005695
Steve Narofff1120de2007-08-24 22:33:52 +00005696 // C99 6.5.16.1p2: The value of the right operand is converted to the
5697 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005698 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5699 // so that we can use references in built-in functions even in C.
5700 // The getNonReferenceType() call makes sure that the resulting expression
5701 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005702 if (result != Incompatible && RHS.get()->getType() != LHSType)
5703 RHS = ImpCastExprToType(RHS.take(),
5704 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005705 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005706}
5707
Richard Trieuf7720da2011-09-06 20:40:12 +00005708QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5709 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005710 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005711 << LHS.get()->getType() << RHS.get()->getType()
5712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005713 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005714}
5715
Richard Trieu08062aa2011-09-06 21:01:04 +00005716QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005717 SourceLocation Loc, bool IsCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005718 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005719 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005720 QualType LHSType =
5721 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5722 QualType RHSType =
5723 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005724
Nate Begemanbe2341d2008-07-14 18:02:46 +00005725 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005726 if (LHSType == RHSType)
5727 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005728
Douglas Gregor255210e2010-08-06 10:14:59 +00005729 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005730 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5731 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5732 if (LHSType->isExtVectorType()) {
5733 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5734 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005735 }
5736
Richard Trieuccd891a2011-09-09 01:45:06 +00005737 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005738 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5739 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005740 }
5741
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005742 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005743 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005744 // If we are allowing lax vector conversions, and LHS and RHS are both
5745 // vectors, the total size only needs to be the same. This is a
5746 // bitcast; no bits are changed but the result type is different.
5747 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005748 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5749 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005750 }
5751
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005752 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5753 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5754 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005755 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005756 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005757 std::swap(RHS, LHS);
5758 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005759 }
Mike Stump1eb44332009-09-09 15:08:12 +00005760
Nate Begemandde25982009-06-28 19:12:57 +00005761 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005762 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005763 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005764 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5765 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005766 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005767 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005768 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005769 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5770 if (swapped) std::swap(RHS, LHS);
5771 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005772 }
5773 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005774 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5775 RHSType->isRealFloatingType()) {
5776 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005777 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005778 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005779 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005780 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5781 if (swapped) std::swap(RHS, LHS);
5782 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005783 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005784 }
5785 }
Mike Stump1eb44332009-09-09 15:08:12 +00005786
Nate Begemandde25982009-06-28 19:12:57 +00005787 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005788 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005789 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005790 << LHS.get()->getType() << RHS.get()->getType()
5791 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005792 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005793}
5794
Richard Trieu481037f2011-09-16 00:53:10 +00005795// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5796// expression. These are mainly cases where the null pointer is used as an
5797// integer instead of a pointer.
5798static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5799 SourceLocation Loc, bool IsCompare) {
5800 // The canonical way to check for a GNU null is with isNullPointerConstant,
5801 // but we use a bit of a hack here for speed; this is a relatively
5802 // hot path, and isNullPointerConstant is slow.
5803 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5804 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5805
5806 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5807
5808 // Avoid analyzing cases where the result will either be invalid (and
5809 // diagnosed as such) or entirely valid and not something to warn about.
5810 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5811 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5812 return;
5813
5814 // Comparison operations would not make sense with a null pointer no matter
5815 // what the other expression is.
5816 if (!IsCompare) {
5817 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5818 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5819 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5820 return;
5821 }
5822
5823 // The rest of the operations only make sense with a null pointer
5824 // if the other expression is a pointer.
5825 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5826 NonNullType->canDecayToPointerType())
5827 return;
5828
5829 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5830 << LHSNull /* LHS is NULL */ << NonNullType
5831 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5832}
5833
Richard Trieu08062aa2011-09-06 21:01:04 +00005834QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005835 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005836 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00005837 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5838
Richard Trieu08062aa2011-09-06 21:01:04 +00005839 if (LHS.get()->getType()->isVectorType() ||
5840 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005841 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005842
Richard Trieuccd891a2011-09-09 01:45:06 +00005843 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005844 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005845 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005846
Richard Trieu08062aa2011-09-06 21:01:04 +00005847 if (!LHS.get()->getType()->isArithmeticType() ||
5848 !RHS.get()->getType()->isArithmeticType())
5849 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005850
Chris Lattner7ef655a2010-01-12 21:23:57 +00005851 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005852 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005853 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005854 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005855 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5856 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005857
Chris Lattner7ef655a2010-01-12 21:23:57 +00005858 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005859}
5860
Chris Lattner7ef655a2010-01-12 21:23:57 +00005861QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005862 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00005863 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5864
Richard Trieu08062aa2011-09-06 21:01:04 +00005865 if (LHS.get()->getType()->isVectorType() ||
5866 RHS.get()->getType()->isVectorType()) {
5867 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5868 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005869 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005870 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005871 }
Steve Naroff90045e82007-07-13 23:32:42 +00005872
Richard Trieuccd891a2011-09-09 01:45:06 +00005873 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005874 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005875 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005876
Richard Trieu08062aa2011-09-06 21:01:04 +00005877 if (!LHS.get()->getType()->isIntegerType() ||
5878 !RHS.get()->getType()->isIntegerType())
5879 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005880
Chris Lattner7ef655a2010-01-12 21:23:57 +00005881 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005882 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005883 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005884 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5885 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005886
Chris Lattner7ef655a2010-01-12 21:23:57 +00005887 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005888}
5889
Chandler Carruth13b21be2011-06-27 08:02:19 +00005890/// \brief Diagnose invalid arithmetic on two void pointers.
5891static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005892 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005893 S.Diag(Loc, S.getLangOptions().CPlusPlus
5894 ? diag::err_typecheck_pointer_arith_void_type
5895 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005896 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5897 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005898}
5899
5900/// \brief Diagnose invalid arithmetic on a void pointer.
5901static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5902 Expr *Pointer) {
5903 S.Diag(Loc, S.getLangOptions().CPlusPlus
5904 ? diag::err_typecheck_pointer_arith_void_type
5905 : diag::ext_gnu_void_ptr)
5906 << 0 /* one pointer */ << Pointer->getSourceRange();
5907}
5908
5909/// \brief Diagnose invalid arithmetic on two function pointers.
5910static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5911 Expr *LHS, Expr *RHS) {
5912 assert(LHS->getType()->isAnyPointerType());
5913 assert(RHS->getType()->isAnyPointerType());
5914 S.Diag(Loc, S.getLangOptions().CPlusPlus
5915 ? diag::err_typecheck_pointer_arith_function_type
5916 : diag::ext_gnu_ptr_func_arith)
5917 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5918 // We only show the second type if it differs from the first.
5919 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5920 RHS->getType())
5921 << RHS->getType()->getPointeeType()
5922 << LHS->getSourceRange() << RHS->getSourceRange();
5923}
5924
5925/// \brief Diagnose invalid arithmetic on a function pointer.
5926static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5927 Expr *Pointer) {
5928 assert(Pointer->getType()->isAnyPointerType());
5929 S.Diag(Loc, S.getLangOptions().CPlusPlus
5930 ? diag::err_typecheck_pointer_arith_function_type
5931 : diag::ext_gnu_ptr_func_arith)
5932 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5933 << 0 /* one pointer, so only one type */
5934 << Pointer->getSourceRange();
5935}
5936
Richard Trieud9f19342011-09-12 18:08:02 +00005937/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00005938///
5939/// \returns True if pointer has incomplete type
5940static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5941 Expr *Operand) {
5942 if ((Operand->getType()->isPointerType() &&
5943 !Operand->getType()->isDependentType()) ||
5944 Operand->getType()->isObjCObjectPointerType()) {
5945 QualType PointeeTy = Operand->getType()->getPointeeType();
5946 if (S.RequireCompleteType(
5947 Loc, PointeeTy,
5948 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5949 << PointeeTy << Operand->getSourceRange()))
5950 return true;
5951 }
5952 return false;
5953}
5954
Chandler Carruth13b21be2011-06-27 08:02:19 +00005955/// \brief Check the validity of an arithmetic pointer operand.
5956///
5957/// If the operand has pointer type, this code will check for pointer types
5958/// which are invalid in arithmetic operations. These will be diagnosed
5959/// appropriately, including whether or not the use is supported as an
5960/// extension.
5961///
5962/// \returns True when the operand is valid to use (even if as an extension).
5963static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5964 Expr *Operand) {
5965 if (!Operand->getType()->isAnyPointerType()) return true;
5966
5967 QualType PointeeTy = Operand->getType()->getPointeeType();
5968 if (PointeeTy->isVoidType()) {
5969 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5970 return !S.getLangOptions().CPlusPlus;
5971 }
5972 if (PointeeTy->isFunctionType()) {
5973 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5974 return !S.getLangOptions().CPlusPlus;
5975 }
5976
Richard Trieu097ecd22011-09-02 02:15:37 +00005977 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00005978
5979 return true;
5980}
5981
5982/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5983/// operands.
5984///
5985/// This routine will diagnose any invalid arithmetic on pointer operands much
5986/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5987/// for emitting a single diagnostic even for operations where both LHS and RHS
5988/// are (potentially problematic) pointers.
5989///
5990/// \returns True when the operand is valid to use (even if as an extension).
5991static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005992 Expr *LHSExpr, Expr *RHSExpr) {
5993 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5994 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005995 if (!isLHSPointer && !isRHSPointer) return true;
5996
5997 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00005998 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5999 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006000
6001 // Check for arithmetic on pointers to incomplete types.
6002 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6003 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6004 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006005 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6006 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6007 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006008
6009 return !S.getLangOptions().CPlusPlus;
6010 }
6011
6012 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6013 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6014 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006015 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6016 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6017 RHSExpr);
6018 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006019
6020 return !S.getLangOptions().CPlusPlus;
6021 }
6022
Richard Trieudef75842011-09-06 21:13:51 +00006023 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6024 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006025
Chandler Carruth13b21be2011-06-27 08:02:19 +00006026 return true;
6027}
6028
Richard Trieudb44a6b2011-09-01 22:53:23 +00006029/// \brief Check bad cases where we step over interface counts.
6030static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6031 SourceLocation OpLoc,
6032 Expr *Op) {
6033 assert(Op->getType()->isAnyPointerType());
6034 QualType PointeeTy = Op->getType()->getPointeeType();
6035 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6036 return true;
6037
6038 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6039 << PointeeTy << Op->getSourceRange();
6040 return false;
6041}
6042
Richard Trieud9f19342011-09-12 18:08:02 +00006043/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006044static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006045 Expr *LHSExpr, Expr *RHSExpr) {
6046 assert(LHSExpr->getType()->isAnyPointerType());
6047 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006048 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006049 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6050 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006051}
6052
Chris Lattner7ef655a2010-01-12 21:23:57 +00006053QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006054 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006055 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6056
Richard Trieudef75842011-09-06 21:13:51 +00006057 if (LHS.get()->getType()->isVectorType() ||
6058 RHS.get()->getType()->isVectorType()) {
6059 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006060 if (CompLHSTy) *CompLHSTy = compType;
6061 return compType;
6062 }
Steve Naroff49b45262007-07-13 16:58:59 +00006063
Richard Trieudef75842011-09-06 21:13:51 +00006064 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6065 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006066 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006067
Reid Spencer5f016e22007-07-11 17:01:13 +00006068 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006069 if (LHS.get()->getType()->isArithmeticType() &&
6070 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006071 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006072 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006073 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006074
Eli Friedmand72d16e2008-05-18 18:08:51 +00006075 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006076 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006077 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006078 std::swap(PExp, IExp);
6079
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006080 if (!PExp->getType()->isAnyPointerType())
6081 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006082
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006083 if (!IExp->getType()->isIntegerType())
6084 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006085
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006086 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6087 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006088
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006089 // Diagnose bad cases where we step over interface counts.
6090 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6091 return QualType();
6092
6093 // Check array bounds for pointer arithemtic
6094 CheckArrayAccess(PExp, IExp);
6095
6096 if (CompLHSTy) {
6097 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6098 if (LHSTy.isNull()) {
6099 LHSTy = LHS.get()->getType();
6100 if (LHSTy->isPromotableIntegerType())
6101 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006102 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006103 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006104 }
6105
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006106 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006107}
6108
Chris Lattnereca7be62008-04-07 05:30:13 +00006109// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006110QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006111 SourceLocation Loc,
6112 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006113 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6114
Richard Trieudef75842011-09-06 21:13:51 +00006115 if (LHS.get()->getType()->isVectorType() ||
6116 RHS.get()->getType()->isVectorType()) {
6117 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006118 if (CompLHSTy) *CompLHSTy = compType;
6119 return compType;
6120 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006121
Richard Trieudef75842011-09-06 21:13:51 +00006122 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6123 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006124 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006125
Chris Lattner6e4ab612007-12-09 21:53:25 +00006126 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006127
Chris Lattner6e4ab612007-12-09 21:53:25 +00006128 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006129 if (LHS.get()->getType()->isArithmeticType() &&
6130 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006131 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006132 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006133 }
Mike Stump1eb44332009-09-09 15:08:12 +00006134
Chris Lattner6e4ab612007-12-09 21:53:25 +00006135 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006136 if (LHS.get()->getType()->isAnyPointerType()) {
6137 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006138
Chris Lattnerb5f15622009-04-24 23:50:08 +00006139 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006140 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006141 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006142
Chris Lattner6e4ab612007-12-09 21:53:25 +00006143 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006144 if (RHS.get()->getType()->isIntegerType()) {
6145 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006146 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006147
Richard Trieudef75842011-09-06 21:13:51 +00006148 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006149 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6150 OK_Ordinary, IExpr->getExprLoc());
6151 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006152 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006153
Richard Trieudef75842011-09-06 21:13:51 +00006154 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6155 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006156 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006157
Chris Lattner6e4ab612007-12-09 21:53:25 +00006158 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006159 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006160 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006161 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006162
Eli Friedman88d936b2009-05-16 13:54:38 +00006163 if (getLangOptions().CPlusPlus) {
6164 // Pointee types must be the same: C++ [expr.add]
6165 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006166 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006167 }
6168 } else {
6169 // Pointee types must be compatible C99 6.5.6p3
6170 if (!Context.typesAreCompatible(
6171 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6172 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006173 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006174 return QualType();
6175 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006176 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006177
Chandler Carruth13b21be2011-06-27 08:02:19 +00006178 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006179 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006180 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006181
Richard Trieudef75842011-09-06 21:13:51 +00006182 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006183 return Context.getPointerDiffType();
6184 }
6185 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006186
Richard Trieudef75842011-09-06 21:13:51 +00006187 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006188}
6189
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006190static bool isScopedEnumerationType(QualType T) {
6191 if (const EnumType *ET = dyn_cast<EnumType>(T))
6192 return ET->getDecl()->isScoped();
6193 return false;
6194}
6195
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006196static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006197 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006198 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006199 llvm::APSInt Right;
6200 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006201 if (RHS.get()->isValueDependent() ||
6202 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006203 return;
6204
6205 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006206 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006207 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006208 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006209 return;
6210 }
6211 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006212 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006213 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006214 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006215 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006216 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006217 return;
6218 }
6219 if (Opc != BO_Shl)
6220 return;
6221
6222 // When left shifting an ICE which is signed, we can check for overflow which
6223 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6224 // integers have defined behavior modulo one more than the maximum value
6225 // representable in the result type, so never warn for those.
6226 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006227 if (LHS.get()->isValueDependent() ||
6228 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6229 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006230 return;
6231 llvm::APInt ResultBits =
6232 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6233 if (LeftBits.uge(ResultBits))
6234 return;
6235 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6236 Result = Result.shl(Right);
6237
Ted Kremenekfa821382011-06-15 00:54:52 +00006238 // Print the bit representation of the signed integer as an unsigned
6239 // hexadecimal number.
6240 llvm::SmallString<40> HexResult;
6241 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6242
Chandler Carruth21206d52011-02-23 23:34:11 +00006243 // If we are only missing a sign bit, this is less likely to result in actual
6244 // bugs -- if the result is cast back to an unsigned type, it will have the
6245 // expected value. Thus we place this behind a different warning that can be
6246 // turned off separately if needed.
6247 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006248 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006249 << HexResult.str() << LHSType
6250 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006251 return;
6252 }
6253
6254 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006255 << HexResult.str() << Result.getMinSignedBits() << LHSType
6256 << Left.getBitWidth() << LHS.get()->getSourceRange()
6257 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006258}
6259
Chris Lattnereca7be62008-04-07 05:30:13 +00006260// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006261QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006262 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006263 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006264 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6265
Chris Lattnerca5eede2007-12-12 05:47:28 +00006266 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006267 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6268 !RHS.get()->getType()->hasIntegerRepresentation())
6269 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006270
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006271 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6272 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006273 if (isScopedEnumerationType(LHS.get()->getType()) ||
6274 isScopedEnumerationType(RHS.get()->getType())) {
6275 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006276 }
6277
Nate Begeman2207d792009-10-25 02:26:48 +00006278 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006279 if (LHS.get()->getType()->isVectorType() ||
6280 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006281 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006282
Chris Lattnerca5eede2007-12-12 05:47:28 +00006283 // Shifts don't perform usual arithmetic conversions, they just do integer
6284 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006285
John McCall1bc80af2010-12-16 19:28:59 +00006286 // For the LHS, do usual unary conversions, but then reset them away
6287 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006288 ExprResult OldLHS = LHS;
6289 LHS = UsualUnaryConversions(LHS.take());
6290 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006291 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006292 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006293 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006294
6295 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006296 RHS = UsualUnaryConversions(RHS.take());
6297 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006298 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006299
Ryan Flynnd0439682009-08-07 16:20:20 +00006300 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006301 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006302
Chris Lattnerca5eede2007-12-12 05:47:28 +00006303 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006304 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006305}
6306
Chandler Carruth99919472010-07-10 12:30:03 +00006307static bool IsWithinTemplateSpecialization(Decl *D) {
6308 if (DeclContext *DC = D->getDeclContext()) {
6309 if (isa<ClassTemplateSpecializationDecl>(DC))
6310 return true;
6311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6312 return FD->isFunctionTemplateSpecialization();
6313 }
6314 return false;
6315}
6316
Richard Trieue648ac32011-09-02 03:48:46 +00006317/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006318static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6319 ExprResult &RHS) {
6320 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6321 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006322
6323 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6324 if (!LHSEnumType)
6325 return;
6326 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6327 if (!RHSEnumType)
6328 return;
6329
6330 // Ignore anonymous enums.
6331 if (!LHSEnumType->getDecl()->getIdentifier())
6332 return;
6333 if (!RHSEnumType->getDecl()->getIdentifier())
6334 return;
6335
6336 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6337 return;
6338
6339 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6340 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006341 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006342}
6343
Richard Trieu7be1be02011-09-02 02:55:45 +00006344/// \brief Diagnose bad pointer comparisons.
6345static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006346 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006347 bool IsError) {
6348 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006349 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006350 << LHS.get()->getType() << RHS.get()->getType()
6351 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006352}
6353
6354/// \brief Returns false if the pointers are converted to a composite type,
6355/// true otherwise.
6356static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006357 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006358 // C++ [expr.rel]p2:
6359 // [...] Pointer conversions (4.10) and qualification
6360 // conversions (4.4) are performed on pointer operands (or on
6361 // a pointer operand and a null pointer constant) to bring
6362 // them to their composite pointer type. [...]
6363 //
6364 // C++ [expr.eq]p1 uses the same notion for (in)equality
6365 // comparisons of pointers.
6366
6367 // C++ [expr.eq]p2:
6368 // In addition, pointers to members can be compared, or a pointer to
6369 // member and a null pointer constant. Pointer to member conversions
6370 // (4.11) and qualification conversions (4.4) are performed to bring
6371 // them to a common type. If one operand is a null pointer constant,
6372 // the common type is the type of the other operand. Otherwise, the
6373 // common type is a pointer to member type similar (4.4) to the type
6374 // of one of the operands, with a cv-qualification signature (4.4)
6375 // that is the union of the cv-qualification signatures of the operand
6376 // types.
6377
Richard Trieuba261492011-09-06 21:27:33 +00006378 QualType LHSType = LHS.get()->getType();
6379 QualType RHSType = RHS.get()->getType();
6380 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6381 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006382
6383 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006384 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006385 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006386 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006387 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006388 return true;
6389 }
6390
6391 if (NonStandardCompositeType)
6392 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006393 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6394 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006395
Richard Trieuba261492011-09-06 21:27:33 +00006396 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6397 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006398 return false;
6399}
6400
6401static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006402 ExprResult &LHS,
6403 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006404 bool IsError) {
6405 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6406 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006407 << LHS.get()->getType() << RHS.get()->getType()
6408 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006409}
6410
Douglas Gregor0c6db942009-05-04 06:07:12 +00006411// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006412QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006413 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006414 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006415 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6416
John McCall2de56d12010-08-25 11:45:40 +00006417 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006418
Chris Lattner02dd4b12009-12-05 05:40:13 +00006419 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006420 if (LHS.get()->getType()->isVectorType() ||
6421 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006422 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006423
Richard Trieuf1775fb2011-09-06 21:43:51 +00006424 QualType LHSType = LHS.get()->getType();
6425 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006426
Richard Trieuf1775fb2011-09-06 21:43:51 +00006427 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6428 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006429
Richard Trieuf1775fb2011-09-06 21:43:51 +00006430 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006431
Richard Trieuf1775fb2011-09-06 21:43:51 +00006432 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006433 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006434 !LHS.get()->getLocStart().isMacroID() &&
6435 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006436 // For non-floating point types, check for self-comparisons of the form
6437 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6438 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006439 //
6440 // NOTE: Don't warn about comparison expressions resulting from macro
6441 // expansion. Also don't warn about comparisons which are only self
6442 // comparisons within a template specialization. The warnings should catch
6443 // obvious cases in the definition of the template anyways. The idea is to
6444 // warn when the typed comparison operator will always evaluate to the same
6445 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006446 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006447 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006448 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006449 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006450 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006451 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006452 << (Opc == BO_EQ
6453 || Opc == BO_LE
6454 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006455 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006456 !DRL->getDecl()->getType()->isReferenceType() &&
6457 !DRR->getDecl()->getType()->isReferenceType()) {
6458 // what is it always going to eval to?
6459 char always_evals_to;
6460 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006461 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006462 always_evals_to = 0; // false
6463 break;
John McCall2de56d12010-08-25 11:45:40 +00006464 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006465 always_evals_to = 1; // true
6466 break;
6467 default:
6468 // best we can say is 'a constant'
6469 always_evals_to = 2; // e.g. array1 <= array2
6470 break;
6471 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006472 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006473 << 1 // array
6474 << always_evals_to);
6475 }
6476 }
Chandler Carruth99919472010-07-10 12:30:03 +00006477 }
Mike Stump1eb44332009-09-09 15:08:12 +00006478
Chris Lattner55660a72009-03-08 19:39:53 +00006479 if (isa<CastExpr>(LHSStripped))
6480 LHSStripped = LHSStripped->IgnoreParenCasts();
6481 if (isa<CastExpr>(RHSStripped))
6482 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006483
Chris Lattner55660a72009-03-08 19:39:53 +00006484 // Warn about comparisons against a string constant (unless the other
6485 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006486 Expr *literalString = 0;
6487 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006488 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006489 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006490 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006491 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006492 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006493 } else if ((isa<StringLiteral>(RHSStripped) ||
6494 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006495 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006496 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006497 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006498 literalStringStripped = RHSStripped;
6499 }
6500
6501 if (literalString) {
6502 std::string resultComparison;
6503 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006504 case BO_LT: resultComparison = ") < 0"; break;
6505 case BO_GT: resultComparison = ") > 0"; break;
6506 case BO_LE: resultComparison = ") <= 0"; break;
6507 case BO_GE: resultComparison = ") >= 0"; break;
6508 case BO_EQ: resultComparison = ") == 0"; break;
6509 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006510 default: assert(false && "Invalid comparison operator");
6511 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006512
Ted Kremenek351ba912011-02-23 01:52:04 +00006513 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006514 PDiag(diag::warn_stringcompare)
6515 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006516 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006517 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006518 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006519
Douglas Gregord64fdd02010-06-08 19:50:34 +00006520 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006521 if (LHS.get()->getType()->isArithmeticType() &&
6522 RHS.get()->getType()->isArithmeticType()) {
6523 UsualArithmeticConversions(LHS, RHS);
6524 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006525 return QualType();
6526 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006527 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006528 LHS = UsualUnaryConversions(LHS.take());
6529 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006530 return QualType();
6531
Richard Trieuf1775fb2011-09-06 21:43:51 +00006532 RHS = UsualUnaryConversions(RHS.take());
6533 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006534 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006535 }
6536
Richard Trieuf1775fb2011-09-06 21:43:51 +00006537 LHSType = LHS.get()->getType();
6538 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006539
Douglas Gregor447b69e2008-11-19 03:25:36 +00006540 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006541 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006542
Richard Trieuccd891a2011-09-09 01:45:06 +00006543 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006544 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006545 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006546 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006547 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006548 if (LHSType->hasFloatingRepresentation())
6549 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006550
Richard Trieuf1775fb2011-09-06 21:43:51 +00006551 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006552 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006553 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006554
Richard Trieuf1775fb2011-09-06 21:43:51 +00006555 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006556 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006557 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006558 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006559
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006560 // All of the following pointer-related warnings are GCC extensions, except
6561 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006562 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006563 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006564 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006565 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006566 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006567
Douglas Gregor0c6db942009-05-04 06:07:12 +00006568 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006569 if (LCanPointeeTy == RCanPointeeTy)
6570 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006571 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006572 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6573 // Valid unless comparison between non-null pointer and function pointer
6574 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006575 // In a SFINAE context, we treat this as a hard error to maintain
6576 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006577 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6578 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006579 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006580 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006581
6582 if (isSFINAEContext())
6583 return QualType();
6584
Richard Trieuf1775fb2011-09-06 21:43:51 +00006585 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006586 return ResultTy;
6587 }
6588 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006589
Richard Trieuf1775fb2011-09-06 21:43:51 +00006590 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006591 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006592 else
6593 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006594 }
Eli Friedman3075e762009-08-23 00:27:47 +00006595 // C99 6.5.9p2 and C99 6.5.8p2
6596 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6597 RCanPointeeTy.getUnqualifiedType())) {
6598 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006599 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006600 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006601 << LHSType << RHSType << LHS.get()->getSourceRange()
6602 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006603 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006604 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006605 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6606 // Valid unless comparison between non-null pointer and function pointer
6607 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006608 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006609 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006610 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006611 } else {
6612 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006613 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006614 }
John McCall34d6f932011-03-11 04:25:25 +00006615 if (LCanPointeeTy != RCanPointeeTy) {
6616 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006617 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006618 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006619 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006620 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006621 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006622 }
Mike Stump1eb44332009-09-09 15:08:12 +00006623
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006624 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006625 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006626 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006627 return ResultTy;
6628
Mike Stump1eb44332009-09-09 15:08:12 +00006629 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006630 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006631 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006632 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006633 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006634 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6635 RHS = ImpCastExprToType(RHS.take(), LHSType,
6636 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006637 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006638 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006639 return ResultTy;
6640 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006641 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006642 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006643 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006644 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6645 LHS = ImpCastExprToType(LHS.take(), RHSType,
6646 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006647 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006648 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006649 return ResultTy;
6650 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006651
6652 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006653 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006654 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6655 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006656 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006657 else
6658 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006659 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006660
6661 // Handle scoped enumeration types specifically, since they don't promote
6662 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006663 if (LHS.get()->getType()->isEnumeralType() &&
6664 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6665 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006666 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006667 }
Mike Stump1eb44332009-09-09 15:08:12 +00006668
Steve Naroff1c7d0672008-09-04 15:10:53 +00006669 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006670 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006671 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006672 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6673 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006674
Steve Naroff1c7d0672008-09-04 15:10:53 +00006675 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006676 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006677 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006678 << LHSType << RHSType << LHS.get()->getSourceRange()
6679 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006680 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006681 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006682 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006683 }
John Wiegley429bb272011-04-08 18:41:53 +00006684
Steve Naroff59f53942008-09-28 01:11:11 +00006685 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006686 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006687 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6688 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006689 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006690 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006691 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006692 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006693 ->getPointeeType()->isVoidType())))
6694 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006695 << LHSType << RHSType << LHS.get()->getSourceRange()
6696 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006697 }
John McCall34d6f932011-03-11 04:25:25 +00006698 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006699 LHS = ImpCastExprToType(LHS.take(), RHSType,
6700 RHSType->isPointerType() ? CK_BitCast
6701 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006702 else
John McCall1d9b3b22011-09-09 05:25:32 +00006703 RHS = ImpCastExprToType(RHS.take(), LHSType,
6704 LHSType->isPointerType() ? CK_BitCast
6705 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006706 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006707 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006708
Richard Trieuf1775fb2011-09-06 21:43:51 +00006709 if (LHSType->isObjCObjectPointerType() ||
6710 RHSType->isObjCObjectPointerType()) {
6711 const PointerType *LPT = LHSType->getAs<PointerType>();
6712 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006713 if (LPT || RPT) {
6714 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6715 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006716
Steve Naroffa8069f12008-11-17 19:49:16 +00006717 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006718 !Context.typesAreCompatible(LHSType, RHSType)) {
6719 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006720 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006721 }
John McCall34d6f932011-03-11 04:25:25 +00006722 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006723 LHS = ImpCastExprToType(LHS.take(), RHSType,
6724 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006725 else
John McCall1d9b3b22011-09-09 05:25:32 +00006726 RHS = ImpCastExprToType(RHS.take(), LHSType,
6727 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006728 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006729 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006730 if (LHSType->isObjCObjectPointerType() &&
6731 RHSType->isObjCObjectPointerType()) {
6732 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6733 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006734 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006735 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006736 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006737 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006738 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006739 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006740 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006741 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006742 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6743 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006744 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006745 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006746 if ((LHSIsNull && LHSType->isIntegerType()) ||
6747 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006748 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006749 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006750 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006751 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006752 else if (getLangOptions().CPlusPlus) {
6753 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6754 isError = true;
6755 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006756 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006757
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006758 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006759 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006760 << LHSType << RHSType << LHS.get()->getSourceRange()
6761 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006762 if (isError)
6763 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006764 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006765
Richard Trieuf1775fb2011-09-06 21:43:51 +00006766 if (LHSType->isIntegerType())
6767 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006768 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006769 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006770 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006771 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006772 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006773 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006774
Steve Naroff39218df2008-09-04 16:56:14 +00006775 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006776 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006777 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6778 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006779 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006780 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006781 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006782 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6783 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006784 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006785 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006786
Richard Trieuf1775fb2011-09-06 21:43:51 +00006787 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006788}
6789
Nate Begemanbe2341d2008-07-14 18:02:46 +00006790/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006791/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006792/// like a scalar comparison, a vector comparison produces a vector of integer
6793/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006794QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006795 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006796 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006797 // Check to make sure we're operating on vectors of the same type and width,
6798 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006799 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006800 if (vType.isNull())
6801 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006802
Richard Trieu9f60dee2011-09-07 01:19:57 +00006803 QualType LHSType = LHS.get()->getType();
6804 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006805
Anton Yartsev7870b132011-03-27 15:36:07 +00006806 // If AltiVec, the comparison results in a numeric type, i.e.
6807 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006808 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006809 return Context.getLogicalOperationType();
6810
Nate Begemanbe2341d2008-07-14 18:02:46 +00006811 // For non-floating point types, check for self-comparisons of the form
6812 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6813 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006814 if (!LHSType->hasFloatingRepresentation()) {
6815 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6816 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006817 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006818 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006819 PDiag(diag::warn_comparison_always)
6820 << 0 // self-
6821 << 2 // "a constant"
6822 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006823 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006824
Nate Begemanbe2341d2008-07-14 18:02:46 +00006825 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006826 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006827 assert (RHSType->hasFloatingRepresentation());
6828 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006829 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006830
Nate Begemanbe2341d2008-07-14 18:02:46 +00006831 // Return the type for the comparison, which is the same as vector type for
6832 // integer vectors, or an integer type of identical size and number of
6833 // elements for floating point vectors.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006834 if (LHSType->hasIntegerRepresentation())
6835 return LHSType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006836
Richard Trieu9f60dee2011-09-07 01:19:57 +00006837 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006838 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006839 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006840 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006841 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006842 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6843
Mike Stumpeed9cac2009-02-19 03:04:26 +00006844 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006845 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006846 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6847}
6848
Reid Spencer5f016e22007-07-11 17:01:13 +00006849inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006850 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006851 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6852
Richard Trieu9f60dee2011-09-07 01:19:57 +00006853 if (LHS.get()->getType()->isVectorType() ||
6854 RHS.get()->getType()->isVectorType()) {
6855 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6856 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006857 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006858
Richard Trieu9f60dee2011-09-07 01:19:57 +00006859 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006860 }
Steve Naroff90045e82007-07-13 23:32:42 +00006861
Richard Trieu9f60dee2011-09-07 01:19:57 +00006862 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6863 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006864 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006865 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006866 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006867 LHS = LHSResult.take();
6868 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006869
Richard Trieu9f60dee2011-09-07 01:19:57 +00006870 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6871 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006872 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006873 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006874}
6875
6876inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006877 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006878
6879 // Diagnose cases where the user write a logical and/or but probably meant a
6880 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6881 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006882 if (LHS.get()->getType()->isIntegerType() &&
6883 !LHS.get()->getType()->isBooleanType() &&
6884 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006885 // Don't warn in macros or template instantiations.
6886 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006887 // If the RHS can be constant folded, and if it constant folds to something
6888 // that isn't 0 or 1 (which indicate a potential logical operation that
6889 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006890 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006891 Expr::EvalResult Result;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006892 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6893 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruth0683a142011-05-31 05:41:42 +00006894 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6895 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006896 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006897 << (Opc == BO_LAnd ? "&&" : "||");
6898 // Suggest replacing the logical operator with the bitwise version
6899 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6900 << (Opc == BO_LAnd ? "&" : "|")
6901 << FixItHint::CreateReplacement(SourceRange(
6902 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6903 getLangOptions())),
6904 Opc == BO_LAnd ? "&" : "|");
6905 if (Opc == BO_LAnd)
6906 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6907 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6908 << FixItHint::CreateRemoval(
6909 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006910 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006911 0, getSourceManager(),
6912 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006913 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006914 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006915 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006916
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006917 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006918 LHS = UsualUnaryConversions(LHS.take());
6919 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006920 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006921
Richard Trieu9f60dee2011-09-07 01:19:57 +00006922 RHS = UsualUnaryConversions(RHS.take());
6923 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006924 return QualType();
6925
Richard Trieu9f60dee2011-09-07 01:19:57 +00006926 if (!LHS.get()->getType()->isScalarType() ||
6927 !RHS.get()->getType()->isScalarType())
6928 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006929
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006930 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006931 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006932
John McCall75f7c0f2010-06-04 00:29:51 +00006933 // The following is safe because we only use this method for
6934 // non-overloadable operands.
6935
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006936 // C++ [expr.log.and]p1
6937 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006938 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006939 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6940 if (LHSRes.isInvalid())
6941 return InvalidOperands(Loc, LHS, RHS);
6942 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00006943
Richard Trieu9f60dee2011-09-07 01:19:57 +00006944 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6945 if (RHSRes.isInvalid())
6946 return InvalidOperands(Loc, LHS, RHS);
6947 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006948
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006949 // C++ [expr.log.and]p2
6950 // C++ [expr.log.or]p2
6951 // The result is a bool.
6952 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006953}
6954
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006955/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6956/// is a read-only property; return true if so. A readonly property expression
6957/// depends on various declarations and thus must be treated specially.
6958///
Mike Stump1eb44332009-09-09 15:08:12 +00006959static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006960 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6961 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006962 if (PropExpr->isImplicitProperty()) return false;
6963
6964 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6965 QualType BaseType = PropExpr->isSuperReceiver() ?
6966 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006967 PropExpr->getBase()->getType();
6968
John McCall12f78a62010-12-02 01:19:52 +00006969 if (const ObjCObjectPointerType *OPT =
6970 BaseType->getAsObjCInterfacePointerType())
6971 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6972 if (S.isPropertyReadonly(PDecl, IFace))
6973 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006974 }
6975 return false;
6976}
6977
Fariborz Jahanian14086762011-03-28 23:47:18 +00006978static bool IsConstProperty(Expr *E, Sema &S) {
6979 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6980 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6981 if (PropExpr->isImplicitProperty()) return false;
6982
6983 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6984 QualType T = PDecl->getType();
6985 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006986 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006987 CanQualType CT = S.Context.getCanonicalType(T);
6988 return CT.isConstQualified();
6989 }
6990 return false;
6991}
6992
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006993static bool IsReadonlyMessage(Expr *E, Sema &S) {
6994 if (E->getStmtClass() != Expr::MemberExprClass)
6995 return false;
6996 const MemberExpr *ME = cast<MemberExpr>(E);
6997 NamedDecl *Member = ME->getMemberDecl();
6998 if (isa<FieldDecl>(Member)) {
6999 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7000 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7001 return false;
7002 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7003 }
7004 return false;
7005}
7006
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007007/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7008/// emit an error and return true. If so, return false.
7009static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007010 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007011 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007012 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007013 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7014 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007015 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7016 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007017 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7018 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007019 if (IsLV == Expr::MLV_Valid)
7020 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007021
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007022 unsigned Diag = 0;
7023 bool NeedType = false;
7024 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007025 case Expr::MLV_ConstQualified:
7026 Diag = diag::err_typecheck_assign_const;
7027
John McCall7acddac2011-06-17 06:42:21 +00007028 // In ARC, use some specialized diagnostics for occasions where we
7029 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00007030 if (S.getLangOptions().ObjCAutoRefCount) {
7031 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7032 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7033 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7034
John McCall7acddac2011-06-17 06:42:21 +00007035 // Use the normal diagnostic if it's pseudo-__strong but the
7036 // user actually wrote 'const'.
7037 if (var->isARCPseudoStrong() &&
7038 (!var->getTypeSourceInfo() ||
7039 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7040 // There are two pseudo-strong cases:
7041 // - self
John McCallf85e1932011-06-15 23:02:42 +00007042 ObjCMethodDecl *method = S.getCurMethodDecl();
7043 if (method && var == method->getSelfDecl())
7044 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007045
7046 // - fast enumeration variables
7047 else
John McCallf85e1932011-06-15 23:02:42 +00007048 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007049
John McCallf85e1932011-06-15 23:02:42 +00007050 SourceRange Assign;
7051 if (Loc != OrigLoc)
7052 Assign = SourceRange(OrigLoc, OrigLoc);
7053 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7054 // We need to preserve the AST regardless, so migration tool
7055 // can do its job.
7056 return false;
7057 }
7058 }
7059 }
7060
7061 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007062 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007063 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7064 NeedType = true;
7065 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007066 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007067 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7068 NeedType = true;
7069 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007070 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007071 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7072 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007073 case Expr::MLV_Valid:
7074 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007075 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007076 case Expr::MLV_MemberFunction:
7077 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007078 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7079 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007080 case Expr::MLV_IncompleteType:
7081 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007082 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007083 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007084 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007085 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007086 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7087 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007088 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007089 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7090 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007091 case Expr::MLV_ReadonlyProperty:
7092 Diag = diag::error_readonly_property_assignment;
7093 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007094 case Expr::MLV_NoSetterProperty:
7095 Diag = diag::error_nosetter_property_assignment;
7096 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007097 case Expr::MLV_InvalidMessageExpression:
7098 Diag = diag::error_readonly_message_assignment;
7099 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007100 case Expr::MLV_SubObjCPropertySetting:
7101 Diag = diag::error_no_subobject_property_setting;
7102 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007103 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007104
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007105 SourceRange Assign;
7106 if (Loc != OrigLoc)
7107 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007108 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007109 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007110 else
Mike Stump1eb44332009-09-09 15:08:12 +00007111 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007112 return true;
7113}
7114
7115
7116
7117// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007118QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007119 SourceLocation Loc,
7120 QualType CompoundType) {
7121 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007122 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007123 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007124
Richard Trieu268942b2011-09-07 01:33:52 +00007125 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007126 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7127 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007128 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007129 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007130 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007131 // Simple assignment "x = y".
Richard Trieu268942b2011-09-07 01:33:52 +00007132 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7133 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley429bb272011-04-08 18:41:53 +00007134 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7135 if (LHSResult.isInvalid())
7136 return QualType();
Richard Trieu268942b2011-09-07 01:33:52 +00007137 LHSExpr = LHSResult.take();
John Wiegley429bb272011-04-08 18:41:53 +00007138 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007139 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007140 if (RHS.isInvalid())
7141 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007142 // Special case of NSObject attributes on c-style pointer types.
7143 if (ConvTy == IncompatiblePointer &&
7144 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007145 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007146 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007147 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007148 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007149
John McCallf89e55a2010-11-18 06:31:45 +00007150 if (ConvTy == Compatible &&
7151 getLangOptions().ObjCNonFragileABI &&
7152 LHSType->isObjCObjectType())
7153 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7154 << LHSType;
7155
Chris Lattner2c156472008-08-21 18:04:13 +00007156 // If the RHS is a unary plus or minus, check to see if they = and + are
7157 // right next to each other. If so, the user may have typo'd "x =+ 4"
7158 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007159 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007160 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7161 RHSCheck = ICE->getSubExpr();
7162 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007163 if ((UO->getOpcode() == UO_Plus ||
7164 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007165 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007166 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007167 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007168 // And there is a space or other character before the subexpr of the
7169 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007170 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007171 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007172 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007173 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007174 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007175 }
Chris Lattner2c156472008-08-21 18:04:13 +00007176 }
John McCallf85e1932011-06-15 23:02:42 +00007177
7178 if (ConvTy == Compatible) {
7179 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007180 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007181 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007182 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007183 }
Chris Lattner2c156472008-08-21 18:04:13 +00007184 } else {
7185 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007186 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007187 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007188
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007189 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007190 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007191 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007192
Richard Trieu268942b2011-09-07 01:33:52 +00007193 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007194
Reid Spencer5f016e22007-07-11 17:01:13 +00007195 // C99 6.5.16p3: The type of an assignment expression is the type of the
7196 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007197 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007198 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7199 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007200 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007201 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007202 return (getLangOptions().CPlusPlus
7203 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007204}
7205
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007206// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007207static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007208 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007209 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007210
John McCallfb8721c2011-04-10 19:13:55 +00007211 LHS = S.CheckPlaceholderExpr(LHS.take());
7212 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007213 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007214 return QualType();
7215
John McCallcf2e5062010-10-12 07:14:40 +00007216 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7217 // operands, but not unary promotions.
7218 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007219
John McCallf6a16482010-12-04 03:47:34 +00007220 // So we treat the LHS as a ignored value, and in C++ we allow the
7221 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007222 LHS = S.IgnoredValueConversions(LHS.take());
7223 if (LHS.isInvalid())
7224 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007225
7226 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007227 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7228 if (RHS.isInvalid())
7229 return QualType();
7230 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007231 S.RequireCompleteType(Loc, RHS.get()->getType(),
7232 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007233 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007234
John Wiegley429bb272011-04-08 18:41:53 +00007235 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007236}
7237
Steve Naroff49b45262007-07-13 16:58:59 +00007238/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7239/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007240static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7241 ExprValueKind &VK,
7242 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007243 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007244 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007245 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007246
Chris Lattner3528d352008-11-21 07:05:48 +00007247 QualType ResType = Op->getType();
7248 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007249
John McCall09431682010-11-18 19:01:18 +00007250 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007251 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007252 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007253 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007254 return QualType();
7255 }
7256 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007257 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007258 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007259 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007260 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007261 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007262 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007263 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007264
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007265 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007266 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007267 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007268 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007269 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007270 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007271 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007272 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007273 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007274 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007275 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007276 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007277 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7278 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007279 } else {
John McCall09431682010-11-18 19:01:18 +00007280 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007281 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007282 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007283 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007284 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007285 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007286 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007287 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007288 // In C++, a prefix increment is the same type as the operand. Otherwise
7289 // (in C or with postfix), the increment is the unqualified type of the
7290 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007291 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007292 VK = VK_LValue;
7293 return ResType;
7294 } else {
7295 VK = VK_RValue;
7296 return ResType.getUnqualifiedType();
7297 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007298}
7299
John Wiegley429bb272011-04-08 18:41:53 +00007300ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007301 assert(E->getValueKind() == VK_LValue &&
7302 E->getObjectKind() == OK_ObjCProperty);
7303 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7304
Douglas Gregor926df6c2011-06-11 01:09:30 +00007305 QualType T = E->getType();
7306 QualType ReceiverType;
7307 if (PRE->isObjectReceiver())
7308 ReceiverType = PRE->getBase()->getType();
7309 else if (PRE->isSuperReceiver())
7310 ReceiverType = PRE->getSuperReceiverType();
7311 else
7312 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7313
John McCallf6a16482010-12-04 03:47:34 +00007314 ExprValueKind VK = VK_RValue;
7315 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007316 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007317 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007318 T = getMessageSendResultType(ReceiverType, GetterMethod,
7319 PRE->isClassReceiver(),
7320 PRE->isSuperReceiver());
7321 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007322 }
7323 else {
7324 Diag(PRE->getLocation(), diag::err_getter_not_found)
7325 << PRE->getBase()->getType();
7326 }
John McCallf6a16482010-12-04 03:47:34 +00007327 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007328
7329 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007330 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007331
7332 ExprResult Result = MaybeBindToTemporary(E);
7333 if (!Result.isInvalid())
7334 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007335
7336 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007337}
7338
Richard Trieu67e29332011-08-02 04:35:43 +00007339void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7340 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007341 assert(LHS.get()->getValueKind() == VK_LValue &&
7342 LHS.get()->getObjectKind() == OK_ObjCProperty);
7343 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007344
John McCallf85e1932011-06-15 23:02:42 +00007345 bool Consumed = false;
7346
John Wiegley429bb272011-04-08 18:41:53 +00007347 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007348 // If using property-dot syntax notation for assignment, and there is a
7349 // setter, RHS expression is being passed to the setter argument. So,
7350 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007351 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007352 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7353 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007354 Consumed = (getLangOptions().ObjCAutoRefCount &&
7355 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007356
7357 // Otherwise, if the getter returns an l-value, just call that.
7358 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007359 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007360 ExprValueKind VK = Expr::getValueKindForType(Result);
7361 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007362 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7363 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007364 return;
John McCall12f78a62010-12-02 01:19:52 +00007365 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007366 }
John McCallf85e1932011-06-15 23:02:42 +00007367 } else if (getLangOptions().ObjCAutoRefCount) {
7368 const ObjCMethodDecl *setter
7369 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7370 if (setter) {
7371 ObjCMethodDecl::param_iterator P = setter->param_begin();
7372 LHSTy = (*P)->getType();
7373 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7374 }
John McCallf6a16482010-12-04 03:47:34 +00007375 }
7376
John McCallf85e1932011-06-15 23:02:42 +00007377 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7378 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007379 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007380 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007381 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007382 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007383 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007384 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7385 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7386 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007387 }
7388}
7389
7390
Anders Carlsson369dee42008-02-01 07:15:58 +00007391/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007392/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007393/// where the declaration is needed for type checking. We only need to
7394/// handle cases when the expression references a function designator
7395/// or is an lvalue. Here are some examples:
7396/// - &(x) => x
7397/// - &*****f => f for f a function designator.
7398/// - &s.xx => s
7399/// - &s.zz[1].yy -> s, if zz is an array
7400/// - *(x + 1) -> x, if x is an array
7401/// - &"123"[2] -> 0
7402/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007403static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007404 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007405 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007406 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007407 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007408 // If this is an arrow operator, the address is an offset from
7409 // the base's value, so the object the base refers to is
7410 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007411 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007412 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007413 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007414 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007415 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007416 // FIXME: This code shouldn't be necessary! We should catch the implicit
7417 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007418 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7419 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7420 if (ICE->getSubExpr()->getType()->isArrayType())
7421 return getPrimaryDecl(ICE->getSubExpr());
7422 }
7423 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007424 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007425 case Stmt::UnaryOperatorClass: {
7426 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007427
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007428 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007429 case UO_Real:
7430 case UO_Imag:
7431 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007432 return getPrimaryDecl(UO->getSubExpr());
7433 default:
7434 return 0;
7435 }
7436 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007437 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007438 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007439 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007440 // If the result of an implicit cast is an l-value, we care about
7441 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007442 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007443 default:
7444 return 0;
7445 }
7446}
7447
Richard Trieu5520f232011-09-07 21:46:33 +00007448namespace {
7449 enum {
7450 AO_Bit_Field = 0,
7451 AO_Vector_Element = 1,
7452 AO_Property_Expansion = 2,
7453 AO_Register_Variable = 3,
7454 AO_No_Error = 4
7455 };
7456}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007457/// \brief Diagnose invalid operand for address of operations.
7458///
7459/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007460static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7461 Expr *E, unsigned Type) {
7462 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7463}
7464
Reid Spencer5f016e22007-07-11 17:01:13 +00007465/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007466/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007467/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007468/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007469/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007470/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007471/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007472static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7473 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007474 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007475 return S.Context.DependentTy;
7476 if (OrigOp->getType() == S.Context.OverloadTy)
7477 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007478 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7479 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007480 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7481 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7482 << OrigOp->getSourceRange();
7483 return QualType();
7484 }
John McCall9c72c602010-08-27 09:08:28 +00007485
John McCall755d8492011-04-12 00:42:48 +00007486 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007487
John McCall9c72c602010-08-27 09:08:28 +00007488 // Make sure to ignore parentheses in subsequent checks
7489 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007490
John McCall09431682010-11-18 19:01:18 +00007491 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007492 // Implement C99-only parts of addressof rules.
7493 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007494 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007495 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7496 // (assuming the deref expression is valid).
7497 return uOp->getSubExpr()->getType();
7498 }
7499 // Technically, there should be a check for array subscript
7500 // expressions here, but the result of one is always an lvalue anyway.
7501 }
John McCall5808ce42011-02-03 08:15:49 +00007502 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007503 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007504 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007505
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007506 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007507 bool sfinae = S.isSFINAEContext();
7508 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7509 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007510 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007511 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007512 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007513 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007514 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007515 } else if (lval == Expr::LV_MemberFunction) {
7516 // If it's an instance method, make a member pointer.
7517 // The expression must have exactly the form &A::foo.
7518
7519 // If the underlying expression isn't a decl ref, give up.
7520 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007521 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007522 << OrigOp->getSourceRange();
7523 return QualType();
7524 }
7525 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7526 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7527
7528 // The id-expression was parenthesized.
7529 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007530 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007531 << OrigOp->getSourceRange();
7532
7533 // The method was named without a qualifier.
7534 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007535 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007536 << op->getSourceRange();
7537 }
7538
John McCall09431682010-11-18 19:01:18 +00007539 return S.Context.getMemberPointerType(op->getType(),
7540 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007541 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007542 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007543 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007544 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007545 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007546 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007547 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007548 return QualType();
7549 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007550 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007551 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007552 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007553 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007554 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007555 AddressOfError = AO_Vector_Element;
John McCall7eb0a9e2010-11-24 05:12:34 +00007556 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007557 // cannot take address of a property expression.
Richard Trieu5520f232011-09-07 21:46:33 +00007558 AddressOfError = AO_Property_Expansion;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007559 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007560 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007561 // with the register storage-class specifier.
7562 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007563 // in C++ it is not error to take address of a register
7564 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007565 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007566 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007567 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007568 }
John McCallba135432009-11-21 08:51:07 +00007569 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007570 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007571 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007572 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007573 // Could be a pointer to member, though, if there is an explicit
7574 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007575 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007576 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007577 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007578 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007579 S.Diag(OpLoc,
7580 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007581 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007582 return QualType();
7583 }
Mike Stump1eb44332009-09-09 15:08:12 +00007584
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007585 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7586 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007587 return S.Context.getMemberPointerType(op->getType(),
7588 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007589 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007590 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007591 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007592 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007593 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007594
Richard Trieu5520f232011-09-07 21:46:33 +00007595 if (AddressOfError != AO_No_Error) {
7596 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7597 return QualType();
7598 }
7599
Eli Friedman441cf102009-05-16 23:27:50 +00007600 if (lval == Expr::LV_IncompleteVoidType) {
7601 // Taking the address of a void variable is technically illegal, but we
7602 // allow it in cases which are otherwise valid.
7603 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007604 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007605 }
7606
Reid Spencer5f016e22007-07-11 17:01:13 +00007607 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007608 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007609 return S.Context.getObjCObjectPointerType(op->getType());
7610 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007611}
7612
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007613/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007614static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7615 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007616 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007617 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007618
John Wiegley429bb272011-04-08 18:41:53 +00007619 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7620 if (ConvResult.isInvalid())
7621 return QualType();
7622 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007623 QualType OpTy = Op->getType();
7624 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007625
7626 if (isa<CXXReinterpretCastExpr>(Op)) {
7627 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7628 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7629 Op->getSourceRange());
7630 }
7631
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007632 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7633 // is an incomplete type or void. It would be possible to warn about
7634 // dereferencing a void pointer, but it's completely well-defined, and such a
7635 // warning is unlikely to catch any mistakes.
7636 if (const PointerType *PT = OpTy->getAs<PointerType>())
7637 Result = PT->getPointeeType();
7638 else if (const ObjCObjectPointerType *OPT =
7639 OpTy->getAs<ObjCObjectPointerType>())
7640 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007641 else {
John McCallfb8721c2011-04-10 19:13:55 +00007642 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007643 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007644 if (PR.take() != Op)
7645 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007646 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007647
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007648 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007649 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007650 << OpTy << Op->getSourceRange();
7651 return QualType();
7652 }
John McCall09431682010-11-18 19:01:18 +00007653
7654 // Dereferences are usually l-values...
7655 VK = VK_LValue;
7656
7657 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007658 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007659 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007660
7661 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007662}
7663
John McCall2de56d12010-08-25 11:45:40 +00007664static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007665 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007666 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007667 switch (Kind) {
7668 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007669 case tok::periodstar: Opc = BO_PtrMemD; break;
7670 case tok::arrowstar: Opc = BO_PtrMemI; break;
7671 case tok::star: Opc = BO_Mul; break;
7672 case tok::slash: Opc = BO_Div; break;
7673 case tok::percent: Opc = BO_Rem; break;
7674 case tok::plus: Opc = BO_Add; break;
7675 case tok::minus: Opc = BO_Sub; break;
7676 case tok::lessless: Opc = BO_Shl; break;
7677 case tok::greatergreater: Opc = BO_Shr; break;
7678 case tok::lessequal: Opc = BO_LE; break;
7679 case tok::less: Opc = BO_LT; break;
7680 case tok::greaterequal: Opc = BO_GE; break;
7681 case tok::greater: Opc = BO_GT; break;
7682 case tok::exclaimequal: Opc = BO_NE; break;
7683 case tok::equalequal: Opc = BO_EQ; break;
7684 case tok::amp: Opc = BO_And; break;
7685 case tok::caret: Opc = BO_Xor; break;
7686 case tok::pipe: Opc = BO_Or; break;
7687 case tok::ampamp: Opc = BO_LAnd; break;
7688 case tok::pipepipe: Opc = BO_LOr; break;
7689 case tok::equal: Opc = BO_Assign; break;
7690 case tok::starequal: Opc = BO_MulAssign; break;
7691 case tok::slashequal: Opc = BO_DivAssign; break;
7692 case tok::percentequal: Opc = BO_RemAssign; break;
7693 case tok::plusequal: Opc = BO_AddAssign; break;
7694 case tok::minusequal: Opc = BO_SubAssign; break;
7695 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7696 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7697 case tok::ampequal: Opc = BO_AndAssign; break;
7698 case tok::caretequal: Opc = BO_XorAssign; break;
7699 case tok::pipeequal: Opc = BO_OrAssign; break;
7700 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007701 }
7702 return Opc;
7703}
7704
John McCall2de56d12010-08-25 11:45:40 +00007705static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007706 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007707 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007708 switch (Kind) {
7709 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007710 case tok::plusplus: Opc = UO_PreInc; break;
7711 case tok::minusminus: Opc = UO_PreDec; break;
7712 case tok::amp: Opc = UO_AddrOf; break;
7713 case tok::star: Opc = UO_Deref; break;
7714 case tok::plus: Opc = UO_Plus; break;
7715 case tok::minus: Opc = UO_Minus; break;
7716 case tok::tilde: Opc = UO_Not; break;
7717 case tok::exclaim: Opc = UO_LNot; break;
7718 case tok::kw___real: Opc = UO_Real; break;
7719 case tok::kw___imag: Opc = UO_Imag; break;
7720 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007721 }
7722 return Opc;
7723}
7724
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007725/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7726/// This warning is only emitted for builtin assignment operations. It is also
7727/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007728static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007729 SourceLocation OpLoc) {
7730 if (!S.ActiveTemplateInstantiations.empty())
7731 return;
7732 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7733 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007734 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7735 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7736 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7737 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7738 if (!LHSDeclRef || !RHSDeclRef ||
7739 LHSDeclRef->getLocation().isMacroID() ||
7740 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007741 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007742 const ValueDecl *LHSDecl =
7743 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7744 const ValueDecl *RHSDecl =
7745 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7746 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007747 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007748 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007749 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007750 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007751 if (RefTy->getPointeeType().isVolatileQualified())
7752 return;
7753
7754 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007755 << LHSDeclRef->getType()
7756 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007757}
7758
Douglas Gregoreaebc752008-11-06 23:29:22 +00007759/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7760/// operator @p Opc at location @c TokLoc. This routine only supports
7761/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007762ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007763 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007764 Expr *LHSExpr, Expr *RHSExpr) {
7765 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007766 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007767 // The following two variables are used for compound assignment operators
7768 QualType CompLHSTy; // Type of LHS after promotions for computation
7769 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007770 ExprValueKind VK = VK_RValue;
7771 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007772
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007773 // Check if a 'foo<int>' involved in a binary op, identifies a single
7774 // function unambiguously (i.e. an lvalue ala 13.4)
7775 // But since an assignment can trigger target based overload, exclude it in
7776 // our blind search. i.e:
7777 // template<class T> void f(); template<class T, class U> void f(U);
7778 // f<int> == 0; // resolve f<int> blindly
7779 // void (*p)(int); p = f<int>; // resolve f<int> using target
7780 if (Opc != BO_Assign) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00007781 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007782 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007783 LHS = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007784
Richard Trieu78ea78b2011-09-07 01:49:20 +00007785 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007786 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007787 RHS = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007788 }
7789
Douglas Gregoreaebc752008-11-06 23:29:22 +00007790 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007791 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007792 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007793 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007794 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7795 VK = LHS.get()->getValueKind();
7796 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007797 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007798 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007799 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007800 break;
John McCall2de56d12010-08-25 11:45:40 +00007801 case BO_PtrMemD:
7802 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007803 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007804 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007805 break;
John McCall2de56d12010-08-25 11:45:40 +00007806 case BO_Mul:
7807 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007808 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007809 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007810 break;
John McCall2de56d12010-08-25 11:45:40 +00007811 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007812 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007813 break;
John McCall2de56d12010-08-25 11:45:40 +00007814 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007815 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007816 break;
John McCall2de56d12010-08-25 11:45:40 +00007817 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007818 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007819 break;
John McCall2de56d12010-08-25 11:45:40 +00007820 case BO_Shl:
7821 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007822 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007823 break;
John McCall2de56d12010-08-25 11:45:40 +00007824 case BO_LE:
7825 case BO_LT:
7826 case BO_GE:
7827 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007828 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007829 break;
John McCall2de56d12010-08-25 11:45:40 +00007830 case BO_EQ:
7831 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007832 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007833 break;
John McCall2de56d12010-08-25 11:45:40 +00007834 case BO_And:
7835 case BO_Xor:
7836 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007837 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007838 break;
John McCall2de56d12010-08-25 11:45:40 +00007839 case BO_LAnd:
7840 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007841 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007842 break;
John McCall2de56d12010-08-25 11:45:40 +00007843 case BO_MulAssign:
7844 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007845 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007846 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007847 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007848 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007850 break;
John McCall2de56d12010-08-25 11:45:40 +00007851 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007852 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007853 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007856 break;
John McCall2de56d12010-08-25 11:45:40 +00007857 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007858 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7859 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7860 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007861 break;
John McCall2de56d12010-08-25 11:45:40 +00007862 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007863 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7864 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7865 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007866 break;
John McCall2de56d12010-08-25 11:45:40 +00007867 case BO_ShlAssign:
7868 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007869 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007870 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007871 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7872 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007873 break;
John McCall2de56d12010-08-25 11:45:40 +00007874 case BO_AndAssign:
7875 case BO_XorAssign:
7876 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007877 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007878 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007879 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7880 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007881 break;
John McCall2de56d12010-08-25 11:45:40 +00007882 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007883 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7884 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7885 VK = RHS.get()->getValueKind();
7886 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007887 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007888 break;
7889 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007890 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007891 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007892
7893 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007894 CheckArrayAccess(LHS.get());
7895 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007896
Eli Friedmanab3a8522009-03-28 01:22:36 +00007897 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007898 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007899 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007900 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007901 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007902 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007903 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007904 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007905 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007906 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007907 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007908}
7909
Sebastian Redlaee3c932009-10-27 12:10:02 +00007910/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7911/// operators are mixed in a way that suggests that the programmer forgot that
7912/// comparison operators have higher precedence. The most typical example of
7913/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007914static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007915 SourceLocation OpLoc, Expr *LHSExpr,
7916 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007917 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007918 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7919 RHSopc = static_cast<BinOp::Opcode>(-1);
7920 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7921 LHSopc = BO->getOpcode();
7922 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7923 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007924
7925 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007926 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007927 return;
7928
7929 // Bitwise operations are sometimes used as eager logical ops.
7930 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007931 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7932 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007933 return;
7934
Richard Trieu78ea78b2011-09-07 01:49:20 +00007935 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7936 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007937 if (!isLeftComp && !isRightComp) return;
7938
Richard Trieu78ea78b2011-09-07 01:49:20 +00007939 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7940 OpLoc)
7941 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7942 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7943 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007944 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00007945 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7946 RHSExpr->getLocEnd())
7947 : SourceRange(LHSExpr->getLocStart(),
7948 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00007949
7950 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7951 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7952 SuggestParentheses(Self, OpLoc,
7953 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007954 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00007955 SuggestParentheses(Self, OpLoc,
7956 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7957 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007958}
7959
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007960/// \brief It accepts a '&' expr that is inside a '|' one.
7961/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7962/// in parentheses.
7963static void
7964EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7965 BinaryOperator *Bop) {
7966 assert(Bop->getOpcode() == BO_And);
7967 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7968 << Bop->getSourceRange() << OpLoc;
7969 SuggestParentheses(Self, Bop->getOperatorLoc(),
7970 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7971 Bop->getSourceRange());
7972}
7973
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007974/// \brief It accepts a '&&' expr that is inside a '||' one.
7975/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7976/// in parentheses.
7977static void
7978EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007979 BinaryOperator *Bop) {
7980 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007981 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7982 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007983 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007984 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007985 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007986}
7987
7988/// \brief Returns true if the given expression can be evaluated as a constant
7989/// 'true'.
7990static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7991 bool Res;
7992 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7993}
7994
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007995/// \brief Returns true if the given expression can be evaluated as a constant
7996/// 'false'.
7997static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7998 bool Res;
7999 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8000}
8001
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008002/// \brief Look for '&&' in the left hand of a '||' expr.
8003static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008004 Expr *LHSExpr, Expr *RHSExpr) {
8005 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008006 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008007 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008008 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008009 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008010 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8011 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8012 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8013 } else if (Bop->getOpcode() == BO_LOr) {
8014 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8015 // If it's "a || b && 1 || c" we didn't warn earlier for
8016 // "a || b && 1", but warn now.
8017 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8018 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8019 }
8020 }
8021 }
8022}
8023
8024/// \brief Look for '&&' in the right hand of a '||' expr.
8025static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008026 Expr *LHSExpr, Expr *RHSExpr) {
8027 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008028 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008029 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008030 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008031 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008032 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8033 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8034 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008035 }
8036 }
8037}
8038
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008039/// \brief Look for '&' in the left or right hand of a '|' expr.
8040static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8041 Expr *OrArg) {
8042 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8043 if (Bop->getOpcode() == BO_And)
8044 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8045 }
8046}
8047
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008048/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008049/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008050static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008051 SourceLocation OpLoc, Expr *LHSExpr,
8052 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008053 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008054 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008055 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008056
8057 // Diagnose "arg1 & arg2 | arg3"
8058 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008059 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8060 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008061 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008062
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008063 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8064 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008065 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008066 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8067 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008068 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008069}
8070
Reid Spencer5f016e22007-07-11 17:01:13 +00008071// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008072ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008073 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008074 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008075 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008076 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8077 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008078
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008079 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008080 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008081
Richard Trieubefece12011-09-07 02:02:10 +00008082 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008083}
8084
John McCall60d7b3a2010-08-24 06:29:42 +00008085ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008086 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008087 Expr *LHSExpr, Expr *RHSExpr) {
John McCall01b2e4e2010-12-06 05:26:58 +00008088 if (getLangOptions().CPlusPlus) {
8089 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008090
Richard Trieubefece12011-09-07 02:02:10 +00008091 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall01b2e4e2010-12-06 05:26:58 +00008092 UseBuiltinOperator = false;
Richard Trieubefece12011-09-07 02:02:10 +00008093 } else if (Opc == BO_Assign &&
8094 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall01b2e4e2010-12-06 05:26:58 +00008095 UseBuiltinOperator = true;
8096 } else {
Richard Trieubefece12011-09-07 02:02:10 +00008097 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8098 !RHSExpr->getType()->isOverloadableType();
John McCall01b2e4e2010-12-06 05:26:58 +00008099 }
8100
8101 if (!UseBuiltinOperator) {
8102 // Find all of the overloaded operators visible from this
8103 // point. We perform both an operator-name lookup from the local
8104 // scope and an argument-dependent lookup based on the types of
8105 // the arguments.
8106 UnresolvedSet<16> Functions;
8107 OverloadedOperatorKind OverOp
8108 = BinaryOperator::getOverloadedOperator(Opc);
8109 if (S && OverOp != OO_None)
Richard Trieubefece12011-09-07 02:02:10 +00008110 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8111 RHSExpr->getType(), Functions);
John McCall01b2e4e2010-12-06 05:26:58 +00008112
8113 // Build the (potentially-overloaded, potentially-dependent)
8114 // binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008115 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall01b2e4e2010-12-06 05:26:58 +00008116 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008117 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008118
Douglas Gregoreaebc752008-11-06 23:29:22 +00008119 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008120 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008121}
8122
John McCall60d7b3a2010-08-24 06:29:42 +00008123ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008124 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008125 Expr *InputExpr) {
8126 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008127 ExprValueKind VK = VK_RValue;
8128 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008129 QualType resultType;
8130 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008131 case UO_PreInc:
8132 case UO_PreDec:
8133 case UO_PostInc:
8134 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008135 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008136 Opc == UO_PreInc ||
8137 Opc == UO_PostInc,
8138 Opc == UO_PreInc ||
8139 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008140 break;
John McCall2de56d12010-08-25 11:45:40 +00008141 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008142 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008143 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008144 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008145 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008146 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008147 Input = move(resolved);
8148 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8149 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008150 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008151 }
John McCall2de56d12010-08-25 11:45:40 +00008152 case UO_Plus:
8153 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008154 Input = UsualUnaryConversions(Input.take());
8155 if (Input.isInvalid()) return ExprError();
8156 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008157 if (resultType->isDependentType())
8158 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008159 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8160 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008161 break;
8162 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8163 resultType->isEnumeralType())
8164 break;
8165 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008166 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008167 resultType->isPointerType())
8168 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008169 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008170 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008171 if (Input.isInvalid()) return ExprError();
8172 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008173 }
Douglas Gregor74253732008-11-19 15:42:04 +00008174
Sebastian Redl0eb23302009-01-19 00:08:26 +00008175 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008176 << resultType << Input.get()->getSourceRange());
8177
John McCall2de56d12010-08-25 11:45:40 +00008178 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008179 Input = UsualUnaryConversions(Input.take());
8180 if (Input.isInvalid()) return ExprError();
8181 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008182 if (resultType->isDependentType())
8183 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008184 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8185 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8186 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008187 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008188 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008189 else if (resultType->hasIntegerRepresentation())
8190 break;
8191 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008192 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008193 if (Input.isInvalid()) return ExprError();
8194 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008195 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008196 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008197 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008198 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008199 break;
John Wiegley429bb272011-04-08 18:41:53 +00008200
John McCall2de56d12010-08-25 11:45:40 +00008201 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008202 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008203 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8204 if (Input.isInvalid()) return ExprError();
8205 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008206 if (resultType->isDependentType())
8207 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008208 if (resultType->isScalarType()) {
8209 // C99 6.5.3.3p1: ok, fallthrough;
8210 if (Context.getLangOptions().CPlusPlus) {
8211 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8212 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008213 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8214 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008215 }
John McCall2cd11fe2010-10-12 02:09:17 +00008216 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008217 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008218 if (Input.isInvalid()) return ExprError();
8219 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008220 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008221 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008222 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008223 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008224
Reid Spencer5f016e22007-07-11 17:01:13 +00008225 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008226 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008227 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008228 break;
John McCall2de56d12010-08-25 11:45:40 +00008229 case UO_Real:
8230 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008231 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008232 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008233 if (Input.isInvalid()) return ExprError();
8234 if (Input.get()->getValueKind() != VK_RValue &&
8235 Input.get()->getObjectKind() == OK_Ordinary)
8236 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008237 break;
John McCall2de56d12010-08-25 11:45:40 +00008238 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008239 resultType = Input.get()->getType();
8240 VK = Input.get()->getValueKind();
8241 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008242 break;
8243 }
John Wiegley429bb272011-04-08 18:41:53 +00008244 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008245 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008246
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008247 // Check for array bounds violations in the operand of the UnaryOperator,
8248 // except for the '*' and '&' operators that have to be handled specially
8249 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8250 // that are explicitly defined as valid by the standard).
8251 if (Opc != UO_AddrOf && Opc != UO_Deref)
8252 CheckArrayAccess(Input.get());
8253
John Wiegley429bb272011-04-08 18:41:53 +00008254 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008255 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008256}
8257
John McCall60d7b3a2010-08-24 06:29:42 +00008258ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008259 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008260 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008261 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008262 // Find all of the overloaded operators visible from this
8263 // point. We perform both an operator-name lookup from the local
8264 // scope and an argument-dependent lookup based on the types of
8265 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008266 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008267 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008268 if (S && OverOp != OO_None)
8269 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8270 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008271
John McCall9ae2f072010-08-23 23:25:46 +00008272 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008273 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008274
John McCall9ae2f072010-08-23 23:25:46 +00008275 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008276}
8277
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008278// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008279ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008280 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008281 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008282}
8283
Steve Naroff1b273c42007-09-16 14:56:35 +00008284/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008285ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008286 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008287 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008288 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008289 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008290 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008291}
8292
John McCallf85e1932011-06-15 23:02:42 +00008293/// Given the last statement in a statement-expression, check whether
8294/// the result is a producing expression (like a call to an
8295/// ns_returns_retained function) and, if so, rebuild it to hoist the
8296/// release out of the full-expression. Otherwise, return null.
8297/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008298static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008299 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008300 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008301 if (!cleanups) return 0;
8302
8303 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008304 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008305 return 0;
8306
8307 // Splice out the cast. This shouldn't modify any interesting
8308 // features of the statement.
8309 Expr *producer = cast->getSubExpr();
8310 assert(producer->getType() == cast->getType());
8311 assert(producer->getValueKind() == cast->getValueKind());
8312 cleanups->setSubExpr(producer);
8313 return cleanups;
8314}
8315
John McCall60d7b3a2010-08-24 06:29:42 +00008316ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008317Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008318 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008319 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8320 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8321
Douglas Gregordd8f5692010-03-10 04:54:39 +00008322 bool isFileScope
8323 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008324 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008325 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008326
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008327 // FIXME: there are a variety of strange constraints to enforce here, for
8328 // example, it is not possible to goto into a stmt expression apparently.
8329 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008330
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008331 // If there are sub stmts in the compound stmt, take the type of the last one
8332 // as the type of the stmtexpr.
8333 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008334 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008335 if (!Compound->body_empty()) {
8336 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008337 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008338 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008339 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8340 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008341 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008342 }
John McCallf85e1932011-06-15 23:02:42 +00008343
John Wiegley429bb272011-04-08 18:41:53 +00008344 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008345 // Do function/array conversion on the last expression, but not
8346 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008347 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8348 if (LastExpr.isInvalid())
8349 return ExprError();
8350 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008351
John Wiegley429bb272011-04-08 18:41:53 +00008352 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008353 // In ARC, if the final expression ends in a consume, splice
8354 // the consume out and bind it later. In the alternate case
8355 // (when dealing with a retainable type), the result
8356 // initialization will create a produce. In both cases the
8357 // result will be +1, and we'll need to balance that out with
8358 // a bind.
8359 if (Expr *rebuiltLastStmt
8360 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8361 LastExpr = rebuiltLastStmt;
8362 } else {
8363 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008364 InitializedEntity::InitializeResult(LPLoc,
8365 Ty,
8366 false),
8367 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008368 LastExpr);
8369 }
8370
John Wiegley429bb272011-04-08 18:41:53 +00008371 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008372 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008373 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008374 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008375 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008376 else
John Wiegley429bb272011-04-08 18:41:53 +00008377 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008378 StmtExprMayBindToTemp = true;
8379 }
8380 }
8381 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008382 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008383
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008384 // FIXME: Check that expression type is complete/non-abstract; statement
8385 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008386 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8387 if (StmtExprMayBindToTemp)
8388 return MaybeBindToTemporary(ResStmtExpr);
8389 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008390}
Steve Naroffd34e9152007-08-01 22:05:33 +00008391
John McCall60d7b3a2010-08-24 06:29:42 +00008392ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008393 TypeSourceInfo *TInfo,
8394 OffsetOfComponent *CompPtr,
8395 unsigned NumComponents,
8396 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008397 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008398 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008399 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008400
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008401 // We must have at least one component that refers to the type, and the first
8402 // one is known to be a field designator. Verify that the ArgTy represents
8403 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008404 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008405 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8406 << ArgTy << TypeRange);
8407
8408 // Type must be complete per C99 7.17p3 because a declaring a variable
8409 // with an incomplete type would be ill-formed.
8410 if (!Dependent
8411 && RequireCompleteType(BuiltinLoc, ArgTy,
8412 PDiag(diag::err_offsetof_incomplete_type)
8413 << TypeRange))
8414 return ExprError();
8415
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008416 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8417 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008418 // FIXME: This diagnostic isn't actually visible because the location is in
8419 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008420 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008421 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8422 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008423
8424 bool DidWarnAboutNonPOD = false;
8425 QualType CurrentType = ArgTy;
8426 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008427 SmallVector<OffsetOfNode, 4> Comps;
8428 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008429 for (unsigned i = 0; i != NumComponents; ++i) {
8430 const OffsetOfComponent &OC = CompPtr[i];
8431 if (OC.isBrackets) {
8432 // Offset of an array sub-field. TODO: Should we allow vector elements?
8433 if (!CurrentType->isDependentType()) {
8434 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8435 if(!AT)
8436 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8437 << CurrentType);
8438 CurrentType = AT->getElementType();
8439 } else
8440 CurrentType = Context.DependentTy;
8441
8442 // The expression must be an integral expression.
8443 // FIXME: An integral constant expression?
8444 Expr *Idx = static_cast<Expr*>(OC.U.E);
8445 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8446 !Idx->getType()->isIntegerType())
8447 return ExprError(Diag(Idx->getLocStart(),
8448 diag::err_typecheck_subscript_not_integer)
8449 << Idx->getSourceRange());
8450
8451 // Record this array index.
8452 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8453 Exprs.push_back(Idx);
8454 continue;
8455 }
8456
8457 // Offset of a field.
8458 if (CurrentType->isDependentType()) {
8459 // We have the offset of a field, but we can't look into the dependent
8460 // type. Just record the identifier of the field.
8461 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8462 CurrentType = Context.DependentTy;
8463 continue;
8464 }
8465
8466 // We need to have a complete type to look into.
8467 if (RequireCompleteType(OC.LocStart, CurrentType,
8468 diag::err_offsetof_incomplete_type))
8469 return ExprError();
8470
8471 // Look for the designated field.
8472 const RecordType *RC = CurrentType->getAs<RecordType>();
8473 if (!RC)
8474 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8475 << CurrentType);
8476 RecordDecl *RD = RC->getDecl();
8477
8478 // C++ [lib.support.types]p5:
8479 // The macro offsetof accepts a restricted set of type arguments in this
8480 // International Standard. type shall be a POD structure or a POD union
8481 // (clause 9).
8482 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8483 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008484 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008485 PDiag(diag::warn_offsetof_non_pod_type)
8486 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8487 << CurrentType))
8488 DidWarnAboutNonPOD = true;
8489 }
8490
8491 // Look for the field.
8492 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8493 LookupQualifiedName(R, RD);
8494 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008495 IndirectFieldDecl *IndirectMemberDecl = 0;
8496 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008497 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008498 MemberDecl = IndirectMemberDecl->getAnonField();
8499 }
8500
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008501 if (!MemberDecl)
8502 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8503 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8504 OC.LocEnd));
8505
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008506 // C99 7.17p3:
8507 // (If the specified member is a bit-field, the behavior is undefined.)
8508 //
8509 // We diagnose this as an error.
8510 if (MemberDecl->getBitWidth()) {
8511 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8512 << MemberDecl->getDeclName()
8513 << SourceRange(BuiltinLoc, RParenLoc);
8514 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8515 return ExprError();
8516 }
Eli Friedman19410a72010-08-05 10:11:36 +00008517
8518 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008519 if (IndirectMemberDecl)
8520 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008521
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008522 // If the member was found in a base class, introduce OffsetOfNodes for
8523 // the base class indirections.
8524 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8525 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008526 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008527 CXXBasePath &Path = Paths.front();
8528 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8529 B != BEnd; ++B)
8530 Comps.push_back(OffsetOfNode(B->Base));
8531 }
Eli Friedman19410a72010-08-05 10:11:36 +00008532
Francois Pichet87c2e122010-11-21 06:08:52 +00008533 if (IndirectMemberDecl) {
8534 for (IndirectFieldDecl::chain_iterator FI =
8535 IndirectMemberDecl->chain_begin(),
8536 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8537 assert(isa<FieldDecl>(*FI));
8538 Comps.push_back(OffsetOfNode(OC.LocStart,
8539 cast<FieldDecl>(*FI), OC.LocEnd));
8540 }
8541 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008542 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008543
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008544 CurrentType = MemberDecl->getType().getNonReferenceType();
8545 }
8546
8547 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8548 TInfo, Comps.data(), Comps.size(),
8549 Exprs.data(), Exprs.size(), RParenLoc));
8550}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008551
John McCall60d7b3a2010-08-24 06:29:42 +00008552ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008553 SourceLocation BuiltinLoc,
8554 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008555 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008556 OffsetOfComponent *CompPtr,
8557 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008558 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008559
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008560 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008561 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008562 if (ArgTy.isNull())
8563 return ExprError();
8564
Eli Friedman5a15dc12010-08-05 10:15:45 +00008565 if (!ArgTInfo)
8566 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8567
8568 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008569 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008570}
8571
8572
John McCall60d7b3a2010-08-24 06:29:42 +00008573ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008574 Expr *CondExpr,
8575 Expr *LHSExpr, Expr *RHSExpr,
8576 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008577 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8578
John McCallf89e55a2010-11-18 06:31:45 +00008579 ExprValueKind VK = VK_RValue;
8580 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008581 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008582 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008583 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008584 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008585 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008586 } else {
8587 // The conditional expression is required to be a constant expression.
8588 llvm::APSInt condEval(32);
8589 SourceLocation ExpLoc;
8590 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008591 return ExprError(Diag(ExpLoc,
8592 diag::err_typecheck_choose_expr_requires_constant)
8593 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008594
Sebastian Redl28507842009-02-26 14:39:58 +00008595 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008596 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8597
8598 resType = ActiveExpr->getType();
8599 ValueDependent = ActiveExpr->isValueDependent();
8600 VK = ActiveExpr->getValueKind();
8601 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008602 }
8603
Sebastian Redlf53597f2009-03-15 17:47:39 +00008604 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008605 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008606 resType->isDependentType(),
8607 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008608}
8609
Steve Naroff4eb206b2008-09-03 18:15:37 +00008610//===----------------------------------------------------------------------===//
8611// Clang Extensions.
8612//===----------------------------------------------------------------------===//
8613
8614/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008615void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008616 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008617 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008618 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008619 if (CurScope)
8620 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008621 else
8622 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008623}
8624
Mike Stump98eb8a72009-02-04 22:31:32 +00008625void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008626 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008627 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008628 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008629
John McCallbf1a0282010-06-04 23:28:52 +00008630 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008631 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008632
John McCall711c52b2011-01-05 12:14:39 +00008633 // GetTypeForDeclarator always produces a function type for a block
8634 // literal signature. Furthermore, it is always a FunctionProtoType
8635 // unless the function was written with a typedef.
8636 assert(T->isFunctionType() &&
8637 "GetTypeForDeclarator made a non-function block signature");
8638
8639 // Look for an explicit signature in that function type.
8640 FunctionProtoTypeLoc ExplicitSignature;
8641
8642 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8643 if (isa<FunctionProtoTypeLoc>(tmp)) {
8644 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8645
8646 // Check whether that explicit signature was synthesized by
8647 // GetTypeForDeclarator. If so, don't save that as part of the
8648 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008649 if (ExplicitSignature.getLocalRangeBegin() ==
8650 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008651 // This would be much cheaper if we stored TypeLocs instead of
8652 // TypeSourceInfos.
8653 TypeLoc Result = ExplicitSignature.getResultLoc();
8654 unsigned Size = Result.getFullDataSize();
8655 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8656 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8657
8658 ExplicitSignature = FunctionProtoTypeLoc();
8659 }
John McCall82dc0092010-06-04 11:21:44 +00008660 }
Mike Stump1eb44332009-09-09 15:08:12 +00008661
John McCall711c52b2011-01-05 12:14:39 +00008662 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8663 CurBlock->FunctionType = T;
8664
8665 const FunctionType *Fn = T->getAs<FunctionType>();
8666 QualType RetTy = Fn->getResultType();
8667 bool isVariadic =
8668 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8669
John McCallc71a4912010-06-04 19:02:56 +00008670 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008671
John McCall82dc0092010-06-04 11:21:44 +00008672 // Don't allow returning a objc interface by value.
8673 if (RetTy->isObjCObjectType()) {
8674 Diag(ParamInfo.getSourceRange().getBegin(),
8675 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8676 return;
8677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008678
John McCall82dc0092010-06-04 11:21:44 +00008679 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008680 // return type. TODO: what should we do with declarators like:
8681 // ^ * { ... }
8682 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008683 if (RetTy != Context.DependentTy)
8684 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008685
John McCall82dc0092010-06-04 11:21:44 +00008686 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008687 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008688 if (ExplicitSignature) {
8689 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8690 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008691 if (Param->getIdentifier() == 0 &&
8692 !Param->isImplicit() &&
8693 !Param->isInvalidDecl() &&
8694 !getLangOptions().CPlusPlus)
8695 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008696 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008697 }
John McCall82dc0092010-06-04 11:21:44 +00008698
8699 // Fake up parameter variables if we have a typedef, like
8700 // ^ fntype { ... }
8701 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8702 for (FunctionProtoType::arg_type_iterator
8703 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8704 ParmVarDecl *Param =
8705 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8706 ParamInfo.getSourceRange().getBegin(),
8707 *I);
John McCallc71a4912010-06-04 19:02:56 +00008708 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008709 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008710 }
John McCall82dc0092010-06-04 11:21:44 +00008711
John McCallc71a4912010-06-04 19:02:56 +00008712 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008713 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00008714 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00008715 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8716 CurBlock->TheDecl->param_end(),
8717 /*CheckParameterNames=*/false);
8718 }
8719
John McCall82dc0092010-06-04 11:21:44 +00008720 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008721 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008722
John McCallc71a4912010-06-04 19:02:56 +00008723 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008724 Diag(ParamInfo.getAttributes()->getLoc(),
8725 diag::warn_attribute_sentinel_not_variadic) << 1;
8726 // FIXME: remove the attribute.
8727 }
8728
8729 // Put the parameter variables in scope. We can bail out immediately
8730 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008731 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008732 return;
8733
Steve Naroff090276f2008-10-10 01:28:17 +00008734 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008735 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8736 (*AI)->setOwningFunction(CurBlock->TheDecl);
8737
Steve Naroff090276f2008-10-10 01:28:17 +00008738 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008739 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008740 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008741
Steve Naroff090276f2008-10-10 01:28:17 +00008742 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008743 }
John McCall7a9813c2010-01-22 00:28:27 +00008744 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008745}
8746
8747/// ActOnBlockError - If there is an error parsing a block, this callback
8748/// is invoked to pop the information about the block from the action impl.
8749void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008750 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008751 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008752 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008753}
8754
8755/// ActOnBlockStmtExpr - This is called when the body of a block statement
8756/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008757ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008758 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008759 // If blocks are disabled, emit an error.
8760 if (!LangOpts.Blocks)
8761 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008762
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008763 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008764
Steve Naroff090276f2008-10-10 01:28:17 +00008765 PopDeclContext();
8766
Steve Naroff4eb206b2008-09-03 18:15:37 +00008767 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008768 if (!BSI->ReturnType.isNull())
8769 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008770
Mike Stump56925862009-07-28 22:04:01 +00008771 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008772 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008773
John McCall469a1eb2011-02-02 13:00:07 +00008774 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008775 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8776 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008777
John McCallc71a4912010-06-04 19:02:56 +00008778 // If the user wrote a function type in some form, try to use that.
8779 if (!BSI->FunctionType.isNull()) {
8780 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8781
8782 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8783 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8784
8785 // Turn protoless block types into nullary block types.
8786 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008787 FunctionProtoType::ExtProtoInfo EPI;
8788 EPI.ExtInfo = Ext;
8789 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008790
8791 // Otherwise, if we don't need to change anything about the function type,
8792 // preserve its sugar structure.
8793 } else if (FTy->getResultType() == RetTy &&
8794 (!NoReturn || FTy->getNoReturnAttr())) {
8795 BlockTy = BSI->FunctionType;
8796
8797 // Otherwise, make the minimal modifications to the function type.
8798 } else {
8799 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008800 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8801 EPI.TypeQuals = 0; // FIXME: silently?
8802 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008803 BlockTy = Context.getFunctionType(RetTy,
8804 FPT->arg_type_begin(),
8805 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008806 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008807 }
8808
8809 // If we don't have a function type, just build one from nothing.
8810 } else {
John McCalle23cf432010-12-14 08:05:40 +00008811 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008812 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008813 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008814 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008815
John McCallc71a4912010-06-04 19:02:56 +00008816 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8817 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008818 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008819
Chris Lattner17a78302009-04-19 05:28:12 +00008820 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008821 if (getCurFunction()->NeedsScopeChecking() &&
8822 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008823 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008824
Chris Lattnere476bdc2011-02-17 23:58:47 +00008825 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008826
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008827 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8828 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8829 const VarDecl *variable = ci->getVariable();
8830 QualType T = variable->getType();
8831 QualType::DestructionKind destructKind = T.isDestructedType();
8832 if (destructKind != QualType::DK_none)
8833 getCurFunction()->setHasBranchProtectedScope();
8834 }
8835
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008836 computeNRVO(Body, getCurBlock());
8837
Benjamin Kramerd2486192011-07-12 14:11:05 +00008838 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8839 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8840 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8841
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008842 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008843}
8844
John McCall60d7b3a2010-08-24 06:29:42 +00008845ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008846 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008847 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008848 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008849 GetTypeFromParser(Ty, &TInfo);
8850 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008851}
8852
John McCall60d7b3a2010-08-24 06:29:42 +00008853ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008854 Expr *E, TypeSourceInfo *TInfo,
8855 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008856 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008857
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008858 // Get the va_list type
8859 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008860 if (VaListType->isArrayType()) {
8861 // Deal with implicit array decay; for example, on x86-64,
8862 // va_list is an array, but it's supposed to decay to
8863 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008864 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008865 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008866 ExprResult Result = UsualUnaryConversions(E);
8867 if (Result.isInvalid())
8868 return ExprError();
8869 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008870 } else {
8871 // Otherwise, the va_list argument must be an l-value because
8872 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008873 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008874 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008875 return ExprError();
8876 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008877
Douglas Gregordd027302009-05-19 23:10:31 +00008878 if (!E->isTypeDependent() &&
8879 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008880 return ExprError(Diag(E->getLocStart(),
8881 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008882 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008883 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008884
David Majnemer0adde122011-06-14 05:17:32 +00008885 if (!TInfo->getType()->isDependentType()) {
8886 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8887 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8888 << TInfo->getTypeLoc().getSourceRange()))
8889 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008890
David Majnemer0adde122011-06-14 05:17:32 +00008891 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8892 TInfo->getType(),
8893 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8894 << TInfo->getTypeLoc().getSourceRange()))
8895 return ExprError();
8896
Douglas Gregor4eb75222011-07-30 06:45:27 +00008897 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008898 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008899 TInfo->getType()->isObjCLifetimeType()
8900 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8901 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008902 << TInfo->getType()
8903 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008904 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008905
8906 // Check for va_arg where arguments of the given type will be promoted
8907 // (i.e. this va_arg is guaranteed to have undefined behavior).
8908 QualType PromoteType;
8909 if (TInfo->getType()->isPromotableIntegerType()) {
8910 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8911 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8912 PromoteType = QualType();
8913 }
8914 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8915 PromoteType = Context.DoubleTy;
8916 if (!PromoteType.isNull())
8917 Diag(TInfo->getTypeLoc().getBeginLoc(),
8918 diag::warn_second_parameter_to_va_arg_never_compatible)
8919 << TInfo->getType()
8920 << PromoteType
8921 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008922 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008923
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008924 QualType T = TInfo->getType().getNonLValueExprType(Context);
8925 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008926}
8927
John McCall60d7b3a2010-08-24 06:29:42 +00008928ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008929 // The type of __null will be int or long, depending on the size of
8930 // pointers on the target.
8931 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008932 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8933 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008934 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008935 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008936 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008937 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008938 Ty = Context.LongLongTy;
8939 else {
Richard Trieu47456fa2011-09-21 02:50:14 +00008940 assert(0 && "I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008941 Ty = Context.IntTy;
8942 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008943
Sebastian Redlf53597f2009-03-15 17:47:39 +00008944 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008945}
8946
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008947static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008948 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008949 if (!SemaRef.getLangOptions().ObjC1)
8950 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008951
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008952 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8953 if (!PT)
8954 return;
8955
8956 // Check if the destination is of type 'id'.
8957 if (!PT->isObjCIdType()) {
8958 // Check if the destination is the 'NSString' interface.
8959 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8960 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8961 return;
8962 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008963
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008964 // Strip off any parens and casts.
8965 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008966 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008967 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008968
Douglas Gregor849b2432010-03-31 17:46:05 +00008969 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008970}
8971
Chris Lattner5cf216b2008-01-04 18:04:52 +00008972bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8973 SourceLocation Loc,
8974 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008975 Expr *SrcExpr, AssignmentAction Action,
8976 bool *Complained) {
8977 if (Complained)
8978 *Complained = false;
8979
Chris Lattner5cf216b2008-01-04 18:04:52 +00008980 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008981 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008982 bool isInvalid = false;
8983 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008984 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008985 ConversionFixItGenerator ConvHints;
8986 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008987
Chris Lattner5cf216b2008-01-04 18:04:52 +00008988 switch (ConvTy) {
8989 default: assert(0 && "Unknown conversion type");
8990 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008991 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008992 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008993 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8994 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008995 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008996 case IntToPointer:
8997 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008998 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8999 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009000 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009001 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009002 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009003 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009004 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9005 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009006 if (Hint.isNull() && !CheckInferredResultType) {
9007 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9008 }
9009 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009010 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009011 case IncompatiblePointerSign:
9012 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9013 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009014 case FunctionVoidPointer:
9015 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9016 break;
John McCall86c05f32011-02-01 00:10:29 +00009017 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009018 // Perform array-to-pointer decay if necessary.
9019 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9020
John McCall86c05f32011-02-01 00:10:29 +00009021 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9022 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9023 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9024 DiagKind = diag::err_typecheck_incompatible_address_space;
9025 break;
John McCallf85e1932011-06-15 23:02:42 +00009026
9027
9028 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009029 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009030 break;
John McCall86c05f32011-02-01 00:10:29 +00009031 }
9032
9033 llvm_unreachable("unknown error case for discarding qualifiers!");
9034 // fallthrough
9035 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009036 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009037 // If the qualifiers lost were because we were applying the
9038 // (deprecated) C++ conversion from a string literal to a char*
9039 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9040 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009041 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009042 // bit of refactoring (so that the second argument is an
9043 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009044 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009045 // C++ semantics.
9046 if (getLangOptions().CPlusPlus &&
9047 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9048 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009049 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9050 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009051 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009052 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009053 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009054 case IntToBlockPointer:
9055 DiagKind = diag::err_int_to_block_pointer;
9056 break;
9057 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009058 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009059 break;
Steve Naroff39579072008-10-14 22:18:38 +00009060 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009061 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009062 // it can give a more specific diagnostic.
9063 DiagKind = diag::warn_incompatible_qualified_id;
9064 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009065 case IncompatibleVectors:
9066 DiagKind = diag::warn_incompatible_vectors;
9067 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009068 case IncompatibleObjCWeakRef:
9069 DiagKind = diag::err_arc_weak_unavailable_assign;
9070 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009071 case Incompatible:
9072 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009073 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9074 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009075 isInvalid = true;
9076 break;
9077 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009078
Douglas Gregord4eea832010-04-09 00:35:39 +00009079 QualType FirstType, SecondType;
9080 switch (Action) {
9081 case AA_Assigning:
9082 case AA_Initializing:
9083 // The destination type comes first.
9084 FirstType = DstType;
9085 SecondType = SrcType;
9086 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009087
Douglas Gregord4eea832010-04-09 00:35:39 +00009088 case AA_Returning:
9089 case AA_Passing:
9090 case AA_Converting:
9091 case AA_Sending:
9092 case AA_Casting:
9093 // The source type comes first.
9094 FirstType = SrcType;
9095 SecondType = DstType;
9096 break;
9097 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009098
Anna Zaks67221552011-07-28 19:51:27 +00009099 PartialDiagnostic FDiag = PDiag(DiagKind);
9100 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9101
9102 // If we can fix the conversion, suggest the FixIts.
9103 assert(ConvHints.isNull() || Hint.isNull());
9104 if (!ConvHints.isNull()) {
9105 for (llvm::SmallVector<FixItHint, 1>::iterator
9106 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9107 HI != HE; ++HI)
9108 FDiag << *HI;
9109 } else {
9110 FDiag << Hint;
9111 }
9112 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9113
9114 Diag(Loc, FDiag);
9115
Douglas Gregor926df6c2011-06-11 01:09:30 +00009116 if (CheckInferredResultType)
9117 EmitRelatedResultTypeNote(SrcExpr);
9118
Douglas Gregora41a8c52010-04-22 00:20:18 +00009119 if (Complained)
9120 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009121 return isInvalid;
9122}
Anders Carlssone21555e2008-11-30 19:50:32 +00009123
Chris Lattner3bf68932009-04-25 21:59:05 +00009124bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009125 llvm::APSInt ICEResult;
9126 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9127 if (Result)
9128 *Result = ICEResult;
9129 return false;
9130 }
9131
Anders Carlssone21555e2008-11-30 19:50:32 +00009132 Expr::EvalResult EvalResult;
9133
Mike Stumpeed9cac2009-02-19 03:04:26 +00009134 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009135 EvalResult.HasSideEffects) {
9136 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9137
9138 if (EvalResult.Diag) {
9139 // We only show the note if it's not the usual "invalid subexpression"
9140 // or if it's actually in a subexpression.
9141 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9142 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9143 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9144 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009145
Anders Carlssone21555e2008-11-30 19:50:32 +00009146 return true;
9147 }
9148
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009149 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9150 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009151
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009152 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009153 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9154 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009155 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009156
Anders Carlssone21555e2008-11-30 19:50:32 +00009157 if (Result)
9158 *Result = EvalResult.Val.getInt();
9159 return false;
9160}
Douglas Gregore0762c92009-06-19 23:52:42 +00009161
Douglas Gregor2afce722009-11-26 00:44:06 +00009162void
Mike Stump1eb44332009-09-09 15:08:12 +00009163Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009164 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009165 ExpressionEvaluationContextRecord(NewContext,
9166 ExprTemporaries.size(),
9167 ExprNeedsCleanups));
9168 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009169}
9170
Richard Trieu67e29332011-08-02 04:35:43 +00009171void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009172 // Pop the current expression evaluation context off the stack.
9173 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9174 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009175
Douglas Gregor06d33692009-12-12 07:57:52 +00009176 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9177 if (Rec.PotentiallyReferenced) {
9178 // Mark any remaining declarations in the current position of the stack
9179 // as "referenced". If they were not meant to be referenced, semantic
9180 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009181 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009182 I = Rec.PotentiallyReferenced->begin(),
9183 IEnd = Rec.PotentiallyReferenced->end();
9184 I != IEnd; ++I)
9185 MarkDeclarationReferenced(I->first, I->second);
9186 }
9187
9188 if (Rec.PotentiallyDiagnosed) {
9189 // Emit any pending diagnostics.
9190 for (PotentiallyEmittedDiagnostics::iterator
9191 I = Rec.PotentiallyDiagnosed->begin(),
9192 IEnd = Rec.PotentiallyDiagnosed->end();
9193 I != IEnd; ++I)
9194 Diag(I->first, I->second);
9195 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009196 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009197
9198 // When are coming out of an unevaluated context, clear out any
9199 // temporaries that we may have created as part of the evaluation of
9200 // the expression in that context: they aren't relevant because they
9201 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009202 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009203 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9204 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009205 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9206
9207 // Otherwise, merge the contexts together.
9208 } else {
9209 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9210 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009211
9212 // Destroy the popped expression evaluation record.
9213 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009214}
Douglas Gregore0762c92009-06-19 23:52:42 +00009215
John McCallf85e1932011-06-15 23:02:42 +00009216void Sema::DiscardCleanupsInEvaluationContext() {
9217 ExprTemporaries.erase(
9218 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9219 ExprTemporaries.end());
9220 ExprNeedsCleanups = false;
9221}
9222
Douglas Gregore0762c92009-06-19 23:52:42 +00009223/// \brief Note that the given declaration was referenced in the source code.
9224///
9225/// This routine should be invoke whenever a given declaration is referenced
9226/// in the source code, and where that reference occurred. If this declaration
9227/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9228/// C99 6.9p3), then the declaration will be marked as used.
9229///
9230/// \param Loc the location where the declaration was referenced.
9231///
9232/// \param D the declaration that has been referenced by the source code.
9233void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9234 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009235
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009236 D->setReferenced();
9237
Douglas Gregorc070cc62010-06-17 23:14:26 +00009238 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009240
Richard Trieu67e29332011-08-02 04:35:43 +00009241 // Mark a parameter or variable declaration "used", regardless of whether
9242 // we're in a template or not. The reason for this is that unevaluated
9243 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9244 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009245 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009246 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009247 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009248 return;
9249 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009250
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009251 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9252 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009253
Douglas Gregore0762c92009-06-19 23:52:42 +00009254 // Do not mark anything as "used" within a dependent context; wait for
9255 // an instantiation.
9256 if (CurContext->isDependentContext())
9257 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009258
Douglas Gregor2afce722009-11-26 00:44:06 +00009259 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009260 case Unevaluated:
9261 // We are in an expression that is not potentially evaluated; do nothing.
9262 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009263
Douglas Gregorac7610d2009-06-22 20:57:11 +00009264 case PotentiallyEvaluated:
9265 // We are in a potentially-evaluated expression, so this declaration is
9266 // "used"; handle this below.
9267 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009268
Douglas Gregorac7610d2009-06-22 20:57:11 +00009269 case PotentiallyPotentiallyEvaluated:
9270 // We are in an expression that may be potentially evaluated; queue this
9271 // declaration reference until we know whether the expression is
9272 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009273 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009274 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009275
9276 case PotentiallyEvaluatedIfUsed:
9277 // Referenced declarations will only be used if the construct in the
9278 // containing expression is used.
9279 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009280 }
Mike Stump1eb44332009-09-09 15:08:12 +00009281
Douglas Gregore0762c92009-06-19 23:52:42 +00009282 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009283 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009284 if (Constructor->isDefaulted()) {
9285 if (Constructor->isDefaultConstructor()) {
9286 if (Constructor->isTrivial())
9287 return;
9288 if (!Constructor->isUsed(false))
9289 DefineImplicitDefaultConstructor(Loc, Constructor);
9290 } else if (Constructor->isCopyConstructor()) {
9291 if (!Constructor->isUsed(false))
9292 DefineImplicitCopyConstructor(Loc, Constructor);
9293 } else if (Constructor->isMoveConstructor()) {
9294 if (!Constructor->isUsed(false))
9295 DefineImplicitMoveConstructor(Loc, Constructor);
9296 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009297 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009298
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009299 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009300 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009301 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009302 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009303 if (Destructor->isVirtual())
9304 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009305 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009306 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009307 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308 if (!MethodDecl->isUsed(false)) {
9309 if (MethodDecl->isCopyAssignmentOperator())
9310 DefineImplicitCopyAssignment(Loc, MethodDecl);
9311 else
9312 DefineImplicitMoveAssignment(Loc, MethodDecl);
9313 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009314 } else if (MethodDecl->isVirtual())
9315 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009316 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009317 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009318 // Recursive functions should be marked when used from another function.
9319 if (CurContext == Function) return;
9320
Mike Stump1eb44332009-09-09 15:08:12 +00009321 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009322 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009323 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009324 bool AlreadyInstantiated = false;
9325 if (FunctionTemplateSpecializationInfo *SpecInfo
9326 = Function->getTemplateSpecializationInfo()) {
9327 if (SpecInfo->getPointOfInstantiation().isInvalid())
9328 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009329 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009330 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009331 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009332 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009333 = Function->getMemberSpecializationInfo()) {
9334 if (MSInfo->getPointOfInstantiation().isInvalid())
9335 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009336 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009337 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009338 AlreadyInstantiated = true;
9339 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009340
Douglas Gregor60406be2010-01-16 22:29:39 +00009341 if (!AlreadyInstantiated) {
9342 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9343 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9344 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9345 Loc));
9346 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009347 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009348 }
John McCall15e310a2011-02-19 02:53:41 +00009349 } else {
9350 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009351 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9352 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009353 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009354 MarkDeclarationReferenced(Loc, *i);
9355 }
John McCall15e310a2011-02-19 02:53:41 +00009356 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009357
John McCall15e310a2011-02-19 02:53:41 +00009358 // Keep track of used but undefined functions.
9359 if (!Function->isPure() && !Function->hasBody() &&
9360 Function->getLinkage() != ExternalLinkage) {
9361 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9362 if (old.isInvalid()) old = Loc;
9363 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009364
John McCall15e310a2011-02-19 02:53:41 +00009365 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009366 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009367 }
Mike Stump1eb44332009-09-09 15:08:12 +00009368
Douglas Gregore0762c92009-06-19 23:52:42 +00009369 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009370 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009371 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009372 Var->getInstantiatedFromStaticDataMember()) {
9373 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9374 assert(MSInfo && "Missing member specialization information?");
9375 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9376 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9377 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009378 // This is a modification of an existing AST node. Notify listeners.
9379 if (ASTMutationListener *L = getASTMutationListener())
9380 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009381 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009382 }
9383 }
Mike Stump1eb44332009-09-09 15:08:12 +00009384
John McCall77efc682011-02-21 19:25:48 +00009385 // Keep track of used but undefined variables. We make a hole in
9386 // the warning for static const data members with in-line
9387 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009388 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009389 && Var->getLinkage() != ExternalLinkage
9390 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009391 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9392 if (old.isInvalid()) old = Loc;
9393 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009394
Douglas Gregore0762c92009-06-19 23:52:42 +00009395 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009396 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009397 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009398}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009399
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009400namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009401 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009402 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009403 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009404 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9405 Sema &S;
9406 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009407
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009408 public:
9409 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009410
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009411 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009412
9413 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9414 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009415 };
9416}
9417
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009418bool MarkReferencedDecls::TraverseTemplateArgument(
9419 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009420 if (Arg.getKind() == TemplateArgument::Declaration) {
9421 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9422 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009423
9424 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009425}
9426
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009427bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009428 if (ClassTemplateSpecializationDecl *Spec
9429 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9430 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009431 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009432 }
9433
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009434 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009435}
9436
9437void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9438 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009439 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009440}
9441
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009442namespace {
9443 /// \brief Helper class that marks all of the declarations referenced by
9444 /// potentially-evaluated subexpressions as "referenced".
9445 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9446 Sema &S;
9447
9448 public:
9449 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9450
9451 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9452
9453 void VisitDeclRefExpr(DeclRefExpr *E) {
9454 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9455 }
9456
9457 void VisitMemberExpr(MemberExpr *E) {
9458 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009459 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009460 }
9461
9462 void VisitCXXNewExpr(CXXNewExpr *E) {
9463 if (E->getConstructor())
9464 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9465 if (E->getOperatorNew())
9466 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9467 if (E->getOperatorDelete())
9468 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009469 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009470 }
9471
9472 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9473 if (E->getOperatorDelete())
9474 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009475 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9476 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9477 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9478 S.MarkDeclarationReferenced(E->getLocStart(),
9479 S.LookupDestructor(Record));
9480 }
9481
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009482 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009483 }
9484
9485 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9486 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009487 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009488 }
9489
9490 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9491 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9492 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009493
9494 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9495 Visit(E->getExpr());
9496 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009497 };
9498}
9499
9500/// \brief Mark any declarations that appear within this expression or any
9501/// potentially-evaluated subexpressions as "referenced".
9502void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9503 EvaluatedExprMarker(*this).Visit(E);
9504}
9505
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009506/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9507/// of the program being compiled.
9508///
9509/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009510/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009511/// possibility that the code will actually be executable. Code in sizeof()
9512/// expressions, code used only during overload resolution, etc., are not
9513/// potentially evaluated. This routine will suppress such diagnostics or,
9514/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009515/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009516/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009517///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009518/// This routine should be used for all diagnostics that describe the run-time
9519/// behavior of a program, such as passing a non-POD value through an ellipsis.
9520/// Failure to do so will likely result in spurious diagnostics or failures
9521/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009522bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009523 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009524 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009525 case Unevaluated:
9526 // The argument will never be evaluated, so don't complain.
9527 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009528
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009529 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009530 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009531 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009532 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009533 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009534 }
9535 else
9536 Diag(Loc, PD);
9537
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009538 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009539
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009540 case PotentiallyPotentiallyEvaluated:
9541 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9542 break;
9543 }
9544
9545 return false;
9546}
9547
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009548bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9549 CallExpr *CE, FunctionDecl *FD) {
9550 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9551 return false;
9552
9553 PartialDiagnostic Note =
9554 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9555 << FD->getDeclName() : PDiag();
9556 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009557
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009558 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009559 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009560 PDiag(diag::err_call_function_incomplete_return)
9561 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009562 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009563 << CE->getSourceRange(),
9564 std::make_pair(NoteLoc, Note)))
9565 return true;
9566
9567 return false;
9568}
9569
Douglas Gregor92c3a042011-01-19 16:50:08 +00009570// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009571// will prevent this condition from triggering, which is what we want.
9572void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9573 SourceLocation Loc;
9574
John McCalla52ef082009-11-11 02:41:58 +00009575 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009576 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009577
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009578 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009579 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009580 return;
9581
Douglas Gregor92c3a042011-01-19 16:50:08 +00009582 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9583
John McCallc8d8ac52009-11-12 00:06:05 +00009584 // Greylist some idioms by putting them into a warning subcategory.
9585 if (ObjCMessageExpr *ME
9586 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9587 Selector Sel = ME->getSelector();
9588
John McCallc8d8ac52009-11-12 00:06:05 +00009589 // self = [<foo> init...]
Fariborz Jahanian1d4e8e92011-09-17 19:23:40 +00009590 if (GetMethodIfSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009591 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9592
9593 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009594 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009595 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9596 }
John McCalla52ef082009-11-11 02:41:58 +00009597
John McCall5a881bb2009-10-12 21:59:07 +00009598 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009599 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009600 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009601 return;
9602
Douglas Gregor92c3a042011-01-19 16:50:08 +00009603 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009604 Loc = Op->getOperatorLoc();
9605 } else {
9606 // Not an assignment.
9607 return;
9608 }
9609
Douglas Gregor55b38842010-04-14 16:09:52 +00009610 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009611
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009612 SourceLocation Open = E->getSourceRange().getBegin();
9613 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9614 Diag(Loc, diag::note_condition_assign_silence)
9615 << FixItHint::CreateInsertion(Open, "(")
9616 << FixItHint::CreateInsertion(Close, ")");
9617
Douglas Gregor92c3a042011-01-19 16:50:08 +00009618 if (IsOrAssign)
9619 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9620 << FixItHint::CreateReplacement(Loc, "!=");
9621 else
9622 Diag(Loc, diag::note_condition_assign_to_comparison)
9623 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009624}
9625
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009626/// \brief Redundant parentheses over an equality comparison can indicate
9627/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009628void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009629 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009630 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009631 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9632 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009633 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009634 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009635 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009636
Richard Trieuccd891a2011-09-09 01:45:06 +00009637 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009638
9639 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009640 if (opE->getOpcode() == BO_EQ &&
9641 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9642 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009643 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009644
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009645 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009646 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009647 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9648 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009649 Diag(Loc, diag::note_equality_comparison_to_assign)
9650 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009651 }
9652}
9653
John Wiegley429bb272011-04-08 18:41:53 +00009654ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009655 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009656 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9657 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009658
John McCall864c0412011-04-26 20:42:42 +00009659 ExprResult result = CheckPlaceholderExpr(E);
9660 if (result.isInvalid()) return ExprError();
9661 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009662
John McCall864c0412011-04-26 20:42:42 +00009663 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009664 if (getLangOptions().CPlusPlus)
9665 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9666
John Wiegley429bb272011-04-08 18:41:53 +00009667 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9668 if (ERes.isInvalid())
9669 return ExprError();
9670 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009671
9672 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009673 if (!T->isScalarType()) { // C99 6.8.4.1p1
9674 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9675 << T << E->getSourceRange();
9676 return ExprError();
9677 }
John McCall5a881bb2009-10-12 21:59:07 +00009678 }
9679
John Wiegley429bb272011-04-08 18:41:53 +00009680 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009681}
Douglas Gregor586596f2010-05-06 17:25:47 +00009682
John McCall60d7b3a2010-08-24 06:29:42 +00009683ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009684 Expr *SubExpr) {
9685 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009686 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009687
Richard Trieuccd891a2011-09-09 01:45:06 +00009688 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009689}
John McCall2a984ca2010-10-12 00:20:44 +00009690
John McCall1de4d4e2011-04-07 08:22:57 +00009691namespace {
John McCall755d8492011-04-12 00:42:48 +00009692 /// A visitor for rebuilding a call to an __unknown_any expression
9693 /// to have an appropriate type.
9694 struct RebuildUnknownAnyFunction
9695 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9696
9697 Sema &S;
9698
9699 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9700
9701 ExprResult VisitStmt(Stmt *S) {
9702 llvm_unreachable("unexpected statement!");
9703 return ExprError();
9704 }
9705
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009706 ExprResult VisitExpr(Expr *E) {
9707 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9708 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009709 return ExprError();
9710 }
9711
9712 /// Rebuild an expression which simply semantically wraps another
9713 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009714 template <class T> ExprResult rebuildSugarExpr(T *E) {
9715 ExprResult SubResult = Visit(E->getSubExpr());
9716 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009717
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009718 Expr *SubExpr = SubResult.take();
9719 E->setSubExpr(SubExpr);
9720 E->setType(SubExpr->getType());
9721 E->setValueKind(SubExpr->getValueKind());
9722 assert(E->getObjectKind() == OK_Ordinary);
9723 return E;
John McCall755d8492011-04-12 00:42:48 +00009724 }
9725
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009726 ExprResult VisitParenExpr(ParenExpr *E) {
9727 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009728 }
9729
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009730 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9731 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009732 }
9733
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009734 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9735 ExprResult SubResult = Visit(E->getSubExpr());
9736 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009737
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009738 Expr *SubExpr = SubResult.take();
9739 E->setSubExpr(SubExpr);
9740 E->setType(S.Context.getPointerType(SubExpr->getType()));
9741 assert(E->getValueKind() == VK_RValue);
9742 assert(E->getObjectKind() == OK_Ordinary);
9743 return E;
John McCall755d8492011-04-12 00:42:48 +00009744 }
9745
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009746 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9747 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009748
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009749 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009750
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009751 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009752 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009753 !(isa<CXXMethodDecl>(VD) &&
9754 cast<CXXMethodDecl>(VD)->isInstance()))
9755 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009756
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009757 return E;
John McCall755d8492011-04-12 00:42:48 +00009758 }
9759
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009760 ExprResult VisitMemberExpr(MemberExpr *E) {
9761 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009762 }
9763
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009764 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9765 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009766 }
9767 };
9768}
9769
9770/// Given a function expression of unknown-any type, try to rebuild it
9771/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009772static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9773 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9774 if (Result.isInvalid()) return ExprError();
9775 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009776}
9777
9778namespace {
John McCall379b5152011-04-11 07:02:50 +00009779 /// A visitor for rebuilding an expression of type __unknown_anytype
9780 /// into one which resolves the type directly on the referring
9781 /// expression. Strict preservation of the original source
9782 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009783 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009784 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009785
9786 Sema &S;
9787
9788 /// The current destination type.
9789 QualType DestType;
9790
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009791 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9792 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009793
John McCalla5fc4722011-04-09 22:50:59 +00009794 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009795 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009796 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009797 }
9798
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009799 ExprResult VisitExpr(Expr *E) {
9800 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9801 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009802 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009803 }
9804
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009805 ExprResult VisitCallExpr(CallExpr *E);
9806 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009807
John McCalla5fc4722011-04-09 22:50:59 +00009808 /// Rebuild an expression which simply semantically wraps another
9809 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009810 template <class T> ExprResult rebuildSugarExpr(T *E) {
9811 ExprResult SubResult = Visit(E->getSubExpr());
9812 if (SubResult.isInvalid()) return ExprError();
9813 Expr *SubExpr = SubResult.take();
9814 E->setSubExpr(SubExpr);
9815 E->setType(SubExpr->getType());
9816 E->setValueKind(SubExpr->getValueKind());
9817 assert(E->getObjectKind() == OK_Ordinary);
9818 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009819 }
John McCall1de4d4e2011-04-07 08:22:57 +00009820
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009821 ExprResult VisitParenExpr(ParenExpr *E) {
9822 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009823 }
9824
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009825 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9826 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009827 }
9828
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009829 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9830 const PointerType *Ptr = DestType->getAs<PointerType>();
9831 if (!Ptr) {
9832 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9833 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009834 return ExprError();
9835 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009836 assert(E->getValueKind() == VK_RValue);
9837 assert(E->getObjectKind() == OK_Ordinary);
9838 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009839
9840 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009841 DestType = Ptr->getPointeeType();
9842 ExprResult SubResult = Visit(E->getSubExpr());
9843 if (SubResult.isInvalid()) return ExprError();
9844 E->setSubExpr(SubResult.take());
9845 return E;
John McCall755d8492011-04-12 00:42:48 +00009846 }
9847
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009848 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009849
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009850 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009851
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009852 ExprResult VisitMemberExpr(MemberExpr *E) {
9853 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009854 }
John McCalla5fc4722011-04-09 22:50:59 +00009855
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009856 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9857 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009858 }
9859 };
9860}
9861
John McCall379b5152011-04-11 07:02:50 +00009862/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009863ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9864 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009865
9866 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009867 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009868 FK_FunctionPointer,
9869 FK_BlockPointer
9870 };
9871
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009872 FnKind Kind;
9873 QualType CalleeType = CalleeExpr->getType();
9874 if (CalleeType == S.Context.BoundMemberTy) {
9875 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9876 Kind = FK_MemberFunction;
9877 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9878 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9879 CalleeType = Ptr->getPointeeType();
9880 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009881 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009882 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9883 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009884 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009885 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009886
9887 // Verify that this is a legal result type of a function.
9888 if (DestType->isArrayType() || DestType->isFunctionType()) {
9889 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009890 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009891 diagID = diag::err_block_returning_array_function;
9892
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009893 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009894 << DestType->isFunctionType() << DestType;
9895 return ExprError();
9896 }
9897
9898 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009899 E->setType(DestType.getNonLValueExprType(S.Context));
9900 E->setValueKind(Expr::getValueKindForType(DestType));
9901 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009902
9903 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009904 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009905 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009906 Proto->arg_type_begin(),
9907 Proto->getNumArgs(),
9908 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009909 else
9910 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009911 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009912
9913 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009914 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009915 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009916 // Nothing to do.
9917 break;
9918
9919 case FK_FunctionPointer:
9920 DestType = S.Context.getPointerType(DestType);
9921 break;
9922
9923 case FK_BlockPointer:
9924 DestType = S.Context.getBlockPointerType(DestType);
9925 break;
9926 }
9927
9928 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009929 ExprResult CalleeResult = Visit(CalleeExpr);
9930 if (!CalleeResult.isUsable()) return ExprError();
9931 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +00009932
9933 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009934 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009935}
9936
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009937ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009938 // Verify that this is a legal result type of a call.
9939 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009940 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +00009941 << DestType->isFunctionType() << DestType;
9942 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009943 }
9944
John McCall48218c62011-07-13 17:56:40 +00009945 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009946 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9947 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9948 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +00009949 }
John McCall755d8492011-04-12 00:42:48 +00009950
John McCall379b5152011-04-11 07:02:50 +00009951 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009952 E->setType(DestType.getNonReferenceType());
9953 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009954
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009955 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009956}
9957
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009958ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009959 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009960 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9961 assert(E->getValueKind() == VK_RValue);
9962 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009963
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009964 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009965
John McCall379b5152011-04-11 07:02:50 +00009966 // Rebuild the sub-expression as the pointee (function) type.
9967 DestType = DestType->castAs<PointerType>()->getPointeeType();
9968
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009969 ExprResult Result = Visit(E->getSubExpr());
9970 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009971
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009972 E->setSubExpr(Result.take());
9973 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +00009974}
9975
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009976ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9977 ExprValueKind ValueKind = VK_LValue;
9978 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +00009979
9980 // We know how to make this work for certain kinds of decls:
9981
9982 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009983 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9984 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9985 DestType = Ptr->getPointeeType();
9986 ExprResult Result = resolveDecl(E, VD);
9987 if (Result.isInvalid()) return ExprError();
9988 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +00009989 CK_FunctionToPointerDecay, VK_RValue);
9990 }
9991
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009992 if (!Type->isFunctionType()) {
9993 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
9994 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +00009995 return ExprError();
9996 }
John McCall379b5152011-04-11 07:02:50 +00009997
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009998 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
9999 if (MD->isInstance()) {
10000 ValueKind = VK_RValue;
10001 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000010002 }
10003
John McCall379b5152011-04-11 07:02:50 +000010004 // Function references aren't l-values in C.
10005 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010006 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000010007
10008 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010009 } else if (isa<VarDecl>(VD)) {
10010 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10011 Type = RefTy->getPointeeType();
10012 } else if (Type->isFunctionType()) {
10013 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10014 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000010015 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010016 }
10017
10018 // - nothing else
10019 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010020 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10021 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010022 return ExprError();
10023 }
10024
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010025 VD->setType(DestType);
10026 E->setType(Type);
10027 E->setValueKind(ValueKind);
10028 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010029}
10030
John McCall1de4d4e2011-04-07 08:22:57 +000010031/// Check a cast of an unknown-any type. We intentionally only
10032/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000010033ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10034 Expr *CastExpr, CastKind &CastKind,
10035 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010036 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010037 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010038 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010039
Richard Trieuccd891a2011-09-09 01:45:06 +000010040 CastExpr = result.take();
10041 VK = CastExpr->getValueKind();
10042 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010043
Richard Trieuccd891a2011-09-09 01:45:06 +000010044 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010045}
10046
Richard Trieuccd891a2011-09-09 01:45:06 +000010047static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10048 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010049 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010050 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010051 E = E->IgnoreParenImpCasts();
10052 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10053 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010054 diagID = diag::err_uncasted_call_of_unknown_any;
10055 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010056 break;
John McCall379b5152011-04-11 07:02:50 +000010057 }
John McCall1de4d4e2011-04-07 08:22:57 +000010058 }
10059
John McCall379b5152011-04-11 07:02:50 +000010060 SourceLocation loc;
10061 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010062 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010063 loc = ref->getLocation();
10064 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010065 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010066 loc = mem->getMemberLoc();
10067 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010068 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010069 diagID = diag::err_uncasted_call_of_unknown_any;
10070 loc = msg->getSelectorLoc();
10071 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010072 if (!d) {
10073 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10074 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10075 << orig->getSourceRange();
10076 return ExprError();
10077 }
John McCall379b5152011-04-11 07:02:50 +000010078 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010079 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10080 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010081 return ExprError();
10082 }
10083
10084 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010085
10086 // Never recoverable.
10087 return ExprError();
10088}
10089
John McCall2a984ca2010-10-12 00:20:44 +000010090/// Check for operands with placeholder types and complain if found.
10091/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010092ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010093 // Placeholder types are always *exactly* the appropriate builtin type.
10094 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010095
John McCall1de4d4e2011-04-07 08:22:57 +000010096 // Overloaded expressions.
10097 if (type == Context.OverloadTy)
10098 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010099 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010100 QualType(),
10101 diag::err_ovl_unresolvable);
10102
John McCall864c0412011-04-26 20:42:42 +000010103 // Bound member functions.
10104 if (type == Context.BoundMemberTy) {
10105 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10106 << E->getSourceRange();
10107 return ExprError();
10108 }
10109
John McCall1de4d4e2011-04-07 08:22:57 +000010110 // Expressions of unknown type.
10111 if (type == Context.UnknownAnyTy)
10112 return diagnoseUnknownAnyExpr(*this, E);
10113
10114 assert(!type->isPlaceholderType());
10115 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010116}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010117
Richard Trieuccd891a2011-09-09 01:45:06 +000010118bool Sema::CheckCaseExpression(Expr *E) {
10119 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010120 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010121 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10122 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010123 return false;
10124}