blob: 7721caf939746609a45ea41135ff7c1d33a240b5 [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
Sebastian Redl14b0c192011-09-24 17:48:00 +000044/// \brief Determine whether the use of this declaration is valid, without
45/// emitting diagnostics.
46bool Sema::CanUseDecl(NamedDecl *D) {
47 // See if this is an auto-typed variable whose initializer we are parsing.
48 if (ParsingInitForAutoVars.count(D))
49 return false;
50
51 // See if this is a deleted function.
52 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53 if (FD->isDeleted())
54 return false;
55 }
56 return true;
57}
David Chisnall0f436562009-08-17 16:35:33 +000058
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000059static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
60 NamedDecl *D, SourceLocation Loc,
61 const ObjCInterfaceDecl *UnknownObjCClass) {
62 // See if this declaration is unavailable or deprecated.
63 std::string Message;
64 AvailabilityResult Result = D->getAvailability(&Message);
65 switch (Result) {
66 case AR_Available:
67 case AR_NotYetIntroduced:
68 break;
69
70 case AR_Deprecated:
71 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
72 break;
73
74 case AR_Unavailable:
75 if (cast<Decl>(S.CurContext)->getAvailability() != AR_Unavailable) {
76 if (Message.empty()) {
77 if (!UnknownObjCClass)
78 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
79 else
80 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
81 << D->getDeclName();
82 }
83 else
84 S.Diag(Loc, diag::err_unavailable_message)
85 << D->getDeclName() << Message;
86 S.Diag(D->getLocation(), diag::note_unavailable_here)
87 << isa<FunctionDecl>(D) << false;
88 }
89 break;
90 }
91 return Result;
92}
93
Douglas Gregor48f3bb92009-02-18 21:56:37 +000094/// \brief Determine whether the use of this declaration is valid, and
95/// emit any corresponding diagnostics.
96///
97/// This routine diagnoses various problems with referencing
98/// declarations that can occur when using a declaration. For example,
99/// it might warn if a deprecated or unavailable declaration is being
100/// used, or produce an error (and return true) if a C++0x deleted
101/// function is being used.
102///
103/// \returns true if there was an error (this declaration cannot be
104/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000105///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000106bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000107 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000108 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
109 // If there were any diagnostics suppressed by template argument deduction,
110 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000111 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000112 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
113 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000115 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
116 Diag(Suppressed[I].first, Suppressed[I].second);
117
118 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000119 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000120 // entry from the table, because we want to avoid ever emitting these
121 // diagnostics again.
122 Suppressed.clear();
123 }
124 }
125
Richard Smith34b41d92011-02-20 03:19:35 +0000126 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000127 if (ParsingInitForAutoVars.count(D)) {
128 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
129 << D->getDeclName();
130 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000131 }
132
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000133 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000135 if (FD->isDeleted()) {
136 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +0000137 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000138 return true;
139 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000140 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000141 AvailabilityResult Result =
142 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000143
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000144 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000145 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000146 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000147 // For available enumerator, it will become unavailable/deprecated
148 // if its enum declaration is as such.
149 if (Result == AR_Available)
150 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
151 const DeclContext *DC = ECD->getDeclContext();
152 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000153 DiagnoseAvailabilityOfDecl(*this,
154 const_cast< EnumDecl *>(TheEnumDecl),
155 Loc, UnknownObjCClass);
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000156 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000157 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000158}
159
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000160/// \brief Retrieve the message suffix that should be added to a
161/// diagnostic complaining about the given function being deleted or
162/// unavailable.
163std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
164 // FIXME: C++0x implicitly-deleted special member functions could be
165 // detected here so that we could improve diagnostics to say, e.g.,
166 // "base class 'A' had a deleted copy constructor".
167 if (FD->isDeleted())
168 return std::string();
169
170 std::string Message;
171 if (FD->getAvailability(&Message))
172 return ": " + Message;
173
174 return std::string();
175}
176
John McCall3323fad2011-09-09 07:56:05 +0000177/// DiagnoseSentinelCalls - This routine checks whether a call or
178/// message-send is to a declaration with the sentinel attribute, and
179/// if so, it checks that the requirements of the sentinel are
180/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000181void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000182 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000183 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000184 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000185 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000186
John McCall3323fad2011-09-09 07:56:05 +0000187 // The number of formal parameters of the declaration.
188 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000189
John McCall3323fad2011-09-09 07:56:05 +0000190 // The kind of declaration. This is also an index into a %select in
191 // the diagnostic.
192 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
193
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000194 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000195 numFormalParams = MD->param_size();
196 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000197 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000198 numFormalParams = FD->param_size();
199 calleeType = CT_Function;
200 } else if (isa<VarDecl>(D)) {
201 QualType type = cast<ValueDecl>(D)->getType();
202 const FunctionType *fn = 0;
203 if (const PointerType *ptr = type->getAs<PointerType>()) {
204 fn = ptr->getPointeeType()->getAs<FunctionType>();
205 if (!fn) return;
206 calleeType = CT_Function;
207 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
208 fn = ptr->getPointeeType()->castAs<FunctionType>();
209 calleeType = CT_Block;
210 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000211 return;
John McCall3323fad2011-09-09 07:56:05 +0000212 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213
John McCall3323fad2011-09-09 07:56:05 +0000214 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
215 numFormalParams = proto->getNumArgs();
216 } else {
217 numFormalParams = 0;
218 }
219 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000220 return;
221 }
John McCall3323fad2011-09-09 07:56:05 +0000222
223 // "nullPos" is the number of formal parameters at the end which
224 // effectively count as part of the variadic arguments. This is
225 // useful if you would prefer to not have *any* formal parameters,
226 // but the language forces you to have at least one.
227 unsigned nullPos = attr->getNullPos();
228 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
229 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
230
231 // The number of arguments which should follow the sentinel.
232 unsigned numArgsAfterSentinel = attr->getSentinel();
233
234 // If there aren't enough arguments for all the formal parameters,
235 // the sentinel, and the args after the sentinel, complain.
236 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000237 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000238 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000239 return;
240 }
John McCall3323fad2011-09-09 07:56:05 +0000241
242 // Otherwise, find the sentinel expression.
243 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000244 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000245 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000246
247 // nullptr_t is always treated as null.
248 if (sentinelExpr->getType()->isNullPtrType()) return;
249
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000250 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000251 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
252 Expr::NPC_ValueDependentIsNull))
253 return;
254
255 // Unfortunately, __null has type 'int'.
256 if (isa<GNUNullExpr>(sentinelExpr)) return;
257
John McCall3323fad2011-09-09 07:56:05 +0000258 // Pick a reasonable string to insert. Optimistically use 'nil' or
259 // 'NULL' if those are actually defined in the context. Only use
260 // 'nil' for ObjC methods, where it's much more likely that the
261 // variadic arguments form a list of object pointers.
262 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000263 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
264 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000265 if (calleeType == CT_Method &&
266 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000267 NullValue = "nil";
268 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
269 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000270 else
John McCall3323fad2011-09-09 07:56:05 +0000271 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000272
273 if (MissingNilLoc.isInvalid())
274 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
275 else
276 Diag(MissingNilLoc, diag::warn_missing_sentinel)
277 << calleeType
278 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000279 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000280}
281
Richard Trieuccd891a2011-09-09 01:45:06 +0000282SourceRange Sema::getExprRange(Expr *E) const {
283 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000284}
285
Chris Lattnere7a2e912008-07-25 21:10:04 +0000286//===----------------------------------------------------------------------===//
287// Standard Promotions and Conversions
288//===----------------------------------------------------------------------===//
289
Chris Lattnere7a2e912008-07-25 21:10:04 +0000290/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000291ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000292 QualType Ty = E->getType();
293 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
294
Chris Lattnere7a2e912008-07-25 21:10:04 +0000295 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000296 E = ImpCastExprToType(E, Context.getPointerType(Ty),
297 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000298 else if (Ty->isArrayType()) {
299 // In C90 mode, arrays only promote to pointers if the array expression is
300 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
301 // type 'array of type' is converted to an expression that has type 'pointer
302 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
303 // that has type 'array of type' ...". The relevant change is "an lvalue"
304 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000305 //
306 // C++ 4.2p1:
307 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
308 // T" can be converted to an rvalue of type "pointer to T".
309 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000310 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000311 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
312 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000313 }
John Wiegley429bb272011-04-08 18:41:53 +0000314 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000315}
316
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000317static void CheckForNullPointerDereference(Sema &S, Expr *E) {
318 // Check to see if we are dereferencing a null pointer. If so,
319 // and if not volatile-qualified, this is undefined behavior that the
320 // optimizer will delete, so warn about it. People sometimes try to use this
321 // to get a deterministic trap and are surprised by clang's behavior. This
322 // only handles the pattern "*null", which is a very syntactic check.
323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
324 if (UO->getOpcode() == UO_Deref &&
325 UO->getSubExpr()->IgnoreParenCasts()->
326 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
327 !UO->getType().isVolatileQualified()) {
328 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
329 S.PDiag(diag::warn_indirection_through_null)
330 << UO->getSubExpr()->getSourceRange());
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::note_indirection_through_null));
333 }
334}
335
John Wiegley429bb272011-04-08 18:41:53 +0000336ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000337 // C++ [conv.lval]p1:
338 // A glvalue of a non-function, non-array type T can be
339 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000340 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000341
John McCall409fa9a2010-12-06 20:48:59 +0000342 QualType T = E->getType();
343 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000344
John McCall409fa9a2010-12-06 20:48:59 +0000345 // Create a load out of an ObjCProperty l-value, if necessary.
346 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000347 ExprResult Res = ConvertPropertyForRValue(E);
348 if (Res.isInvalid())
349 return Owned(E);
350 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000351 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000352 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000353 }
John McCall409fa9a2010-12-06 20:48:59 +0000354
355 // We don't want to throw lvalue-to-rvalue casts on top of
356 // expressions of certain types in C++.
357 if (getLangOptions().CPlusPlus &&
358 (E->getType() == Context.OverloadTy ||
359 T->isDependentType() ||
360 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000361 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000362
363 // The C standard is actually really unclear on this point, and
364 // DR106 tells us what the result should be but not why. It's
365 // generally best to say that void types just doesn't undergo
366 // lvalue-to-rvalue at all. Note that expressions of unqualified
367 // 'void' type are never l-values, but qualified void can be.
368 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000369 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000370
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000371 CheckForNullPointerDereference(*this, E);
372
John McCall409fa9a2010-12-06 20:48:59 +0000373 // C++ [conv.lval]p1:
374 // [...] If T is a non-class type, the type of the prvalue is the
375 // cv-unqualified version of T. Otherwise, the type of the
376 // rvalue is T.
377 //
378 // C99 6.3.2.1p2:
379 // If the lvalue has qualified type, the value has the unqualified
380 // version of the type of the lvalue; otherwise, the value has the
381 // type of the lvalue.
382 if (T.hasQualifiers())
383 T = T.getUnqualifiedType();
Ted Kremeneka0125d82011-02-16 01:57:07 +0000384
John Wiegley429bb272011-04-08 18:41:53 +0000385 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
386 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000387}
388
John Wiegley429bb272011-04-08 18:41:53 +0000389ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
390 ExprResult Res = DefaultFunctionArrayConversion(E);
391 if (Res.isInvalid())
392 return ExprError();
393 Res = DefaultLvalueConversion(Res.take());
394 if (Res.isInvalid())
395 return ExprError();
396 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000397}
398
399
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000401/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000402/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403/// apply if the array is an argument to the sizeof or address (&) operators.
404/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000405ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000406 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000407 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
408 if (Res.isInvalid())
409 return Owned(E);
410 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000411
412 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000413 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000414
415 // Try to perform integral promotions if the object has a theoretically
416 // promotable type.
417 if (Ty->isIntegralOrUnscopedEnumerationType()) {
418 // C99 6.3.1.1p2:
419 //
420 // The following may be used in an expression wherever an int or
421 // unsigned int may be used:
422 // - an object or expression with an integer type whose integer
423 // conversion rank is less than or equal to the rank of int
424 // and unsigned int.
425 // - A bit-field of type _Bool, int, signed int, or unsigned int.
426 //
427 // If an int can represent all values of the original type, the
428 // value is converted to an int; otherwise, it is converted to an
429 // unsigned int. These are called the integer promotions. All
430 // other types are unchanged by the integer promotions.
431
432 QualType PTy = Context.isPromotableBitField(E);
433 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
435 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000436 }
437 if (Ty->isPromotableIntegerType()) {
438 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000439 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
440 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000441 }
Eli Friedman04e83572009-08-20 04:21:42 +0000442 }
John Wiegley429bb272011-04-08 18:41:53 +0000443 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000444}
445
Chris Lattner05faf172008-07-25 22:25:12 +0000446/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000447/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000448/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000449ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
450 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000451 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000452
John Wiegley429bb272011-04-08 18:41:53 +0000453 ExprResult Res = UsualUnaryConversions(E);
454 if (Res.isInvalid())
455 return Owned(E);
456 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000457
Chris Lattner05faf172008-07-25 22:25:12 +0000458 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000459 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000460 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
461
John McCall96a914a2011-08-27 22:06:17 +0000462 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000463 // promotion, even on class types, but note:
464 // C++11 [conv.lval]p2:
465 // When an lvalue-to-rvalue conversion occurs in an unevaluated
466 // operand or a subexpression thereof the value contained in the
467 // referenced object is not accessed. Otherwise, if the glvalue
468 // has a class type, the conversion copy-initializes a temporary
469 // of type T from the glvalue and the result of the conversion
470 // is a prvalue for the temporary.
471 // FIXME: add some way to gate this entire thing for correctness in
472 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000473 if (getLangOptions().CPlusPlus && E->isGLValue() &&
474 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000475 ExprResult Temp = PerformCopyInitialization(
476 InitializedEntity::InitializeTemporary(E->getType()),
477 E->getExprLoc(),
478 Owned(E));
479 if (Temp.isInvalid())
480 return ExprError();
481 E = Temp.get();
482 }
483
John Wiegley429bb272011-04-08 18:41:53 +0000484 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000485}
486
Chris Lattner312531a2009-04-12 08:11:20 +0000487/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
488/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000489/// interfaces passed by value.
490ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000491 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000492 ExprResult ExprRes = CheckPlaceholderExpr(E);
493 if (ExprRes.isInvalid())
494 return ExprError();
495
496 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000497 if (ExprRes.isInvalid())
498 return ExprError();
499 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000501 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000502 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000503 DiagRuntimeBehavior(E->getLocStart(), 0,
504 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
505 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000506 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000507
John McCallf85e1932011-06-15 23:02:42 +0000508 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000509 // C++0x [expr.call]p7:
510 // Passing a potentially-evaluated argument of class type (Clause 9)
511 // having a non-trivial copy constructor, a non-trivial move constructor,
512 // or a non-trivial destructor, with no corresponding parameter,
513 // is conditionally-supported with implementation-defined semantics.
514 bool TrivialEnough = false;
515 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
516 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
517 if (Record->hasTrivialCopyConstructor() &&
518 Record->hasTrivialMoveConstructor() &&
519 Record->hasTrivialDestructor())
520 TrivialEnough = true;
521 }
522 }
John McCallf85e1932011-06-15 23:02:42 +0000523
524 if (!TrivialEnough &&
525 getLangOptions().ObjCAutoRefCount &&
526 E->getType()->isObjCLifetimeType())
527 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000528
529 if (TrivialEnough) {
530 // Nothing to diagnose. This is okay.
531 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000532 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000533 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000534 << CT)) {
535 // Turn this into a trap.
536 CXXScopeSpec SS;
537 UnqualifiedId Name;
538 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
539 E->getLocStart());
540 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
541 if (TrapFn.isInvalid())
542 return ExprError();
543
544 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
545 MultiExprArg(), E->getLocEnd());
546 if (Call.isInvalid())
547 return ExprError();
548
549 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
550 Call.get(), E);
551 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000552 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000553 E = Comma.get();
554 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000555 }
556
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000558}
559
Richard Trieu8289f492011-09-02 20:58:51 +0000560/// \brief Converts an integer to complex float type. Helper function of
561/// UsualArithmeticConversions()
562///
563/// \return false if the integer expression is an integer type and is
564/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000565static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
566 ExprResult &ComplexExpr,
567 QualType IntTy,
568 QualType ComplexTy,
569 bool SkipCast) {
570 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
571 if (SkipCast) return false;
572 if (IntTy->isIntegerType()) {
573 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
574 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
575 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000576 CK_FloatingRealToComplex);
577 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000578 assert(IntTy->isComplexIntegerType());
579 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000580 CK_IntegralComplexToFloatingComplex);
581 }
582 return false;
583}
584
585/// \brief Takes two complex float types and converts them to the same type.
586/// Helper function of UsualArithmeticConversions()
587static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000588handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
589 ExprResult &RHS, QualType LHSType,
590 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000591 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000592 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000593
594 if (order < 0) {
595 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000596 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000597 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
598 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000599 }
600 if (order > 0)
601 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000602 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
603 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000604}
605
606/// \brief Converts otherExpr to complex float and promotes complexExpr if
607/// necessary. Helper function of UsualArithmeticConversions()
608static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000609 ExprResult &ComplexExpr,
610 ExprResult &OtherExpr,
611 QualType ComplexTy,
612 QualType OtherTy,
613 bool ConvertComplexExpr,
614 bool ConvertOtherExpr) {
615 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000616
617 // If just the complexExpr is complex, the otherExpr needs to be converted,
618 // and the complexExpr might need to be promoted.
619 if (order > 0) { // complexExpr is wider
620 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000621 if (ConvertOtherExpr) {
622 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
623 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
624 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000625 CK_FloatingRealToComplex);
626 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000627 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000628 }
629
630 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000631 QualType result = (order == 0 ? ComplexTy :
632 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000633
634 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000635 if (ConvertOtherExpr)
636 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000637 CK_FloatingRealToComplex);
638
639 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000640 if (ConvertComplexExpr && order < 0)
641 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000642 CK_FloatingComplexCast);
643
644 return result;
645}
646
647/// \brief Handle arithmetic conversion with complex types. Helper function of
648/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000649static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
650 ExprResult &RHS, QualType LHSType,
651 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000652 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000653 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000654 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000655 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000656 return LHSType;
657 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000658 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000659 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000660
661 // This handles complex/complex, complex/float, or float/complex.
662 // When both operands are complex, the shorter operand is converted to the
663 // type of the longer, and that is the type of the result. This corresponds
664 // to what is done when combining two real floating-point operands.
665 // The fun begins when size promotion occur across type domains.
666 // From H&S 6.3.4: When one operand is complex and the other is a real
667 // floating-point type, the less precise type is converted, within it's
668 // real or complex domain, to the precision of the other type. For example,
669 // when combining a "long double" with a "double _Complex", the
670 // "double _Complex" is promoted to "long double _Complex".
671
Richard Trieucafd30b2011-09-06 18:25:09 +0000672 bool LHSComplexFloat = LHSType->isComplexType();
673 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000674
675 // If both are complex, just cast to the more precise type.
676 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000677 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
678 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000679 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000680
681 // If only one operand is complex, promote it if necessary and convert the
682 // other operand to complex.
683 if (LHSComplexFloat)
684 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000685 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000686 /*convertOtherExpr*/ true);
687
688 assert(RHSComplexFloat);
689 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000690 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000691 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000692}
693
694/// \brief Hande arithmetic conversion from integer to float. Helper function
695/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000696static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
697 ExprResult &IntExpr,
698 QualType FloatTy, QualType IntTy,
699 bool ConvertFloat, bool ConvertInt) {
700 if (IntTy->isIntegerType()) {
701 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000702 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000703 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000704 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000705 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000706 }
707
708 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000709 assert(IntTy->isComplexIntegerType());
710 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000711
712 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000713 if (ConvertInt)
714 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000715 CK_IntegralComplexToFloatingComplex);
716
717 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000718 if (ConvertFloat)
719 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000720 CK_FloatingRealToComplex);
721
722 return result;
723}
724
725/// \brief Handle arithmethic conversion with floating point types. Helper
726/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000727static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
728 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000729 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000730 bool LHSFloat = LHSType->isRealFloatingType();
731 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000732
733 // If we have two real floating types, convert the smaller operand
734 // to the bigger result.
735 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000736 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000737 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000738 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
739 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000740 }
741
742 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000743 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000744 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
745 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000746 }
747
748 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000749 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000750 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000751 /*convertInt=*/ true);
752 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000753 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000754 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000755 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000756}
757
758/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000759/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000760// FIXME: if the operands are (int, _Complex long), we currently
761// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000762static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
763 ExprResult &RHS, QualType LHSType,
764 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000765 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000766 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
767 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000768
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000769 if (LHSComplexInt && RHSComplexInt) {
770 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
771 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000772 assert(order && "inequal types with equal element ordering");
773 if (order > 0) {
774 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000775 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
776 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000777 }
778
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000784 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000785 // int -> _Complex int
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000786 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
787 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000788 }
789
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000790 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000791 // int -> _Complex int
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000793 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
794 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000795}
796
797/// \brief Handle integer arithmetic conversions. Helper function of
798/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000799static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
800 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000801 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000802 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000803 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
804 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
805 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
806 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000807 // Same signedness; use the higher-ranked type
808 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000809 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
810 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000811 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000812 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
813 return RHSType;
814 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000815 // The unsigned type has greater than or equal rank to the
816 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000817 if (RHSSigned) {
818 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
819 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000820 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000821 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
822 return RHSType;
823 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000824 // The two types are different widths; if we are here, that
825 // means the signed type is larger than the unsigned type, so
826 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000827 if (LHSSigned) {
828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
829 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000830 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000831 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
832 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000833 } else {
834 // The signed type is higher-ranked than the unsigned type,
835 // but isn't actually any bigger (like unsigned int and long
836 // on most 32-bit systems). Use the unsigned type corresponding
837 // to the signed type.
838 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000839 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
840 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000841 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000842 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000843 return result;
844 }
845}
846
Chris Lattnere7a2e912008-07-25 21:10:04 +0000847/// UsualArithmeticConversions - Performs various conversions that are common to
848/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000849/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000850/// responsible for emitting appropriate error diagnostics.
851/// FIXME: verify the conversion rules for "complex int" are consistent with
852/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000853QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000854 bool IsCompAssign) {
855 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000856 LHS = UsualUnaryConversions(LHS.take());
857 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000858 return QualType();
859 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000860
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000861 RHS = UsualUnaryConversions(RHS.take());
862 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000863 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000864
Mike Stump1eb44332009-09-09 15:08:12 +0000865 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000866 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000867 QualType LHSType =
868 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
869 QualType RHSType =
870 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000871
872 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000873 if (LHSType == RHSType)
874 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000875
876 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
877 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000878 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
879 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000880
John McCallcf33b242010-11-13 08:17:45 +0000881 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000882 QualType LHSUnpromotedType = LHSType;
883 if (LHSType->isPromotableIntegerType())
884 LHSType = Context.getPromotedIntegerType(LHSType);
885 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000886 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000887 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000889 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000890
John McCallcf33b242010-11-13 08:17:45 +0000891 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000892 if (LHSType == RHSType)
893 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000894
895 // At this point, we have two different arithmetic types.
896
897 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000898 if (LHSType->isComplexType() || RHSType->isComplexType())
899 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000900 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000901
902 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000903 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
904 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000905 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000906
907 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000908 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000909 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000910 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000911
912 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000913 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000914 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000915}
916
Chris Lattnere7a2e912008-07-25 21:10:04 +0000917//===----------------------------------------------------------------------===//
918// Semantic Analysis for various Expression Types
919//===----------------------------------------------------------------------===//
920
921
Peter Collingbournef111d932011-04-15 00:35:48 +0000922ExprResult
923Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
924 SourceLocation DefaultLoc,
925 SourceLocation RParenLoc,
926 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000927 MultiTypeArg ArgTypes,
928 MultiExprArg ArgExprs) {
929 unsigned NumAssocs = ArgTypes.size();
930 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000931
Richard Trieuccd891a2011-09-09 01:45:06 +0000932 ParsedType *ParsedTypes = ArgTypes.release();
933 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000934
935 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
936 for (unsigned i = 0; i < NumAssocs; ++i) {
937 if (ParsedTypes[i])
938 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
939 else
940 Types[i] = 0;
941 }
942
943 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
944 ControllingExpr, Types, Exprs,
945 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000946 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000947 return ER;
948}
949
950ExprResult
951Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
952 SourceLocation DefaultLoc,
953 SourceLocation RParenLoc,
954 Expr *ControllingExpr,
955 TypeSourceInfo **Types,
956 Expr **Exprs,
957 unsigned NumAssocs) {
958 bool TypeErrorFound = false,
959 IsResultDependent = ControllingExpr->isTypeDependent(),
960 ContainsUnexpandedParameterPack
961 = ControllingExpr->containsUnexpandedParameterPack();
962
963 for (unsigned i = 0; i < NumAssocs; ++i) {
964 if (Exprs[i]->containsUnexpandedParameterPack())
965 ContainsUnexpandedParameterPack = true;
966
967 if (Types[i]) {
968 if (Types[i]->getType()->containsUnexpandedParameterPack())
969 ContainsUnexpandedParameterPack = true;
970
971 if (Types[i]->getType()->isDependentType()) {
972 IsResultDependent = true;
973 } else {
974 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
975 // complete object type other than a variably modified type."
976 unsigned D = 0;
977 if (Types[i]->getType()->isIncompleteType())
978 D = diag::err_assoc_type_incomplete;
979 else if (!Types[i]->getType()->isObjectType())
980 D = diag::err_assoc_type_nonobject;
981 else if (Types[i]->getType()->isVariablyModifiedType())
982 D = diag::err_assoc_type_variably_modified;
983
984 if (D != 0) {
985 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
986 << Types[i]->getTypeLoc().getSourceRange()
987 << Types[i]->getType();
988 TypeErrorFound = true;
989 }
990
991 // C1X 6.5.1.1p2 "No two generic associations in the same generic
992 // selection shall specify compatible types."
993 for (unsigned j = i+1; j < NumAssocs; ++j)
994 if (Types[j] && !Types[j]->getType()->isDependentType() &&
995 Context.typesAreCompatible(Types[i]->getType(),
996 Types[j]->getType())) {
997 Diag(Types[j]->getTypeLoc().getBeginLoc(),
998 diag::err_assoc_compatible_types)
999 << Types[j]->getTypeLoc().getSourceRange()
1000 << Types[j]->getType()
1001 << Types[i]->getType();
1002 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1003 diag::note_compat_assoc)
1004 << Types[i]->getTypeLoc().getSourceRange()
1005 << Types[i]->getType();
1006 TypeErrorFound = true;
1007 }
1008 }
1009 }
1010 }
1011 if (TypeErrorFound)
1012 return ExprError();
1013
1014 // If we determined that the generic selection is result-dependent, don't
1015 // try to compute the result expression.
1016 if (IsResultDependent)
1017 return Owned(new (Context) GenericSelectionExpr(
1018 Context, KeyLoc, ControllingExpr,
1019 Types, Exprs, NumAssocs, DefaultLoc,
1020 RParenLoc, ContainsUnexpandedParameterPack));
1021
Chris Lattner5f9e2722011-07-23 10:55:15 +00001022 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001023 unsigned DefaultIndex = -1U;
1024 for (unsigned i = 0; i < NumAssocs; ++i) {
1025 if (!Types[i])
1026 DefaultIndex = i;
1027 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1028 Types[i]->getType()))
1029 CompatIndices.push_back(i);
1030 }
1031
1032 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1033 // type compatible with at most one of the types named in its generic
1034 // association list."
1035 if (CompatIndices.size() > 1) {
1036 // We strip parens here because the controlling expression is typically
1037 // parenthesized in macro definitions.
1038 ControllingExpr = ControllingExpr->IgnoreParens();
1039 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1040 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1041 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001042 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001043 E = CompatIndices.end(); I != E; ++I) {
1044 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1045 diag::note_compat_assoc)
1046 << Types[*I]->getTypeLoc().getSourceRange()
1047 << Types[*I]->getType();
1048 }
1049 return ExprError();
1050 }
1051
1052 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1053 // its controlling expression shall have type compatible with exactly one of
1054 // the types named in its generic association list."
1055 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1056 // We strip parens here because the controlling expression is typically
1057 // parenthesized in macro definitions.
1058 ControllingExpr = ControllingExpr->IgnoreParens();
1059 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1060 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1061 return ExprError();
1062 }
1063
1064 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1065 // type name that is compatible with the type of the controlling expression,
1066 // then the result expression of the generic selection is the expression
1067 // in that generic association. Otherwise, the result expression of the
1068 // generic selection is the expression in the default generic association."
1069 unsigned ResultIndex =
1070 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1071
1072 return Owned(new (Context) GenericSelectionExpr(
1073 Context, KeyLoc, ControllingExpr,
1074 Types, Exprs, NumAssocs, DefaultLoc,
1075 RParenLoc, ContainsUnexpandedParameterPack,
1076 ResultIndex));
1077}
1078
Steve Narofff69936d2007-09-16 03:34:24 +00001079/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001080/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1081/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1082/// multiple tokens. However, the common case is that StringToks points to one
1083/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001084///
John McCall60d7b3a2010-08-24 06:29:42 +00001085ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001086Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 assert(NumStringToks && "Must have at least one string!");
1088
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001089 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001091 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001092
Chris Lattner5f9e2722011-07-23 10:55:15 +00001093 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 for (unsigned i = 0; i != NumStringToks; ++i)
1095 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001096
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001097 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001098 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001099 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001100 else if (Literal.isUTF16())
1101 StrTy = Context.Char16Ty;
1102 else if (Literal.isUTF32())
1103 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001104 else if (Literal.Pascal)
1105 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001106
Douglas Gregor5cee1192011-07-27 05:40:30 +00001107 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1108 if (Literal.isWide())
1109 Kind = StringLiteral::Wide;
1110 else if (Literal.isUTF8())
1111 Kind = StringLiteral::UTF8;
1112 else if (Literal.isUTF16())
1113 Kind = StringLiteral::UTF16;
1114 else if (Literal.isUTF32())
1115 Kind = StringLiteral::UTF32;
1116
Douglas Gregor77a52232008-09-12 00:47:35 +00001117 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001118 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001119 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001120
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001121 // Get an array type for the string, according to C99 6.4.5. This includes
1122 // the nul terminator character as well as the string length for pascal
1123 // strings.
1124 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001125 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001126 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001129 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001130 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001131 &StringTokLocs[0],
1132 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001133}
1134
John McCall469a1eb2011-02-02 13:00:07 +00001135enum CaptureResult {
1136 /// No capture is required.
1137 CR_NoCapture,
1138
1139 /// A capture is required.
1140 CR_Capture,
1141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 /// A by-ref capture is required.
1143 CR_CaptureByRef,
1144
John McCall469a1eb2011-02-02 13:00:07 +00001145 /// An error occurred when trying to capture the given variable.
1146 CR_Error
1147};
1148
1149/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001150///
John McCall469a1eb2011-02-02 13:00:07 +00001151/// \param var - the variable referenced
1152/// \param DC - the context which we couldn't capture through
1153static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001154diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001155 VarDecl *var, DeclContext *DC) {
1156 switch (S.ExprEvalContexts.back().Context) {
1157 case Sema::Unevaluated:
1158 // The argument will never be evaluated, so don't complain.
1159 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCall469a1eb2011-02-02 13:00:07 +00001161 case Sema::PotentiallyEvaluated:
1162 case Sema::PotentiallyEvaluatedIfUsed:
1163 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001164
John McCall469a1eb2011-02-02 13:00:07 +00001165 case Sema::PotentiallyPotentiallyEvaluated:
1166 // FIXME: delay these!
1167 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
John McCall469a1eb2011-02-02 13:00:07 +00001170 // Don't diagnose about capture if we're not actually in code right
1171 // now; in general, there are more appropriate places that will
1172 // diagnose this.
1173 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1174
John McCall4f38f412011-03-22 23:15:50 +00001175 // Certain madnesses can happen with parameter declarations, which
1176 // we want to ignore.
1177 if (isa<ParmVarDecl>(var)) {
1178 // - If the parameter still belongs to the translation unit, then
1179 // we're actually just using one parameter in the declaration of
1180 // the next. This is useful in e.g. VLAs.
1181 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1182 return CR_NoCapture;
1183
1184 // - This particular madness can happen in ill-formed default
1185 // arguments; claim it's okay and let downstream code handle it.
1186 if (S.CurContext == var->getDeclContext()->getParent())
1187 return CR_NoCapture;
1188 }
John McCall469a1eb2011-02-02 13:00:07 +00001189
1190 DeclarationName functionName;
1191 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1192 functionName = fn->getDeclName();
1193 // FIXME: variable from enclosing block that we couldn't capture from!
1194
1195 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1196 << var->getIdentifier() << functionName;
1197 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1198 << var->getIdentifier();
1199
1200 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001201}
1202
John McCall6b5a61b2011-02-07 10:33:21 +00001203/// There is a well-formed capture at a particular scope level;
1204/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001205static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1206 const BlockDecl::Capture &Capture) {
1207 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001208
1209 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001210 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001211 i != e; ++i) {
1212 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1213 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001214 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1215 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001216 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1217 }
1218
Richard Trieuccd891a2011-09-09 01:45:06 +00001219 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001220}
1221
1222/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001223/// given value in the current context requires a variable capture.
1224///
1225/// This also keeps the captures set in the BlockScopeInfo records
1226/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001227static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001228 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001229 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001230 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001231 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001232
1233 // Fast path: variables from the current context never require capture.
1234 DeclContext *DC = S.CurContext;
1235 if (var->getDeclContext() == DC) return CR_NoCapture;
1236
1237 // Only variables with local storage require capture.
1238 // FIXME: What about 'const' variables in C++?
1239 if (!var->hasLocalStorage()) return CR_NoCapture;
1240
1241 // Otherwise, we need to capture.
1242
1243 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001244 do {
1245 // Only blocks (and eventually C++0x closures) can capture; other
1246 // scopes don't work.
1247 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001248 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001249
1250 BlockScopeInfo *blockScope =
1251 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1252 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1253
John McCall6b5a61b2011-02-07 10:33:21 +00001254 // Check whether we've already captured it in this block. If so,
1255 // we're done.
1256 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1257 return propagateCapture(S, functionScopesIndex,
1258 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001259
1260 functionScopesIndex--;
1261 DC = cast<BlockDecl>(DC)->getDeclContext();
1262 } while (var->getDeclContext() != DC);
1263
John McCall6b5a61b2011-02-07 10:33:21 +00001264 // Okay, we descended all the way to the block that defines the variable.
1265 // Actually try to capture it.
1266 QualType type = var->getType();
1267
1268 // Prohibit variably-modified types.
1269 if (type->isVariablyModifiedType()) {
1270 S.Diag(loc, diag::err_ref_vm_type);
1271 S.Diag(var->getLocation(), diag::note_declared_at);
1272 return CR_Error;
1273 }
1274
1275 // Prohibit arrays, even in __block variables, but not references to
1276 // them.
1277 if (type->isArrayType()) {
1278 S.Diag(loc, diag::err_ref_array_type);
1279 S.Diag(var->getLocation(), diag::note_declared_at);
1280 return CR_Error;
1281 }
1282
1283 S.MarkDeclarationReferenced(loc, var);
1284
1285 // The BlocksAttr indicates the variable is bound by-reference.
1286 bool byRef = var->hasAttr<BlocksAttr>();
1287
1288 // Build a copy expression.
1289 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001290 const RecordType *rtype;
1291 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1292 (rtype = type->getAs<RecordType>())) {
1293
1294 // The capture logic needs the destructor, so make sure we mark it.
1295 // Usually this is unnecessary because most local variables have
1296 // their destructors marked at declaration time, but parameters are
1297 // an exception because it's technically only the call site that
1298 // actually requires the destructor.
1299 if (isa<ParmVarDecl>(var))
1300 S.FinalizeVarWithDestructor(var, rtype);
1301
John McCall6b5a61b2011-02-07 10:33:21 +00001302 // According to the blocks spec, the capture of a variable from
1303 // the stack requires a const copy constructor. This is not true
1304 // of the copy/move done to move a __block variable to the heap.
1305 type.addConst();
1306
1307 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1308 ExprResult result =
1309 S.PerformCopyInitialization(
1310 InitializedEntity::InitializeBlock(var->getLocation(),
1311 type, false),
1312 loc, S.Owned(declRef));
1313
1314 // Build a full-expression copy expression if initialization
1315 // succeeded and used a non-trivial constructor. Recover from
1316 // errors by pretending that the copy isn't necessary.
1317 if (!result.isInvalid() &&
1318 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1319 result = S.MaybeCreateExprWithCleanups(result);
1320 copyExpr = result.take();
1321 }
1322 }
1323
1324 // We're currently at the declarer; go back to the closure.
1325 functionScopesIndex++;
1326 BlockScopeInfo *blockScope =
1327 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1328
1329 // Build a valid capture in this scope.
1330 blockScope->Captures.push_back(
1331 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1332 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1333
1334 // Propagate that to inner captures if necessary.
1335 return propagateCapture(S, functionScopesIndex,
1336 blockScope->Captures.back());
1337}
1338
Richard Trieuccd891a2011-09-09 01:45:06 +00001339static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001340 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001341 bool ByRef) {
1342 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001343
Richard Trieuccd891a2011-09-09 01:45:06 +00001344 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001345 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001346 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001347
1348 QualType exprType = var->getType().getNonReferenceType();
1349
1350 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001351 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001352 // The variable will be bound by copy; make it const within the
1353 // closure, but record that this was done in the expression.
1354 bool constAdded = !exprType.isConstQualified();
1355 exprType.addConst();
1356
1357 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1358 NameInfo.getLoc(), false,
1359 constAdded);
1360 } else {
1361 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1362 NameInfo.getLoc(), true);
1363 }
1364
1365 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001366}
Chris Lattner639e2d32008-10-20 05:16:36 +00001367
John McCall60d7b3a2010-08-24 06:29:42 +00001368ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001369Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001370 SourceLocation Loc,
1371 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001372 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001373 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001374}
1375
John McCall76a40212011-02-09 01:13:10 +00001376/// BuildDeclRefExpr - Build an expression that references a
1377/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001378ExprResult
John McCall76a40212011-02-09 01:13:10 +00001379Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001380 const DeclarationNameInfo &NameInfo,
1381 const CXXScopeSpec *SS) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001382 if (getLangOptions().CUDA)
1383 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1384 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1385 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1386 CalleeTarget = IdentifyCUDATarget(Callee);
1387 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1388 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1389 << CalleeTarget << D->getIdentifier() << CallerTarget;
1390 Diag(D->getLocation(), diag::note_previous_decl)
1391 << D->getIdentifier();
1392 return ExprError();
1393 }
1394 }
1395
Abramo Bagnara25777432010-08-11 22:01:17 +00001396 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
John McCall7eb0a9e2010-11-24 05:12:34 +00001398 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001399 SS? SS->getWithLocInContext(Context)
1400 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001401 D, NameInfo, Ty, VK);
1402
1403 // Just in case we're building an illegal pointer-to-member.
1404 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1405 E->setObjectKind(OK_BitField);
1406
1407 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001408}
1409
Abramo Bagnara25777432010-08-11 22:01:17 +00001410/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001411/// possibly a list of template arguments.
1412///
1413/// If this produces template arguments, it is permitted to call
1414/// DecomposeTemplateName.
1415///
1416/// This actually loses a lot of source location information for
1417/// non-standard name kinds; we should consider preserving that in
1418/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001419void
1420Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1421 TemplateArgumentListInfo &Buffer,
1422 DeclarationNameInfo &NameInfo,
1423 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001424 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1425 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1426 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1427
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001428 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001429 Id.TemplateId->getTemplateArgs(),
1430 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001431 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001432 TemplateArgsPtr.release();
1433
John McCall2b5289b2010-08-23 07:28:44 +00001434 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001435 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001436 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001437 TemplateArgs = &Buffer;
1438 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001439 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001440 TemplateArgs = 0;
1441 }
1442}
1443
John McCall578b69b2009-12-16 08:11:27 +00001444/// Diagnose an empty lookup.
1445///
1446/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001447bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001448 CorrectTypoContext CTC,
1449 TemplateArgumentListInfo *ExplicitTemplateArgs,
1450 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001451 DeclarationName Name = R.getLookupName();
1452
John McCall578b69b2009-12-16 08:11:27 +00001453 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001454 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001455 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1456 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001457 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001458 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001459 diagnostic_suggest = diag::err_undeclared_use_suggest;
1460 }
John McCall578b69b2009-12-16 08:11:27 +00001461
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001462 // If the original lookup was an unqualified lookup, fake an
1463 // unqualified lookup. This is useful when (for example) the
1464 // original lookup would not have found something because it was a
1465 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001466 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001467 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001468 if (isa<CXXRecordDecl>(DC)) {
1469 LookupQualifiedName(R, DC);
1470
1471 if (!R.empty()) {
1472 // Don't give errors about ambiguities in this lookup.
1473 R.suppressDiagnostics();
1474
1475 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1476 bool isInstance = CurMethod &&
1477 CurMethod->isInstance() &&
1478 DC == CurMethod->getParent();
1479
1480 // Give a code modification hint to insert 'this->'.
1481 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1482 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001483 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001484 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1485 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001486 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001487 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001488 if (DepMethod) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00001489 if (getLangOptions().MicrosoftExt)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001490 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001491 Diag(R.getNameLoc(), diagnostic) << Name
1492 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1493 QualType DepThisType = DepMethod->getThisType(Context);
1494 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1495 R.getNameLoc(), DepThisType, false);
1496 TemplateArgumentListInfo TList;
1497 if (ULE->hasExplicitTemplateArgs())
1498 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001499
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001500 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001501 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001502 CXXDependentScopeMemberExpr *DepExpr =
1503 CXXDependentScopeMemberExpr::Create(
1504 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001505 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001506 R.getLookupNameInfo(),
1507 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001508 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001509 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001510 // FIXME: we should be able to handle this case too. It is correct
1511 // to add this-> here. This is a workaround for PR7947.
1512 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001513 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001514 } else {
John McCall578b69b2009-12-16 08:11:27 +00001515 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001516 }
John McCall578b69b2009-12-16 08:11:27 +00001517
1518 // Do we really want to note all of these?
1519 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1520 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1521
1522 // Tell the callee to try to recover.
1523 return false;
1524 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001525
1526 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001527 }
1528 }
1529
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001530 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001531 TypoCorrection Corrected;
1532 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1533 S, &SS, NULL, false, CTC))) {
1534 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1535 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1536 R.setLookupName(Corrected.getCorrection());
1537
Hans Wennborg701d1e72011-07-12 08:45:31 +00001538 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001539 if (Corrected.isOverloaded()) {
1540 OverloadCandidateSet OCS(R.getNameLoc());
1541 OverloadCandidateSet::iterator Best;
1542 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1543 CDEnd = Corrected.end();
1544 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001545 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001546 dyn_cast<FunctionTemplateDecl>(*CD))
1547 AddTemplateOverloadCandidate(
1548 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1549 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001550 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1551 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1552 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1553 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001554 }
1555 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1556 case OR_Success:
1557 ND = Best->Function;
1558 break;
1559 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001560 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001561 }
1562 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001563 R.addDecl(ND);
1564 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001565 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001566 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1567 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001568 else
1569 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001570 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001571 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001572 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1573 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001574 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001575 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001576
1577 // Tell the callee to try to recover.
1578 return false;
1579 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001580
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001581 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001582 // FIXME: If we ended up with a typo for a type name or
1583 // Objective-C class name, we're in trouble because the parser
1584 // is in the wrong place to recover. Suggest the typo
1585 // correction, but don't make it a fix-it since we're not going
1586 // to recover well anyway.
1587 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001588 Diag(R.getNameLoc(), diagnostic_suggest)
1589 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001590 else
1591 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001592 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001593 << SS.getRange();
1594
1595 // Don't try to recover; it won't work.
1596 return true;
1597 }
1598 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001599 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001600 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001601 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001602 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001603 else
Douglas Gregord203a162010-01-01 00:15:04 +00001604 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001605 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001606 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001607 return true;
1608 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001609 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001610 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001611
1612 // Emit a special diagnostic for failed member lookups.
1613 // FIXME: computing the declaration context might fail here (?)
1614 if (!SS.isEmpty()) {
1615 Diag(R.getNameLoc(), diag::err_no_member)
1616 << Name << computeDeclContext(SS, false)
1617 << SS.getRange();
1618 return true;
1619 }
1620
John McCall578b69b2009-12-16 08:11:27 +00001621 // Give up, we can't recover.
1622 Diag(R.getNameLoc(), diagnostic) << Name;
1623 return true;
1624}
1625
John McCall60d7b3a2010-08-24 06:29:42 +00001626ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001627 CXXScopeSpec &SS,
1628 UnqualifiedId &Id,
1629 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001630 bool IsAddressOfOperand) {
1631 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001632 "cannot be direct & operand and have a trailing lparen");
1633
1634 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001635 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001636
John McCall129e2df2009-11-30 22:42:35 +00001637 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001638
1639 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001640 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001641 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001642 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001643
Abramo Bagnara25777432010-08-11 22:01:17 +00001644 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001645 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001646 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001647
John McCallf7a1a742009-11-24 19:00:30 +00001648 // C++ [temp.dep.expr]p3:
1649 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001650 // -- an identifier that was declared with a dependent type,
1651 // (note: handled after lookup)
1652 // -- a template-id that is dependent,
1653 // (note: handled in BuildTemplateIdExpr)
1654 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001655 // -- a nested-name-specifier that contains a class-name that
1656 // names a dependent type.
1657 // Determine whether this is a member of an unknown specialization;
1658 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001659 bool DependentID = false;
1660 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1661 Name.getCXXNameType()->isDependentType()) {
1662 DependentID = true;
1663 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001664 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001665 if (RequireCompleteDeclContext(SS, DC))
1666 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001667 } else {
1668 DependentID = true;
1669 }
1670 }
1671
Chris Lattner337e5502011-02-18 01:27:55 +00001672 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001673 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001674 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001675
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001676 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001677 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001678 LookupResult R(*this, NameInfo,
1679 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1680 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001681 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001682 // Lookup the template name again to correctly establish the context in
1683 // which it was found. This is really unfortunate as we already did the
1684 // lookup to determine that it was a template name in the first place. If
1685 // this becomes a performance hit, we can work harder to preserve those
1686 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001687 bool MemberOfUnknownSpecialization;
1688 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1689 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001690
1691 if (MemberOfUnknownSpecialization ||
1692 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001693 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001694 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001695 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001696 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001697 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001699 // If the result might be in a dependent base class, this is a dependent
1700 // id-expression.
1701 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001702 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001703 TemplateArgs);
1704
John McCallf7a1a742009-11-24 19:00:30 +00001705 // If this reference is in an Objective-C method, then we need to do
1706 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001707 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001708 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001709 if (E.isInvalid())
1710 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Chris Lattner337e5502011-02-18 01:27:55 +00001712 if (Expr *Ex = E.takeAs<Expr>())
1713 return Owned(Ex);
1714
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001715 // for further use, this must be set to false if in class method.
1716 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001717 }
Chris Lattner8a934232008-03-31 00:36:02 +00001718 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001719
John McCallf7a1a742009-11-24 19:00:30 +00001720 if (R.isAmbiguous())
1721 return ExprError();
1722
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001723 // Determine whether this name might be a candidate for
1724 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001725 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001726
John McCallf7a1a742009-11-24 19:00:30 +00001727 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001729 // in C90, extension in C99, forbidden in C++).
1730 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1731 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1732 if (D) R.addDecl(D);
1733 }
1734
1735 // If this name wasn't predeclared and if this is not a function
1736 // call, diagnose the problem.
1737 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001738
1739 // In Microsoft mode, if we are inside a template class member function
1740 // and we can't resolve an identifier then assume the identifier is type
1741 // dependent. The goal is to postpone name lookup to instantiation time
1742 // to be able to search into type dependent base classes.
1743 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1744 isa<CXXMethodDecl>(CurContext))
1745 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1746 TemplateArgs);
1747
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001748 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001749 return ExprError();
1750
1751 assert(!R.empty() &&
1752 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001753
1754 // If we found an Objective-C instance variable, let
1755 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001756 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001757 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1758 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001759 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001760 // In a hopelessly buggy code, Objective-C instance variable
1761 // lookup fails and no expression will be built to reference it.
1762 if (!E.isInvalid() && !E.get())
1763 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001764 return move(E);
1765 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 }
1767 }
Mike Stump1eb44332009-09-09 15:08:12 +00001768
John McCallf7a1a742009-11-24 19:00:30 +00001769 // This is guaranteed from this point on.
1770 assert(!R.empty() || ADL);
1771
John McCallaa81e162009-12-01 22:10:20 +00001772 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001773 // C++ [class.mfct.non-static]p3:
1774 // When an id-expression that is not part of a class member access
1775 // syntax and not used to form a pointer to member is used in the
1776 // body of a non-static member function of class X, if name lookup
1777 // resolves the name in the id-expression to a non-static non-type
1778 // member of some class C, the id-expression is transformed into a
1779 // class member access expression using (*this) as the
1780 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001781 //
1782 // But we don't actually need to do this for '&' operands if R
1783 // resolved to a function or overloaded function set, because the
1784 // expression is ill-formed if it actually works out to be a
1785 // non-static member function:
1786 //
1787 // C++ [expr.ref]p4:
1788 // Otherwise, if E1.E2 refers to a non-static member function. . .
1789 // [t]he expression can be used only as the left-hand operand of a
1790 // member function call.
1791 //
1792 // There are other safeguards against such uses, but it's important
1793 // to get this right here so that we don't end up making a
1794 // spuriously dependent expression if we're inside a dependent
1795 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001796 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001797 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001798 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001799 MightBeImplicitMember = true;
1800 else if (!SS.isEmpty())
1801 MightBeImplicitMember = false;
1802 else if (R.isOverloadedResult())
1803 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001804 else if (R.isUnresolvableResult())
1805 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001806 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001807 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1808 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001809
1810 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001811 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001812 }
1813
John McCallf7a1a742009-11-24 19:00:30 +00001814 if (TemplateArgs)
1815 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001816
John McCallf7a1a742009-11-24 19:00:30 +00001817 return BuildDeclarationNameExpr(SS, R, ADL);
1818}
1819
John McCall129e2df2009-11-30 22:42:35 +00001820/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1821/// declaration name, generally during template instantiation.
1822/// There's a large number of things which don't need to be done along
1823/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001824ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001825Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001826 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001827 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001828 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001829 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001830
John McCall77bb1aa2010-05-01 00:40:08 +00001831 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001832 return ExprError();
1833
Abramo Bagnara25777432010-08-11 22:01:17 +00001834 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001835 LookupQualifiedName(R, DC);
1836
1837 if (R.isAmbiguous())
1838 return ExprError();
1839
1840 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001841 Diag(NameInfo.getLoc(), diag::err_no_member)
1842 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001843 return ExprError();
1844 }
1845
1846 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1847}
1848
1849/// LookupInObjCMethod - The parser has read a name in, and Sema has
1850/// detected that we're currently inside an ObjC method. Perform some
1851/// additional lookup.
1852///
1853/// Ideally, most of this would be done by lookup, but there's
1854/// actually quite a lot of extra work involved.
1855///
1856/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001857ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001858Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001859 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001860 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001861 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001862
John McCallf7a1a742009-11-24 19:00:30 +00001863 // There are two cases to handle here. 1) scoped lookup could have failed,
1864 // in which case we should look for an ivar. 2) scoped lookup could have
1865 // found a decl, but that decl is outside the current instance method (i.e.
1866 // a global variable). In these two cases, we do a lookup for an ivar with
1867 // this name, if the lookup sucedes, we replace it our current decl.
1868
1869 // If we're in a class method, we don't normally want to look for
1870 // ivars. But if we don't find anything else, and there's an
1871 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001872 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001873
1874 bool LookForIvars;
1875 if (Lookup.empty())
1876 LookForIvars = true;
1877 else if (IsClassMethod)
1878 LookForIvars = false;
1879 else
1880 LookForIvars = (Lookup.isSingleResult() &&
1881 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001882 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001883 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001884 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001885 ObjCInterfaceDecl *ClassDeclared;
1886 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1887 // Diagnose using an ivar in a class method.
1888 if (IsClassMethod)
1889 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1890 << IV->getDeclName());
1891
1892 // If we're referencing an invalid decl, just return this as a silent
1893 // error node. The error diagnostic was already emitted on the decl.
1894 if (IV->isInvalidDecl())
1895 return ExprError();
1896
1897 // Check if referencing a field with __attribute__((deprecated)).
1898 if (DiagnoseUseOfDecl(IV, Loc))
1899 return ExprError();
1900
1901 // Diagnose the use of an ivar outside of the declaring class.
1902 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1903 ClassDeclared != IFace)
1904 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1905
1906 // FIXME: This should use a new expr for a direct reference, don't
1907 // turn this into Self->ivar, just return a BareIVarExpr or something.
1908 IdentifierInfo &II = Context.Idents.get("self");
1909 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001910 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001911 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001912 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001913 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001914 SelfName, false, false);
1915 if (SelfExpr.isInvalid())
1916 return ExprError();
1917
John Wiegley429bb272011-04-08 18:41:53 +00001918 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1919 if (SelfExpr.isInvalid())
1920 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001921
John McCallf7a1a742009-11-24 19:00:30 +00001922 MarkDeclarationReferenced(Loc, IV);
1923 return Owned(new (Context)
1924 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001925 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001926 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001927 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001928 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001929 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001930 ObjCInterfaceDecl *ClassDeclared;
1931 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1932 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1933 IFace == ClassDeclared)
1934 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1935 }
1936 }
1937
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001938 if (Lookup.empty() && II && AllowBuiltinCreation) {
1939 // FIXME. Consolidate this with similar code in LookupName.
1940 if (unsigned BuiltinID = II->getBuiltinID()) {
1941 if (!(getLangOptions().CPlusPlus &&
1942 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1943 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1944 S, Lookup.isForRedeclaration(),
1945 Lookup.getNameLoc());
1946 if (D) Lookup.addDecl(D);
1947 }
1948 }
1949 }
John McCallf7a1a742009-11-24 19:00:30 +00001950 // Sentinel value saying that we didn't do anything special.
1951 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001952}
John McCallba135432009-11-21 08:51:07 +00001953
John McCall6bb80172010-03-30 21:47:33 +00001954/// \brief Cast a base object to a member's actual type.
1955///
1956/// Logically this happens in three phases:
1957///
1958/// * First we cast from the base type to the naming class.
1959/// The naming class is the class into which we were looking
1960/// when we found the member; it's the qualifier type if a
1961/// qualifier was provided, and otherwise it's the base type.
1962///
1963/// * Next we cast from the naming class to the declaring class.
1964/// If the member we found was brought into a class's scope by
1965/// a using declaration, this is that class; otherwise it's
1966/// the class declaring the member.
1967///
1968/// * Finally we cast from the declaring class to the "true"
1969/// declaring class of the member. This conversion does not
1970/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001971ExprResult
1972Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001973 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001974 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001975 NamedDecl *Member) {
1976 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1977 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001978 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001979
Douglas Gregor5fccd362010-03-03 23:55:11 +00001980 QualType DestRecordType;
1981 QualType DestType;
1982 QualType FromRecordType;
1983 QualType FromType = From->getType();
1984 bool PointerConversions = false;
1985 if (isa<FieldDecl>(Member)) {
1986 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001987
Douglas Gregor5fccd362010-03-03 23:55:11 +00001988 if (FromType->getAs<PointerType>()) {
1989 DestType = Context.getPointerType(DestRecordType);
1990 FromRecordType = FromType->getPointeeType();
1991 PointerConversions = true;
1992 } else {
1993 DestType = DestRecordType;
1994 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001995 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001996 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1997 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001998 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001999
Douglas Gregor5fccd362010-03-03 23:55:11 +00002000 DestType = Method->getThisType(Context);
2001 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002002
Douglas Gregor5fccd362010-03-03 23:55:11 +00002003 if (FromType->getAs<PointerType>()) {
2004 FromRecordType = FromType->getPointeeType();
2005 PointerConversions = true;
2006 } else {
2007 FromRecordType = FromType;
2008 DestType = DestRecordType;
2009 }
2010 } else {
2011 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002012 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002013 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002014
Douglas Gregor5fccd362010-03-03 23:55:11 +00002015 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002016 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002017
Douglas Gregor5fccd362010-03-03 23:55:11 +00002018 // If the unqualified types are the same, no conversion is necessary.
2019 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002020 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002021
John McCall6bb80172010-03-30 21:47:33 +00002022 SourceRange FromRange = From->getSourceRange();
2023 SourceLocation FromLoc = FromRange.getBegin();
2024
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002025 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002026
Douglas Gregor5fccd362010-03-03 23:55:11 +00002027 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002028 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002029 // class name.
2030 //
2031 // If the member was a qualified name and the qualified referred to a
2032 // specific base subobject type, we'll cast to that intermediate type
2033 // first and then to the object in which the member is declared. That allows
2034 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2035 //
2036 // class Base { public: int x; };
2037 // class Derived1 : public Base { };
2038 // class Derived2 : public Base { };
2039 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2040 //
2041 // void VeryDerived::f() {
2042 // x = 17; // error: ambiguous base subobjects
2043 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2044 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002045 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002046 QualType QType = QualType(Qualifier->getAsType(), 0);
2047 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2048 assert(QType->isRecordType() && "lookup done with non-record type");
2049
2050 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2051
2052 // In C++98, the qualifier type doesn't actually have to be a base
2053 // type of the object type, in which case we just ignore it.
2054 // Otherwise build the appropriate casts.
2055 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002056 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002057 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002058 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002059 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002060
Douglas Gregor5fccd362010-03-03 23:55:11 +00002061 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002062 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002063 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2064 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002065
2066 FromType = QType;
2067 FromRecordType = QRecordType;
2068
2069 // If the qualifier type was the same as the destination type,
2070 // we're done.
2071 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002072 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002073 }
2074 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002075
John McCall6bb80172010-03-30 21:47:33 +00002076 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002077
John McCall6bb80172010-03-30 21:47:33 +00002078 // If we actually found the member through a using declaration, cast
2079 // down to the using declaration's type.
2080 //
2081 // Pointer equality is fine here because only one declaration of a
2082 // class ever has member declarations.
2083 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2084 assert(isa<UsingShadowDecl>(FoundDecl));
2085 QualType URecordType = Context.getTypeDeclType(
2086 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2087
2088 // We only need to do this if the naming-class to declaring-class
2089 // conversion is non-trivial.
2090 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2091 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002092 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002093 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002094 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002095 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002096
John McCall6bb80172010-03-30 21:47:33 +00002097 QualType UType = URecordType;
2098 if (PointerConversions)
2099 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002100 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2101 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002102 FromType = UType;
2103 FromRecordType = URecordType;
2104 }
2105
2106 // We don't do access control for the conversion from the
2107 // declaring class to the true declaring class.
2108 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002109 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002110
John McCallf871d0c2010-08-07 06:22:56 +00002111 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002112 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2113 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002114 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002115 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002116
John Wiegley429bb272011-04-08 18:41:53 +00002117 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2118 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002119}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002120
John McCallf7a1a742009-11-24 19:00:30 +00002121bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002122 const LookupResult &R,
2123 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002124 // Only when used directly as the postfix-expression of a call.
2125 if (!HasTrailingLParen)
2126 return false;
2127
2128 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002129 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002130 return false;
2131
2132 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002133 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002134 return false;
2135
2136 // Turn off ADL when we find certain kinds of declarations during
2137 // normal lookup:
2138 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2139 NamedDecl *D = *I;
2140
2141 // C++0x [basic.lookup.argdep]p3:
2142 // -- a declaration of a class member
2143 // Since using decls preserve this property, we check this on the
2144 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002145 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002146 return false;
2147
2148 // C++0x [basic.lookup.argdep]p3:
2149 // -- a block-scope function declaration that is not a
2150 // using-declaration
2151 // NOTE: we also trigger this for function templates (in fact, we
2152 // don't check the decl type at all, since all other decl types
2153 // turn off ADL anyway).
2154 if (isa<UsingShadowDecl>(D))
2155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2156 else if (D->getDeclContext()->isFunctionOrMethod())
2157 return false;
2158
2159 // C++0x [basic.lookup.argdep]p3:
2160 // -- a declaration that is neither a function or a function
2161 // template
2162 // And also for builtin functions.
2163 if (isa<FunctionDecl>(D)) {
2164 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2165
2166 // But also builtin functions.
2167 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2168 return false;
2169 } else if (!isa<FunctionTemplateDecl>(D))
2170 return false;
2171 }
2172
2173 return true;
2174}
2175
2176
John McCallba135432009-11-21 08:51:07 +00002177/// Diagnoses obvious problems with the use of the given declaration
2178/// as an expression. This is only actually called for lookups that
2179/// were not overloaded, and it doesn't promise that the declaration
2180/// will in fact be used.
2181static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002182 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002183 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2184 return true;
2185 }
2186
2187 if (isa<ObjCInterfaceDecl>(D)) {
2188 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2189 return true;
2190 }
2191
2192 if (isa<NamespaceDecl>(D)) {
2193 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2194 return true;
2195 }
2196
2197 return false;
2198}
2199
John McCall60d7b3a2010-08-24 06:29:42 +00002200ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002201Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002202 LookupResult &R,
2203 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002204 // If this is a single, fully-resolved result and we don't need ADL,
2205 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002206 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002207 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2208 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002209
2210 // We only need to check the declaration if there's exactly one
2211 // result, because in the overloaded case the results can only be
2212 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002213 if (R.isSingleResult() &&
2214 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002215 return ExprError();
2216
John McCallc373d482010-01-27 01:50:18 +00002217 // Otherwise, just build an unresolved lookup expression. Suppress
2218 // any lookup-related diagnostics; we'll hash these out later, when
2219 // we've picked a target.
2220 R.suppressDiagnostics();
2221
John McCallba135432009-11-21 08:51:07 +00002222 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002223 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002224 SS.getWithLocInContext(Context),
2225 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002226 NeedsADL, R.isOverloadedResult(),
2227 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002228
2229 return Owned(ULE);
2230}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002231
John McCallba135432009-11-21 08:51:07 +00002232/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002233ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002234Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002235 const DeclarationNameInfo &NameInfo,
2236 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002237 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002238 assert(!isa<FunctionTemplateDecl>(D) &&
2239 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002240
Abramo Bagnara25777432010-08-11 22:01:17 +00002241 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002242 if (CheckDeclInExpr(*this, Loc, D))
2243 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002244
Douglas Gregor9af2f522009-12-01 16:58:18 +00002245 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2246 // Specifically diagnose references to class templates that are missing
2247 // a template argument list.
2248 Diag(Loc, diag::err_template_decl_ref)
2249 << Template << SS.getRange();
2250 Diag(Template->getLocation(), diag::note_template_decl_here);
2251 return ExprError();
2252 }
2253
2254 // Make sure that we're referring to a value.
2255 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2256 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002257 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002258 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002259 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002260 return ExprError();
2261 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002262
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002263 // Check whether this declaration can be used. Note that we suppress
2264 // this check when we're going to perform argument-dependent lookup
2265 // on this function name, because this might not be the function
2266 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002267 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002268 return ExprError();
2269
Steve Naroffdd972f22008-09-05 22:11:13 +00002270 // Only create DeclRefExpr's for valid Decl's.
2271 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002272 return ExprError();
2273
John McCall5808ce42011-02-03 08:15:49 +00002274 // Handle members of anonymous structs and unions. If we got here,
2275 // and the reference is to a class member indirect field, then this
2276 // must be the subject of a pointer-to-member expression.
2277 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2278 if (!indirectField->isCXXClassMember())
2279 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2280 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002281
Chris Lattner639e2d32008-10-20 05:16:36 +00002282 // If the identifier reference is inside a block, and it refers to a value
2283 // that is outside the block, create a BlockDeclRefExpr instead of a
2284 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2285 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002286 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002287 // We do not do this for things like enum constants, global variables, etc,
2288 // as they do not get snapshotted.
2289 //
John McCall6b5a61b2011-02-07 10:33:21 +00002290 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002291 case CR_Error:
2292 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002293
John McCall469a1eb2011-02-02 13:00:07 +00002294 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002295 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2296 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2297
2298 case CR_CaptureByRef:
2299 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2300 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002301
2302 case CR_NoCapture: {
2303 // If this reference is not in a block or if the referenced
2304 // variable is within the block, create a normal DeclRefExpr.
2305
2306 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002307 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002308
2309 switch (D->getKind()) {
2310 // Ignore all the non-ValueDecl kinds.
2311#define ABSTRACT_DECL(kind)
2312#define VALUE(type, base)
2313#define DECL(type, base) \
2314 case Decl::type:
2315#include "clang/AST/DeclNodes.inc"
2316 llvm_unreachable("invalid value decl kind");
2317 return ExprError();
2318
2319 // These shouldn't make it here.
2320 case Decl::ObjCAtDefsField:
2321 case Decl::ObjCIvar:
2322 llvm_unreachable("forming non-member reference to ivar?");
2323 return ExprError();
2324
2325 // Enum constants are always r-values and never references.
2326 // Unresolved using declarations are dependent.
2327 case Decl::EnumConstant:
2328 case Decl::UnresolvedUsingValue:
2329 valueKind = VK_RValue;
2330 break;
2331
2332 // Fields and indirect fields that got here must be for
2333 // pointer-to-member expressions; we just call them l-values for
2334 // internal consistency, because this subexpression doesn't really
2335 // exist in the high-level semantics.
2336 case Decl::Field:
2337 case Decl::IndirectField:
2338 assert(getLangOptions().CPlusPlus &&
2339 "building reference to field in C?");
2340
2341 // These can't have reference type in well-formed programs, but
2342 // for internal consistency we do this anyway.
2343 type = type.getNonReferenceType();
2344 valueKind = VK_LValue;
2345 break;
2346
2347 // Non-type template parameters are either l-values or r-values
2348 // depending on the type.
2349 case Decl::NonTypeTemplateParm: {
2350 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2351 type = reftype->getPointeeType();
2352 valueKind = VK_LValue; // even if the parameter is an r-value reference
2353 break;
2354 }
2355
2356 // For non-references, we need to strip qualifiers just in case
2357 // the template parameter was declared as 'const int' or whatever.
2358 valueKind = VK_RValue;
2359 type = type.getUnqualifiedType();
2360 break;
2361 }
2362
2363 case Decl::Var:
2364 // In C, "extern void blah;" is valid and is an r-value.
2365 if (!getLangOptions().CPlusPlus &&
2366 !type.hasQualifiers() &&
2367 type->isVoidType()) {
2368 valueKind = VK_RValue;
2369 break;
2370 }
2371 // fallthrough
2372
2373 case Decl::ImplicitParam:
2374 case Decl::ParmVar:
2375 // These are always l-values.
2376 valueKind = VK_LValue;
2377 type = type.getNonReferenceType();
2378 break;
2379
2380 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002381 const FunctionType *fty = type->castAs<FunctionType>();
2382
2383 // If we're referring to a function with an __unknown_anytype
2384 // result type, make the entire expression __unknown_anytype.
2385 if (fty->getResultType() == Context.UnknownAnyTy) {
2386 type = Context.UnknownAnyTy;
2387 valueKind = VK_RValue;
2388 break;
2389 }
2390
John McCall76a40212011-02-09 01:13:10 +00002391 // Functions are l-values in C++.
2392 if (getLangOptions().CPlusPlus) {
2393 valueKind = VK_LValue;
2394 break;
2395 }
2396
2397 // C99 DR 316 says that, if a function type comes from a
2398 // function definition (without a prototype), that type is only
2399 // used for checking compatibility. Therefore, when referencing
2400 // the function, we pretend that we don't have the full function
2401 // type.
John McCall755d8492011-04-12 00:42:48 +00002402 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2403 isa<FunctionProtoType>(fty))
2404 type = Context.getFunctionNoProtoType(fty->getResultType(),
2405 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002406
2407 // Functions are r-values in C.
2408 valueKind = VK_RValue;
2409 break;
2410 }
2411
2412 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002413 // If we're referring to a method with an __unknown_anytype
2414 // result type, make the entire expression __unknown_anytype.
2415 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002416 if (const FunctionProtoType *proto
2417 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002418 if (proto->getResultType() == Context.UnknownAnyTy) {
2419 type = Context.UnknownAnyTy;
2420 valueKind = VK_RValue;
2421 break;
2422 }
2423
John McCall76a40212011-02-09 01:13:10 +00002424 // C++ methods are l-values if static, r-values if non-static.
2425 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2426 valueKind = VK_LValue;
2427 break;
2428 }
2429 // fallthrough
2430
2431 case Decl::CXXConversion:
2432 case Decl::CXXDestructor:
2433 case Decl::CXXConstructor:
2434 valueKind = VK_RValue;
2435 break;
2436 }
2437
2438 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2439 }
2440
John McCall469a1eb2011-02-02 13:00:07 +00002441 }
John McCallf89e55a2010-11-18 06:31:45 +00002442
John McCall6b5a61b2011-02-07 10:33:21 +00002443 llvm_unreachable("unknown capture result");
2444 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002445}
2446
John McCall755d8492011-04-12 00:42:48 +00002447ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002448 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002449
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002451 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002452 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2453 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2454 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002455 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002456
Chris Lattnerfa28b302008-01-12 08:14:25 +00002457 // Pre-defined identifiers are of type char[x], where x is the length of the
2458 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Anders Carlsson3a082d82009-09-08 18:24:21 +00002460 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002461 if (!currentDecl && getCurBlock())
2462 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002463 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002464 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002465 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002466 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002467
Anders Carlsson773f3972009-09-11 01:22:35 +00002468 QualType ResTy;
2469 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2470 ResTy = Context.DependentTy;
2471 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002472 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002473
Anders Carlsson773f3972009-09-11 01:22:35 +00002474 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002475 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002476 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2477 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002478 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002479}
2480
John McCall60d7b3a2010-08-24 06:29:42 +00002481ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002483 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002484 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002485 if (Invalid)
2486 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002487
Benjamin Kramerddeea562010-02-27 13:44:12 +00002488 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002489 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002491 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002492
Chris Lattnere8337df2009-12-30 21:19:39 +00002493 QualType Ty;
2494 if (!getLangOptions().CPlusPlus)
2495 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2496 else if (Literal.isWide())
2497 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002498 else if (Literal.isUTF16())
2499 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2500 else if (Literal.isUTF32())
2501 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002502 else if (Literal.isMultiChar())
2503 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002504 else
2505 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002506
Douglas Gregor5cee1192011-07-27 05:40:30 +00002507 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2508 if (Literal.isWide())
2509 Kind = CharacterLiteral::Wide;
2510 else if (Literal.isUTF16())
2511 Kind = CharacterLiteral::UTF16;
2512 else if (Literal.isUTF32())
2513 Kind = CharacterLiteral::UTF32;
2514
2515 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2516 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002517}
2518
John McCall60d7b3a2010-08-24 06:29:42 +00002519ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002520 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002521 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2522 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002523 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002524 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002525 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002526 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 }
Ted Kremenek28396602009-01-13 23:19:12 +00002528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002530 // Add padding so that NumericLiteralParser can overread by one character.
2531 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002532 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002533
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002535 bool Invalid = false;
2536 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2537 if (Invalid)
2538 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002539
Mike Stump1eb44332009-09-09 15:08:12 +00002540 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 Tok.getLocation(), PP);
2542 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002543 return ExprError();
2544
Chris Lattner5d661452007-08-26 03:42:43 +00002545 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002546
Chris Lattner5d661452007-08-26 03:42:43 +00002547 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002548 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002549 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002550 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002551 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002552 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002553 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002554 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002555
2556 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2557
John McCall94c939d2009-12-24 09:08:04 +00002558 using llvm::APFloat;
2559 APFloat Val(Format);
2560
2561 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002562
2563 // Overflow is always an error, but underflow is only an error if
2564 // we underflowed to zero (APFloat reports denormals as underflow).
2565 if ((result & APFloat::opOverflow) ||
2566 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002567 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002568 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002569 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002570 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002571 APFloat::getLargest(Format).toString(buffer);
2572 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002573 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002574 APFloat::getSmallest(Format).toString(buffer);
2575 }
2576
2577 Diag(Tok.getLocation(), diagnostic)
2578 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002580 }
2581
2582 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002583 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002584
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002585 if (Ty == Context.DoubleTy) {
2586 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002587 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002588 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2589 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002590 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002591 }
2592 }
Chris Lattner5d661452007-08-26 03:42:43 +00002593 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002594 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002595 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002596 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002597
Neil Boothb9449512007-08-29 22:00:19 +00002598 // long long is a C99 feature.
2599 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002600 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002601 Diag(Tok.getLocation(), diag::ext_longlong);
2602
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002604 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002605
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 if (Literal.GetIntegerValue(ResultVal)) {
2607 // If this value didn't fit into uintmax_t, warn and force to ull.
2608 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002609 Ty = Context.UnsignedLongLongTy;
2610 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002611 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 } else {
2613 // If this value fits into a ULL, try to figure out what else it fits into
2614 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002615
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2617 // be an unsigned int.
2618 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2619
2620 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002621 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002622 if (!Literal.isLong && !Literal.isLongLong) {
2623 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002624 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // Does it fit in a unsigned int?
2627 if (ResultVal.isIntN(IntSize)) {
2628 // Does it fit in a signed int?
2629 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002630 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002632 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002633 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002636
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002638 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002639 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002640
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 // Does it fit in a unsigned long?
2642 if (ResultVal.isIntN(LongSize)) {
2643 // Does it fit in a signed long?
2644 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002645 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002647 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002648 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002650 }
2651
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002653 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002654 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // Does it fit in a unsigned long long?
2657 if (ResultVal.isIntN(LongLongSize)) {
2658 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002659 // To be compatible with MSVC, hex integer literals ending with the
2660 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002661 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet62ec1f22011-09-17 17:15:52 +00002662 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002663 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002665 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002666 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 }
2668 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 // If we still couldn't decide a type, we probably have something that
2671 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002672 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002674 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002675 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002677
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002678 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002679 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002681 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002683
Chris Lattner5d661452007-08-26 03:42:43 +00002684 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2685 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002686 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002687 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002688
2689 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002690}
2691
Richard Trieuccd891a2011-09-09 01:45:06 +00002692ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002693 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002694 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002695}
2696
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002697static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2698 SourceLocation Loc,
2699 SourceRange ArgRange) {
2700 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2701 // scalar or vector data type argument..."
2702 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2703 // type (C99 6.2.5p18) or void.
2704 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2705 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2706 << T << ArgRange;
2707 return true;
2708 }
2709
2710 assert((T->isVoidType() || !T->isIncompleteType()) &&
2711 "Scalar types should always be complete");
2712 return false;
2713}
2714
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002715static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2716 SourceLocation Loc,
2717 SourceRange ArgRange,
2718 UnaryExprOrTypeTrait TraitKind) {
2719 // C99 6.5.3.4p1:
2720 if (T->isFunctionType()) {
2721 // alignof(function) is allowed as an extension.
2722 if (TraitKind == UETT_SizeOf)
2723 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2724 return false;
2725 }
2726
2727 // Allow sizeof(void)/alignof(void) as an extension.
2728 if (T->isVoidType()) {
2729 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2730 return false;
2731 }
2732
2733 return true;
2734}
2735
2736static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2737 SourceLocation Loc,
2738 SourceRange ArgRange,
2739 UnaryExprOrTypeTrait TraitKind) {
2740 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2741 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2742 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2743 << T << (TraitKind == UETT_SizeOf)
2744 << ArgRange;
2745 return true;
2746 }
2747
2748 return false;
2749}
2750
Chandler Carruth9d342d02011-05-26 08:53:10 +00002751/// \brief Check the constrains on expression operands to unary type expression
2752/// and type traits.
2753///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002754/// Completes any types necessary and validates the constraints on the operand
2755/// expression. The logic mostly mirrors the type-based overload, but may modify
2756/// the expression as it completes the type for that expression through template
2757/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002758bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002759 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002760 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002761
2762 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2763 // the result is the size of the referenced type."
2764 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2765 // result shall be the alignment of the referenced type."
2766 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2767 ExprTy = Ref->getPointeeType();
2768
2769 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002770 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2771 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002772
2773 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002774 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2775 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002776 return false;
2777
Richard Trieuccd891a2011-09-09 01:45:06 +00002778 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002779 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002780 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002781 std::make_pair(SourceLocation(), PDiag(0))))
2782 return true;
2783
2784 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002785 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002786 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2787 ExprTy = Ref->getPointeeType();
2788
Richard Trieuccd891a2011-09-09 01:45:06 +00002789 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2790 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002791 return true;
2792
Nico Webercf739922011-06-15 02:47:03 +00002793 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002794 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002795 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2796 QualType OType = PVD->getOriginalType();
2797 QualType Type = PVD->getType();
2798 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002799 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002800 << Type << OType;
2801 Diag(PVD->getLocation(), diag::note_declared_at);
2802 }
2803 }
2804 }
2805 }
2806
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002807 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002808}
2809
2810/// \brief Check the constraints on operands to unary expression and type
2811/// traits.
2812///
2813/// This will complete any types necessary, and validate the various constraints
2814/// on those operands.
2815///
Reid Spencer5f016e22007-07-11 17:01:13 +00002816/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002817/// C99 6.3.2.1p[2-4] all state:
2818/// Except when it is the operand of the sizeof operator ...
2819///
2820/// C++ [expr.sizeof]p4
2821/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2822/// standard conversions are not applied to the operand of sizeof.
2823///
2824/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002825bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002826 SourceLocation OpLoc,
2827 SourceRange ExprRange,
2828 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002829 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002830 return false;
2831
Sebastian Redl5d484e82009-11-23 17:18:46 +00002832 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2833 // the result is the size of the referenced type."
2834 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2835 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002836 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2837 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002838
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002839 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002840 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002841
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002842 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002843 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002844 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002845 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Richard Trieuccd891a2011-09-09 01:45:06 +00002847 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002848 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002849 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002850 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Richard Trieuccd891a2011-09-09 01:45:06 +00002852 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002853 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002854 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Chris Lattner1efaa952009-04-24 00:30:45 +00002856 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002857}
2858
Chandler Carruth9d342d02011-05-26 08:53:10 +00002859static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002860 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002861
Mike Stump1eb44332009-09-09 15:08:12 +00002862 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002863 if (isa<DeclRefExpr>(E))
2864 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002865
2866 // Cannot know anything else if the expression is dependent.
2867 if (E->isTypeDependent())
2868 return false;
2869
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002870 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002871 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2872 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002873 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002874 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002875
2876 // Alignment of a field access is always okay, so long as it isn't a
2877 // bit-field.
2878 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002879 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002880 return false;
2881
Chandler Carruth9d342d02011-05-26 08:53:10 +00002882 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002883}
2884
Chandler Carruth9d342d02011-05-26 08:53:10 +00002885bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002886 E = E->IgnoreParens();
2887
2888 // Cannot know anything else if the expression is dependent.
2889 if (E->isTypeDependent())
2890 return false;
2891
Chandler Carruth9d342d02011-05-26 08:53:10 +00002892 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002893}
2894
Douglas Gregorba498172009-03-13 21:01:28 +00002895/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002896ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002897Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2898 SourceLocation OpLoc,
2899 UnaryExprOrTypeTrait ExprKind,
2900 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002901 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002902 return ExprError();
2903
John McCalla93c9342009-12-07 02:54:59 +00002904 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002905
Douglas Gregorba498172009-03-13 21:01:28 +00002906 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002907 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002908 return ExprError();
2909
2910 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002911 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2912 Context.getSizeType(),
2913 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002914}
2915
2916/// \brief Build a sizeof or alignof expression given an expression
2917/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002918ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002919Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2920 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002921 ExprResult PE = CheckPlaceholderExpr(E);
2922 if (PE.isInvalid())
2923 return ExprError();
2924
2925 E = PE.get();
2926
Douglas Gregorba498172009-03-13 21:01:28 +00002927 // Verify that the operand is valid.
2928 bool isInvalid = false;
2929 if (E->isTypeDependent()) {
2930 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002931 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002932 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002933 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002934 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002935 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002936 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002937 isInvalid = true;
2938 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002939 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002940 }
2941
2942 if (isInvalid)
2943 return ExprError();
2944
2945 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002946 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002947 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002948 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002949}
2950
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002951/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2952/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002953/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002954ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002955Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002956 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002957 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002959 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002960
Richard Trieuccd891a2011-09-09 01:45:06 +00002961 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00002962 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002963 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002964 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002965 }
Sebastian Redl05189992008-11-11 17:56:53 +00002966
Douglas Gregorba498172009-03-13 21:01:28 +00002967 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002968 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002969 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002970}
2971
John Wiegley429bb272011-04-08 18:41:53 +00002972static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002973 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002974 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002975 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002976
John McCallf6a16482010-12-04 03:47:34 +00002977 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002978 if (V.get()->getObjectKind() != OK_Ordinary) {
2979 V = S.DefaultLvalueConversion(V.take());
2980 if (V.isInvalid())
2981 return QualType();
2982 }
John McCallf6a16482010-12-04 03:47:34 +00002983
Chris Lattnercc26ed72007-08-26 05:39:26 +00002984 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002985 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002986 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Chris Lattnercc26ed72007-08-26 05:39:26 +00002988 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002989 if (V.get()->getType()->isArithmeticType())
2990 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002991
John McCall2cd11fe2010-10-12 02:09:17 +00002992 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002993 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002994 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002995 if (PR.get() != V.get()) {
2996 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00002997 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002998 }
2999
Chris Lattnercc26ed72007-08-26 05:39:26 +00003000 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003001 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003002 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003003 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003004}
3005
3006
Reid Spencer5f016e22007-07-11 17:01:13 +00003007
John McCall60d7b3a2010-08-24 06:29:42 +00003008ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003009Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003010 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003011 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003013 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003014 case tok::plusplus: Opc = UO_PostInc; break;
3015 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003017
John McCall9ae2f072010-08-23 23:25:46 +00003018 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003019}
3020
John McCall60d7b3a2010-08-24 06:29:42 +00003021ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003022Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3023 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003024 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003025 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003026 if (Result.isInvalid()) return ExprError();
3027 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003028
John McCall9ae2f072010-08-23 23:25:46 +00003029 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Douglas Gregor337c6b92008-11-19 17:17:41 +00003031 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003032 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003033 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003034 Context.DependentTy,
3035 VK_LValue, OK_Ordinary,
3036 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003037 }
3038
Mike Stump1eb44332009-09-09 15:08:12 +00003039 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003040 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003041 LHSExp->getType()->isEnumeralType() ||
3042 RHSExp->getType()->isRecordType() ||
3043 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003044 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003045 }
3046
John McCall9ae2f072010-08-23 23:25:46 +00003047 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003048}
3049
3050
John McCall60d7b3a2010-08-24 06:29:42 +00003051ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003052Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003053 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003054 Expr *LHSExp = Base;
3055 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003056
Chris Lattner12d9ff62007-07-16 00:14:47 +00003057 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003058 if (!LHSExp->getType()->getAs<VectorType>()) {
3059 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3060 if (Result.isInvalid())
3061 return ExprError();
3062 LHSExp = Result.take();
3063 }
3064 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3065 if (Result.isInvalid())
3066 return ExprError();
3067 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003068
Chris Lattner12d9ff62007-07-16 00:14:47 +00003069 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003070 ExprValueKind VK = VK_LValue;
3071 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003072
Reid Spencer5f016e22007-07-11 17:01:13 +00003073 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003074 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003075 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003076 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003077 Expr *BaseExpr, *IndexExpr;
3078 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003079 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003083 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003086 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003087 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003088 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003089 BaseExpr = RHSExp;
3090 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003091 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003092 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003093 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003094 BaseExpr = LHSExp;
3095 IndexExpr = RHSExp;
3096 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003097 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003098 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003099 // Handle the uncommon case of "123[Ptr]".
3100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
3102 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003103 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003104 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003105 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003106 VK = LHSExp->getValueKind();
3107 if (VK != VK_RValue)
3108 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003109
Chris Lattner12d9ff62007-07-16 00:14:47 +00003110 // FIXME: need to deal with const...
3111 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003112 } else if (LHSTy->isArrayType()) {
3113 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003114 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003115 // wasn't promoted because of the C90 rule that doesn't
3116 // allow promoting non-lvalue arrays. Warn, then
3117 // force the promotion here.
3118 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3119 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003120 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3121 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003122 LHSTy = LHSExp->getType();
3123
3124 BaseExpr = LHSExp;
3125 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003126 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003127 } else if (RHSTy->isArrayType()) {
3128 // Same as previous, except for 123[f().a] case
3129 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3130 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003131 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3132 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003133 RHSTy = RHSExp->getType();
3134
3135 BaseExpr = RHSExp;
3136 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003137 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003139 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3140 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003141 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003142 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003143 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003144 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3145 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003146
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003147 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003148 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3149 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003150 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3151
Douglas Gregore7450f52009-03-24 19:52:54 +00003152 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003153 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3154 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003155 // incomplete types are not object types.
3156 if (ResultType->isFunctionType()) {
3157 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3158 << ResultType << BaseExpr->getSourceRange();
3159 return ExprError();
3160 }
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Abramo Bagnara46358452010-09-13 06:50:07 +00003162 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3163 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003164 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3165 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003166
3167 // C forbids expressions of unqualified void type from being l-values.
3168 // See IsCForbiddenLValueType.
3169 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003170 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003171 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003172 PDiag(diag::err_subscript_incomplete_type)
3173 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003174 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Chris Lattner1efaa952009-04-24 00:30:45 +00003176 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003177 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003178 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3179 << ResultType << BaseExpr->getSourceRange();
3180 return ExprError();
3181 }
Mike Stump1eb44332009-09-09 15:08:12 +00003182
John McCall09431682010-11-18 19:01:18 +00003183 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003184 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003185
Mike Stumpeed9cac2009-02-19 03:04:26 +00003186 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003187 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003188}
3189
John McCall60d7b3a2010-08-24 06:29:42 +00003190ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003191 FunctionDecl *FD,
3192 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003193 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003194 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003195 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003196 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003197 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003198 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003199 return ExprError();
3200 }
3201
3202 if (Param->hasUninstantiatedDefaultArg()) {
3203 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003204
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003205 // Instantiate the expression.
3206 MultiLevelTemplateArgumentList ArgList
3207 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003208
Nico Weber08e41a62010-11-29 18:19:25 +00003209 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003210 = ArgList.getInnermost();
3211 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3212 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003213
Nico Weber08e41a62010-11-29 18:19:25 +00003214 ExprResult Result;
3215 {
3216 // C++ [dcl.fct.default]p5:
3217 // The names in the [default argument] expression are bound, and
3218 // the semantic constraints are checked, at the point where the
3219 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003220 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003221 Result = SubstExpr(UninstExpr, ArgList);
3222 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003223 if (Result.isInvalid())
3224 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003225
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003226 // Check the expression as an initializer for the parameter.
3227 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003228 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003229 InitializationKind Kind
3230 = InitializationKind::CreateCopy(Param->getLocation(),
3231 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3232 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003233
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003234 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3235 Result = InitSeq.Perform(*this, Entity, Kind,
3236 MultiExprArg(*this, &ResultE, 1));
3237 if (Result.isInvalid())
3238 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003239
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003240 // Build the default argument expression.
3241 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3242 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003243 }
3244
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003245 // If the default expression creates temporaries, we need to
3246 // push them to the current stack of expression temporaries so they'll
3247 // be properly destroyed.
3248 // FIXME: We should really be rebuilding the default argument with new
3249 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003250 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3251 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3252 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3253 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3254 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003255 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003256 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003257
3258 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003259 // Just mark all of the declarations in this potentially-evaluated expression
3260 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003261 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003262 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003263}
3264
Douglas Gregor88a35142008-12-22 05:46:06 +00003265/// ConvertArgumentsForCall - Converts the arguments specified in
3266/// Args/NumArgs to the parameter types of the function FDecl with
3267/// function prototype Proto. Call is the call expression itself, and
3268/// Fn is the function expression. For a C++ member function, this
3269/// routine does not attempt to convert the object argument. Returns
3270/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003271bool
3272Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003273 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003274 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003275 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003276 SourceLocation RParenLoc,
3277 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003278 // Bail out early if calling a builtin with custom typechecking.
3279 // We don't need to do this in the
3280 if (FDecl)
3281 if (unsigned ID = FDecl->getBuiltinID())
3282 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3283 return false;
3284
Mike Stumpeed9cac2009-02-19 03:04:26 +00003285 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 // assignment, to the types of the corresponding parameter, ...
3287 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003288 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003289 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003290 unsigned FnKind = Fn->getType()->isBlockPointerType()
3291 ? 1 /* block */
3292 : (IsExecConfig ? 3 /* kernel function (exec config) */
3293 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003294
Douglas Gregor88a35142008-12-22 05:46:06 +00003295 // If too few arguments are available (and we don't have default
3296 // arguments for the remaining parameters), don't make the call.
3297 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003298 if (NumArgs < MinArgs) {
3299 Diag(RParenLoc, MinArgs == NumArgsInProto
3300 ? diag::err_typecheck_call_too_few_args
3301 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003302 << FnKind
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003303 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003304
3305 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003306 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003307 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3308 << FDecl;
3309
3310 return true;
3311 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003312 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003313 }
3314
3315 // If too many are passed and not variadic, error on the extras and drop
3316 // them.
3317 if (NumArgs > NumArgsInProto) {
3318 if (!Proto->isVariadic()) {
3319 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003320 MinArgs == NumArgsInProto
3321 ? diag::err_typecheck_call_too_many_args
3322 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003323 << FnKind
Eric Christopherccfa9632010-04-16 04:56:46 +00003324 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003325 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3326 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003327
3328 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003329 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003330 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3331 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003332
Douglas Gregor88a35142008-12-22 05:46:06 +00003333 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003334 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003335 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003336 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003337 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003338 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003339 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003340 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3341 if (Fn->getType()->isBlockPointerType())
3342 CallType = VariadicBlock; // Block
3343 else if (isa<MemberExpr>(Fn))
3344 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003345 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003346 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003347 if (Invalid)
3348 return true;
3349 unsigned TotalNumArgs = AllArgs.size();
3350 for (unsigned i = 0; i < TotalNumArgs; ++i)
3351 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003352
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003353 return false;
3354}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003355
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003356bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3357 FunctionDecl *FDecl,
3358 const FunctionProtoType *Proto,
3359 unsigned FirstProtoArg,
3360 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003361 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003362 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003363 unsigned NumArgsInProto = Proto->getNumArgs();
3364 unsigned NumArgsToCheck = NumArgs;
3365 bool Invalid = false;
3366 if (NumArgs != NumArgsInProto)
3367 // Use default arguments for missing arguments
3368 NumArgsToCheck = NumArgsInProto;
3369 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003370 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003371 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003372 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003373
Douglas Gregor88a35142008-12-22 05:46:06 +00003374 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003375 if (ArgIx < NumArgs) {
3376 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003377
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003378 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3379 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003380 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003381 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003382 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003383
Douglas Gregora188ff22009-12-22 16:09:06 +00003384 // Pass the argument
3385 ParmVarDecl *Param = 0;
3386 if (FDecl && i < FDecl->getNumParams())
3387 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003388
Douglas Gregora188ff22009-12-22 16:09:06 +00003389 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003390 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003391 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3392 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003393 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003394 SourceLocation(),
3395 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003396 if (ArgE.isInvalid())
3397 return true;
3398
3399 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003400 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003401 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003402
John McCall60d7b3a2010-08-24 06:29:42 +00003403 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003404 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003405 if (ArgExpr.isInvalid())
3406 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003407
Anders Carlsson56c5e332009-08-25 03:49:14 +00003408 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003409 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003410
3411 // Check for array bounds violations for each argument to the call. This
3412 // check only triggers warnings when the argument isn't a more complex Expr
3413 // with its own checking, such as a BinaryOperator.
3414 CheckArrayAccess(Arg);
3415
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003416 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003417 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003418
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003420 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003421
3422 // Assume that extern "C" functions with variadic arguments that
3423 // return __unknown_anytype aren't *really* variadic.
3424 if (Proto->getResultType() == Context.UnknownAnyTy &&
3425 FDecl && FDecl->isExternC()) {
3426 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3427 ExprResult arg;
3428 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3429 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3430 else
3431 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3432 Invalid |= arg.isInvalid();
3433 AllArgs.push_back(arg.take());
3434 }
3435
3436 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3437 } else {
3438 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003439 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3440 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003441 Invalid |= Arg.isInvalid();
3442 AllArgs.push_back(Arg.take());
3443 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003444 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003445
3446 // Check for array bounds violations.
3447 for (unsigned i = ArgIx; i != NumArgs; ++i)
3448 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003449 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003450 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003451}
3452
John McCall755d8492011-04-12 00:42:48 +00003453/// Given a function expression of unknown-any type, try to rebuild it
3454/// to have a function type.
3455static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3456
Steve Narofff69936d2007-09-16 03:34:24 +00003457/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003458/// This provides the location of the left/right parens and a list of comma
3459/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003460ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003461Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003462 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003463 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003464 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003465
3466 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003467 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003468 if (Result.isInvalid()) return ExprError();
3469 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Richard Trieuccd891a2011-09-09 01:45:06 +00003471 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Douglas Gregor88a35142008-12-22 05:46:06 +00003473 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003474 // If this is a pseudo-destructor expression, build the call immediately.
3475 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3476 if (NumArgs > 0) {
3477 // Pseudo-destructor calls should not have any arguments.
3478 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003479 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003480 SourceRange(Args[0]->getLocStart(),
3481 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Douglas Gregora71d8192009-09-04 17:36:40 +00003483 NumArgs = 0;
3484 }
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Douglas Gregora71d8192009-09-04 17:36:40 +00003486 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003487 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003488 }
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Douglas Gregor17330012009-02-04 15:01:18 +00003490 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003491 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003492 // FIXME: Will need to cache the results of name lookup (including ADL) in
3493 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003494 bool Dependent = false;
3495 if (Fn->isTypeDependent())
3496 Dependent = true;
3497 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3498 Dependent = true;
3499
Peter Collingbournee08ce652011-02-09 21:07:24 +00003500 if (Dependent) {
3501 if (ExecConfig) {
3502 return Owned(new (Context) CUDAKernelCallExpr(
3503 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3504 Context.DependentTy, VK_RValue, RParenLoc));
3505 } else {
3506 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3507 Context.DependentTy, VK_RValue,
3508 RParenLoc));
3509 }
3510 }
Douglas Gregor17330012009-02-04 15:01:18 +00003511
3512 // Determine whether this is a call to an object (C++ [over.call.object]).
3513 if (Fn->getType()->isRecordType())
3514 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003515 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003516
John McCall755d8492011-04-12 00:42:48 +00003517 if (Fn->getType() == Context.UnknownAnyTy) {
3518 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3519 if (result.isInvalid()) return ExprError();
3520 Fn = result.take();
3521 }
3522
John McCall864c0412011-04-26 20:42:42 +00003523 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003524 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003525 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003526 }
John McCall864c0412011-04-26 20:42:42 +00003527 }
John McCall129e2df2009-11-30 22:42:35 +00003528
John McCall864c0412011-04-26 20:42:42 +00003529 // Check for overloaded calls. This can happen even in C due to extensions.
3530 if (Fn->getType() == Context.OverloadTy) {
3531 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3532
3533 // We aren't supposed to apply this logic if there's an '&' involved.
3534 if (!find.IsAddressOfOperand) {
3535 OverloadExpr *ovl = find.Expression;
3536 if (isa<UnresolvedLookupExpr>(ovl)) {
3537 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3538 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3539 RParenLoc, ExecConfig);
3540 } else {
John McCallaa81e162009-12-01 22:10:20 +00003541 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003542 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003543 }
3544 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003545 }
3546
Douglas Gregorfa047642009-02-04 00:32:51 +00003547 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003548
Eli Friedmanefa42f72009-12-26 03:35:45 +00003549 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003550
John McCall3b4294e2009-12-16 12:17:52 +00003551 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003552 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3553 if (UnOp->getOpcode() == UO_AddrOf)
3554 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3555
John McCall3b4294e2009-12-16 12:17:52 +00003556 if (isa<DeclRefExpr>(NakedFn))
3557 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003558 else if (isa<MemberExpr>(NakedFn))
3559 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003560
Peter Collingbournee08ce652011-02-09 21:07:24 +00003561 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003562 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003563}
3564
3565ExprResult
3566Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003567 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003568 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3569 if (!ConfigDecl)
3570 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3571 << "cudaConfigureCall");
3572 QualType ConfigQTy = ConfigDecl->getType();
3573
3574 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3575 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3576
Peter Collingbourne1f240762011-10-02 23:49:29 +00003577 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3578 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003579}
3580
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003581/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3582///
3583/// __builtin_astype( value, dst type )
3584///
Richard Trieuccd891a2011-09-09 01:45:06 +00003585ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003586 SourceLocation BuiltinLoc,
3587 SourceLocation RParenLoc) {
3588 ExprValueKind VK = VK_RValue;
3589 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003590 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3591 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003592 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3593 return ExprError(Diag(BuiltinLoc,
3594 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003595 << DstTy
3596 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003597 << E->getSourceRange());
3598 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003599 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003600}
3601
John McCall3b4294e2009-12-16 12:17:52 +00003602/// BuildResolvedCallExpr - Build a call to a resolved expression,
3603/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003604/// unary-convert to an expression of function-pointer or
3605/// block-pointer type.
3606///
3607/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003608ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003609Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3610 SourceLocation LParenLoc,
3611 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003612 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003613 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003614 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3615
Chris Lattner04421082008-04-08 04:40:51 +00003616 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003617 ExprResult Result = UsualUnaryConversions(Fn);
3618 if (Result.isInvalid())
3619 return ExprError();
3620 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003621
Chris Lattner925e60d2007-12-28 05:29:59 +00003622 // Make the call expr early, before semantic checks. This guarantees cleanup
3623 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003624 CallExpr *TheCall;
3625 if (Config) {
3626 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3627 cast<CallExpr>(Config),
3628 Args, NumArgs,
3629 Context.BoolTy,
3630 VK_RValue,
3631 RParenLoc);
3632 } else {
3633 TheCall = new (Context) CallExpr(Context, Fn,
3634 Args, NumArgs,
3635 Context.BoolTy,
3636 VK_RValue,
3637 RParenLoc);
3638 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003639
John McCall8e10f3b2011-02-26 05:39:39 +00003640 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3641
3642 // Bail out early if calling a builtin with custom typechecking.
3643 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3644 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3645
John McCall1de4d4e2011-04-07 08:22:57 +00003646 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003647 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003648 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003649 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3650 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003651 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003652 if (FuncT == 0)
3653 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3654 << Fn->getType() << Fn->getSourceRange());
3655 } else if (const BlockPointerType *BPT =
3656 Fn->getType()->getAs<BlockPointerType>()) {
3657 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3658 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003659 // Handle calls to expressions of unknown-any type.
3660 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003661 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003662 if (rewrite.isInvalid()) return ExprError();
3663 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003664 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003665 goto retry;
3666 }
3667
Sebastian Redl0eb23302009-01-19 00:08:26 +00003668 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3669 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003670 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003671
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003672 if (getLangOptions().CUDA) {
3673 if (Config) {
3674 // CUDA: Kernel calls must be to global functions
3675 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3676 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3677 << FDecl->getName() << Fn->getSourceRange());
3678
3679 // CUDA: Kernel function must have 'void' return type
3680 if (!FuncT->getResultType()->isVoidType())
3681 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3682 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003683 } else {
3684 // CUDA: Calls to global functions must be configured
3685 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3686 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3687 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003688 }
3689 }
3690
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003691 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003692 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003693 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003694 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003695 return ExprError();
3696
Chris Lattner925e60d2007-12-28 05:29:59 +00003697 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003698 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003699 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003700
Douglas Gregor72564e72009-02-26 23:50:07 +00003701 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003702 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003703 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003704 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003705 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003706 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003707
Douglas Gregor74734d52009-04-02 15:37:10 +00003708 if (FDecl) {
3709 // Check if we have too few/too many template arguments, based
3710 // on our knowledge of the function definition.
3711 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003712 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003713 const FunctionProtoType *Proto
3714 = Def->getType()->getAs<FunctionProtoType>();
3715 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003716 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3717 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003718 }
Douglas Gregor46542412010-10-25 20:39:23 +00003719
3720 // If the function we're calling isn't a function prototype, but we have
3721 // a function prototype from a prior declaratiom, use that prototype.
3722 if (!FDecl->hasPrototype())
3723 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003724 }
3725
Steve Naroffb291ab62007-08-28 23:30:39 +00003726 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003727 for (unsigned i = 0; i != NumArgs; i++) {
3728 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003729
3730 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003731 InitializedEntity Entity
3732 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003733 Proto->getArgType(i),
3734 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003735 ExprResult ArgE = PerformCopyInitialization(Entity,
3736 SourceLocation(),
3737 Owned(Arg));
3738 if (ArgE.isInvalid())
3739 return true;
3740
3741 Arg = ArgE.takeAs<Expr>();
3742
3743 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003744 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3745
3746 if (ArgE.isInvalid())
3747 return true;
3748
3749 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003750 }
3751
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003752 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3753 Arg->getType(),
3754 PDiag(diag::err_call_incomplete_argument)
3755 << Arg->getSourceRange()))
3756 return ExprError();
3757
Chris Lattner925e60d2007-12-28 05:29:59 +00003758 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003759 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003760 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003761
Douglas Gregor88a35142008-12-22 05:46:06 +00003762 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3763 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003764 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3765 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003766
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003767 // Check for sentinels
3768 if (NDecl)
3769 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattner59907c42007-08-10 20:18:51 +00003771 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003772 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003773 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003774 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003775
John McCall8e10f3b2011-02-26 05:39:39 +00003776 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003777 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003778 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003779 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003780 return ExprError();
3781 }
Chris Lattner59907c42007-08-10 20:18:51 +00003782
John McCall9ae2f072010-08-23 23:25:46 +00003783 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003784}
3785
John McCall60d7b3a2010-08-24 06:29:42 +00003786ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003787Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003788 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003789 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003790 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003791 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003792
3793 TypeSourceInfo *TInfo;
3794 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3795 if (!TInfo)
3796 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3797
John McCall9ae2f072010-08-23 23:25:46 +00003798 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003799}
3800
John McCall60d7b3a2010-08-24 06:29:42 +00003801ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003802Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003803 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003804 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003805
Eli Friedman6223c222008-05-20 05:22:08 +00003806 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003807 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3808 PDiag(diag::err_illegal_decl_array_incomplete_type)
3809 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003810 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003811 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003812 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003813 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003814 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003815 } else if (!literalType->isDependentType() &&
3816 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003817 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003818 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003819 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003820 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003821
Douglas Gregor99a2e602009-12-16 01:38:02 +00003822 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003823 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003824 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003825 = InitializationKind::CreateCStyleCast(LParenLoc,
3826 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003827 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003828 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003829 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003830 &literalType);
3831 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003832 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003833 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003834
Chris Lattner371f2582008-12-04 23:50:19 +00003835 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003836 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003837 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003838 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003839 }
Eli Friedman08544622009-12-22 02:35:53 +00003840
John McCallf89e55a2010-11-18 06:31:45 +00003841 // In C, compound literals are l-values for some reason.
3842 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3843
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003844 return MaybeBindToTemporary(
3845 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003846 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003847}
3848
John McCall60d7b3a2010-08-24 06:29:42 +00003849ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00003850Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003851 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003852 unsigned NumInit = InitArgList.size();
3853 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003854
Steve Naroff08d92e42007-09-15 18:49:24 +00003855 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003856 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003857
Ted Kremenek709210f2010-04-13 23:39:13 +00003858 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3859 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003860 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003861 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003862}
3863
John McCalldc05b112011-09-10 01:16:55 +00003864/// Do an explicit extend of the given block pointer if we're in ARC.
3865static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3866 assert(E.get()->getType()->isBlockPointerType());
3867 assert(E.get()->isRValue());
3868
3869 // Only do this in an r-value context.
3870 if (!S.getLangOptions().ObjCAutoRefCount) return;
3871
3872 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00003873 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00003874 /*base path*/ 0, VK_RValue);
3875 S.ExprNeedsCleanups = true;
3876}
3877
3878/// Prepare a conversion of the given expression to an ObjC object
3879/// pointer type.
3880CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3881 QualType type = E.get()->getType();
3882 if (type->isObjCObjectPointerType()) {
3883 return CK_BitCast;
3884 } else if (type->isBlockPointerType()) {
3885 maybeExtendBlockObject(*this, E);
3886 return CK_BlockPointerToObjCPointerCast;
3887 } else {
3888 assert(type->isPointerType());
3889 return CK_CPointerToObjCPointerCast;
3890 }
3891}
3892
John McCallf3ea8cf2010-11-14 08:17:51 +00003893/// Prepares for a scalar cast, performing all the necessary stages
3894/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003895static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003896 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3897 // Also, callers should have filtered out the invalid cases with
3898 // pointers. Everything else should be possible.
3899
John Wiegley429bb272011-04-08 18:41:53 +00003900 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003901 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003902 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003903
John McCall1d9b3b22011-09-09 05:25:32 +00003904 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00003905 case Type::STK_MemberPointer:
3906 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003907
John McCall1d9b3b22011-09-09 05:25:32 +00003908 case Type::STK_CPointer:
3909 case Type::STK_BlockPointer:
3910 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003911 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003912 case Type::STK_CPointer:
3913 return CK_BitCast;
3914 case Type::STK_BlockPointer:
3915 return (SrcKind == Type::STK_BlockPointer
3916 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3917 case Type::STK_ObjCObjectPointer:
3918 if (SrcKind == Type::STK_ObjCObjectPointer)
3919 return CK_BitCast;
3920 else if (SrcKind == Type::STK_CPointer)
3921 return CK_CPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003922 else {
3923 maybeExtendBlockObject(S, Src);
John McCall1d9b3b22011-09-09 05:25:32 +00003924 return CK_BlockPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003925 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003926 case Type::STK_Bool:
3927 return CK_PointerToBoolean;
3928 case Type::STK_Integral:
3929 return CK_PointerToIntegral;
3930 case Type::STK_Floating:
3931 case Type::STK_FloatingComplex:
3932 case Type::STK_IntegralComplex:
3933 case Type::STK_MemberPointer:
3934 llvm_unreachable("illegal cast from pointer");
3935 }
3936 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003937
John McCalldaa8e4e2010-11-15 09:13:47 +00003938 case Type::STK_Bool: // casting from bool is like casting from an integer
3939 case Type::STK_Integral:
3940 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003941 case Type::STK_CPointer:
3942 case Type::STK_ObjCObjectPointer:
3943 case Type::STK_BlockPointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003944 if (Src.get()->isNullPointerConstant(S.Context,
3945 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003946 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003947 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003948 case Type::STK_Bool:
3949 return CK_IntegralToBoolean;
3950 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003951 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003952 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003953 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003954 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003955 Src = S.ImpCastExprToType(Src.take(),
3956 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003957 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003958 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003959 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003960 Src = S.ImpCastExprToType(Src.take(),
3961 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003962 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003963 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003964 case Type::STK_MemberPointer:
3965 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003966 }
3967 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003968
John McCalldaa8e4e2010-11-15 09:13:47 +00003969 case Type::STK_Floating:
3970 switch (DestTy->getScalarTypeKind()) {
3971 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003972 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003973 case Type::STK_Bool:
3974 return CK_FloatingToBoolean;
3975 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003976 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003977 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003978 Src = S.ImpCastExprToType(Src.take(),
3979 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003980 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003981 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003982 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003983 Src = S.ImpCastExprToType(Src.take(),
3984 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003985 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003986 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00003987 case Type::STK_CPointer:
3988 case Type::STK_ObjCObjectPointer:
3989 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003990 llvm_unreachable("valid float->pointer cast?");
3991 case Type::STK_MemberPointer:
3992 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003993 }
3994 break;
3995
John McCalldaa8e4e2010-11-15 09:13:47 +00003996 case Type::STK_FloatingComplex:
3997 switch (DestTy->getScalarTypeKind()) {
3998 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003999 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004000 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004001 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004002 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004003 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004004 if (S.Context.hasSameType(ET, DestTy))
4005 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00004006 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004007 return CK_FloatingCast;
4008 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004009 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004010 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004011 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00004012 Src = S.ImpCastExprToType(Src.take(),
4013 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00004014 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004015 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004016 case Type::STK_CPointer:
4017 case Type::STK_ObjCObjectPointer:
4018 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004019 llvm_unreachable("valid complex float->pointer cast?");
4020 case Type::STK_MemberPointer:
4021 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004022 }
4023 break;
4024
John McCalldaa8e4e2010-11-15 09:13:47 +00004025 case Type::STK_IntegralComplex:
4026 switch (DestTy->getScalarTypeKind()) {
4027 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004028 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004029 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004030 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004031 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004032 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004033 if (S.Context.hasSameType(ET, DestTy))
4034 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00004035 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004036 return CK_IntegralCast;
4037 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004038 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004039 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004040 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00004041 Src = S.ImpCastExprToType(Src.take(),
4042 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00004043 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004044 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004045 case Type::STK_CPointer:
4046 case Type::STK_ObjCObjectPointer:
4047 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004048 llvm_unreachable("valid complex int->pointer cast?");
4049 case Type::STK_MemberPointer:
4050 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004051 }
4052 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004053 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004054
John McCallf3ea8cf2010-11-14 08:17:51 +00004055 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004056}
4057
John McCallb45ae252011-10-05 07:41:44 +00004058/// CheckCastTypes - Check type constraints for casting between types in C.
4059ExprResult Sema::CheckCCastTypes(SourceLocation CastStartLoc,
4060 SourceRange TypeRange, QualType CastType,
4061 Expr *CastExpr, CastKind &Kind) {
4062 assert(!getLangOptions().CPlusPlus);
4063
4064 if (CastExpr->getType() == Context.UnknownAnyTy) {
4065 // We can safely ignore these here because C never has base paths
4066 // or casts to l-values.
4067 CXXCastPath BasePath;
4068 ExprValueKind VK = VK_RValue;
Richard Trieuccd891a2011-09-09 01:45:06 +00004069 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4070 BasePath);
John McCallb45ae252011-10-05 07:41:44 +00004071 }
John McCall1de4d4e2011-04-07 08:22:57 +00004072
John McCallb45ae252011-10-05 07:41:44 +00004073 ExprResult Result = CheckPlaceholderExpr(CastExpr);
4074 if (Result.isInvalid())
4075 return ExprError();
4076 CastExpr = Result.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004077
Richard Trieuccd891a2011-09-09 01:45:06 +00004078 assert(!CastExpr->getType()->isPlaceholderType());
John McCallfb8721c2011-04-10 19:13:55 +00004079
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004080 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4081 // type needs to be scalar.
Richard Trieuccd891a2011-09-09 01:45:06 +00004082 if (CastType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004083 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuccd891a2011-09-09 01:45:06 +00004084 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004085 if (castExprRes.isInvalid())
4086 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004087 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004088
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004089 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004090 Kind = CK_ToVoid;
Richard Trieuccd891a2011-09-09 01:45:06 +00004091 return Owned(CastExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004092 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004093
Richard Trieuccd891a2011-09-09 01:45:06 +00004094 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004095 if (castExprRes.isInvalid())
4096 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004097 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004098
Richard Trieuccd891a2011-09-09 01:45:06 +00004099 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedman8d438082010-07-17 20:43:49 +00004100 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004101 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004102
Richard Trieuccd891a2011-09-09 01:45:06 +00004103 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4104 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4105 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004106 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004107 // FIXME: Check that the cast destination type is complete.
Richard Trieuccd891a2011-09-09 01:45:06 +00004108 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4109 << CastType << CastExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004110 Kind = CK_NoOp;
Richard Trieuccd891a2011-09-09 01:45:06 +00004111 return Owned(CastExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004112 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004113
Richard Trieuccd891a2011-09-09 01:45:06 +00004114 if (CastType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004115 // GCC cast to union extension
Richard Trieuccd891a2011-09-09 01:45:06 +00004116 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004117 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004118 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004119 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004120 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004121 CastExpr->getType()) &&
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004122 !Field->isUnnamedBitfield()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004123 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4124 << CastExpr->getSourceRange();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004125 break;
4126 }
4127 }
John Wiegley429bb272011-04-08 18:41:53 +00004128 if (Field == FieldEnd) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004129 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4130 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004131 return ExprError();
4132 }
John McCall2de56d12010-08-25 11:45:40 +00004133 Kind = CK_ToUnion;
Richard Trieuccd891a2011-09-09 01:45:06 +00004134 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004135 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004136
Anders Carlssonc3516322009-10-16 02:48:28 +00004137 // Reject any other conversions to non-scalar types.
Richard Trieuccd891a2011-09-09 01:45:06 +00004138 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4139 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004140 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004141 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004142
John McCallf3ea8cf2010-11-14 08:17:51 +00004143 // The type we're casting to is known to be a scalar or vector.
4144
4145 // Require the operand to be a scalar or vector.
Richard Trieuccd891a2011-09-09 01:45:06 +00004146 if (!CastExpr->getType()->isScalarType() &&
4147 !CastExpr->getType()->isVectorType()) {
4148 Diag(CastExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004149 diag::err_typecheck_expect_scalar_operand)
Richard Trieuccd891a2011-09-09 01:45:06 +00004150 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004151 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004152 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004153
Richard Trieuccd891a2011-09-09 01:45:06 +00004154 if (CastType->isExtVectorType())
4155 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004156
Richard Trieuccd891a2011-09-09 01:45:06 +00004157 if (CastType->isVectorType()) {
4158 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsevd06fea82011-03-27 09:32:40 +00004159 VectorType::AltiVecVector &&
Richard Trieuccd891a2011-09-09 01:45:06 +00004160 (CastExpr->getType()->isIntegerType() ||
4161 CastExpr->getType()->isFloatingType())) {
Anton Yartsevd06fea82011-03-27 09:32:40 +00004162 Kind = CK_VectorSplat;
Richard Trieuccd891a2011-09-09 01:45:06 +00004163 return Owned(CastExpr);
4164 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4165 Kind)) {
John Wiegley429bb272011-04-08 18:41:53 +00004166 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004167 } else
Richard Trieuccd891a2011-09-09 01:45:06 +00004168 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004169 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004170 if (CastExpr->getType()->isVectorType()) {
4171 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley429bb272011-04-08 18:41:53 +00004172 return ExprError();
4173 else
Richard Trieuccd891a2011-09-09 01:45:06 +00004174 return Owned(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004175 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004176
John McCallf3ea8cf2010-11-14 08:17:51 +00004177 // The source and target types are both scalars, i.e.
4178 // - arithmetic types (fundamental, enum, and complex)
4179 // - all kinds of pointers
4180 // Note that member pointers were filtered out with C++, above.
4181
Richard Trieuccd891a2011-09-09 01:45:06 +00004182 if (isa<ObjCSelectorExpr>(CastExpr)) {
4183 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley429bb272011-04-08 18:41:53 +00004184 return ExprError();
4185 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004186
John McCallf3ea8cf2010-11-14 08:17:51 +00004187 // If either type is a pointer, the other type has to be either an
4188 // integer or a pointer.
Richard Trieuccd891a2011-09-09 01:45:06 +00004189 QualType CastExprType = CastExpr->getType();
4190 if (!CastType->isArithmeticType()) {
4191 if (!CastExprType->isIntegralType(Context) &&
4192 CastExprType->isArithmeticType()) {
4193 Diag(CastExpr->getLocStart(),
John Wiegley429bb272011-04-08 18:41:53 +00004194 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuccd891a2011-09-09 01:45:06 +00004195 << CastExprType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004196 return ExprError();
4197 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004198 } else if (!CastExpr->getType()->isArithmeticType()) {
4199 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4200 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4201 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004202 return ExprError();
4203 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004204 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004205
John McCallb45ae252011-10-05 07:41:44 +00004206 // ARC imposes extra restrictions on casts.
John McCallf85e1932011-06-15 23:02:42 +00004207 if (getLangOptions().ObjCAutoRefCount) {
John McCallb45ae252011-10-05 07:41:44 +00004208 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
Richard Trieuccd891a2011-09-09 01:45:06 +00004209 CastType, CastExpr, CCK_CStyleCast);
John McCallf85e1932011-06-15 23:02:42 +00004210
Richard Trieuccd891a2011-09-09 01:45:06 +00004211 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4212 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCallf85e1932011-06-15 23:02:42 +00004213 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4214 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4215 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4216 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4217 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004218 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004219 diag::err_typecheck_incompatible_ownership)
Richard Trieuccd891a2011-09-09 01:45:06 +00004220 << CastExprType << CastType << AA_Casting
4221 << CastExpr->getSourceRange();
John McCallf85e1932011-06-15 23:02:42 +00004222
4223 return ExprError();
4224 }
4225 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004226 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004227 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4228 Diag(CastExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004229 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuccd891a2011-09-09 01:45:06 +00004230 << CastExprType << CastType
4231 << CastExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004232 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004233 }
4234 }
4235
Richard Trieuccd891a2011-09-09 01:45:06 +00004236 castExprRes = Owned(CastExpr);
4237 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley429bb272011-04-08 18:41:53 +00004238 if (castExprRes.isInvalid())
4239 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004240 CastExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004241
John McCallf3ea8cf2010-11-14 08:17:51 +00004242 if (Kind == CK_BitCast)
Richard Trieuccd891a2011-09-09 01:45:06 +00004243 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCallb7f4ffe2010-08-12 21:44:57 +00004244
Richard Trieuccd891a2011-09-09 01:45:06 +00004245 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004246}
4247
Anders Carlssonc3516322009-10-16 02:48:28 +00004248bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004249 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004250 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004251
Anders Carlssona64db8f2007-11-27 05:51:55 +00004252 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004253 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004254 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004255 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004256 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004257 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004258 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004259 } else
4260 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004261 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004262 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004263
John McCall2de56d12010-08-25 11:45:40 +00004264 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004265 return false;
4266}
4267
John Wiegley429bb272011-04-08 18:41:53 +00004268ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4269 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004270 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004271
Anders Carlsson16a89042009-10-16 05:23:41 +00004272 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004273
Nate Begeman9b10da62009-06-27 22:05:55 +00004274 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4275 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004276 // In OpenCL, casts between vectors of different types are not allowed.
4277 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004278 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004279 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4280 || (getLangOptions().OpenCL &&
4281 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004282 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004283 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004284 return ExprError();
4285 }
John McCall2de56d12010-08-25 11:45:40 +00004286 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004287 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004288 }
4289
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004290 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004291 // conversion will take place first from scalar to elt type, and then
4292 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004293 if (SrcTy->isPointerType())
4294 return Diag(R.getBegin(),
4295 diag::err_invalid_conversion_between_vector_and_scalar)
4296 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004297
4298 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004299 ExprResult CastExprRes = Owned(CastExpr);
4300 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4301 if (CastExprRes.isInvalid())
4302 return ExprError();
4303 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004304
John McCall2de56d12010-08-25 11:45:40 +00004305 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004306 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004307}
4308
John McCall60d7b3a2010-08-24 06:29:42 +00004309ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004310Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4311 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004312 SourceLocation RParenLoc, Expr *CastExpr) {
4313 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004314 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004315
Richard Trieuccd891a2011-09-09 01:45:06 +00004316 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004317 if (D.isInvalidType())
4318 return ExprError();
4319
4320 if (getLangOptions().CPlusPlus) {
4321 // Check that there are no default arguments (C++ only).
4322 CheckExtraCXXDefaultArguments(D);
4323 }
4324
John McCalle82247a2011-10-01 05:17:03 +00004325 checkUnusedDeclAttributes(D);
4326
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004327 QualType castType = castTInfo->getType();
4328 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004330 bool isVectorLiteral = false;
4331
4332 // Check for an altivec or OpenCL literal,
4333 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004334 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4335 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser37c31c22011-09-21 18:28:29 +00004336 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4337 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004338 if (PLE && PLE->getNumExprs() == 0) {
4339 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4340 return ExprError();
4341 }
4342 if (PE || PLE->getNumExprs() == 1) {
4343 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4344 if (!E->getType()->isVectorType())
4345 isVectorLiteral = true;
4346 }
4347 else
4348 isVectorLiteral = true;
4349 }
4350
4351 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4352 // then handle it as such.
4353 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004354 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004355
Nate Begeman2ef13e52009-08-10 23:49:36 +00004356 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004357 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4358 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004359 if (isa<ParenListExpr>(CastExpr)) {
4360 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004361 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004362 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004363 }
John McCallb042fdf2010-01-15 18:56:44 +00004364
Richard Trieuccd891a2011-09-09 01:45:06 +00004365 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004366}
4367
John McCall60d7b3a2010-08-24 06:29:42 +00004368ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004369Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004370 SourceLocation RParenLoc, Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00004371 if (getLangOptions().CPlusPlus)
4372 return CXXBuildCStyleCastExpr(LParenLoc, Ty, RParenLoc, CastExpr);
4373
John McCalldaa8e4e2010-11-15 09:13:47 +00004374 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00004375 ExprResult CastResult =
John McCallb45ae252011-10-05 07:41:44 +00004376 CheckCCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc),
4377 Ty->getType(), CastExpr, Kind);
John Wiegley429bb272011-04-08 18:41:53 +00004378 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004379 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004380 CastExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004381
John McCallb45ae252011-10-05 07:41:44 +00004382 return Owned(CStyleCastExpr::Create(Context, Ty->getType(), VK_RValue, Kind,
4383 CastExpr, /*base path*/ 0, Ty,
4384 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004385}
4386
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004387ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4388 SourceLocation RParenLoc, Expr *E,
4389 TypeSourceInfo *TInfo) {
4390 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4391 "Expected paren or paren list expression");
4392
4393 Expr **exprs;
4394 unsigned numExprs;
4395 Expr *subExpr;
4396 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4397 exprs = PE->getExprs();
4398 numExprs = PE->getNumExprs();
4399 } else {
4400 subExpr = cast<ParenExpr>(E)->getSubExpr();
4401 exprs = &subExpr;
4402 numExprs = 1;
4403 }
4404
4405 QualType Ty = TInfo->getType();
4406 assert(Ty->isVectorType() && "Expected vector type");
4407
Chris Lattner5f9e2722011-07-23 10:55:15 +00004408 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004409 const VectorType *VTy = Ty->getAs<VectorType>();
4410 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4411
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004412 // '(...)' form of vector initialization in AltiVec: the number of
4413 // initializers must be one or must match the size of the vector.
4414 // If a single value is specified in the initializer then it will be
4415 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004416 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004417 // The number of initializers must be one or must match the size of the
4418 // vector. If a single value is specified in the initializer then it will
4419 // be replicated to all the components of the vector
4420 if (numExprs == 1) {
4421 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4422 ExprResult Literal = Owned(exprs[0]);
4423 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4424 PrepareScalarCast(*this, Literal, ElemTy));
4425 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4426 }
4427 else if (numExprs < numElems) {
4428 Diag(E->getExprLoc(),
4429 diag::err_incorrect_number_of_vector_initializers);
4430 return ExprError();
4431 }
4432 else
4433 for (unsigned i = 0, e = numExprs; i != e; ++i)
4434 initExprs.push_back(exprs[i]);
4435 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004436 else {
4437 // For OpenCL, when the number of initializers is a single value,
4438 // it will be replicated to all components of the vector.
4439 if (getLangOptions().OpenCL &&
4440 VTy->getVectorKind() == VectorType::GenericVector &&
4441 numExprs == 1) {
4442 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4443 ExprResult Literal = Owned(exprs[0]);
4444 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4445 PrepareScalarCast(*this, Literal, ElemTy));
4446 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4447 }
4448
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004449 for (unsigned i = 0, e = numExprs; i != e; ++i)
4450 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004451 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004452 // FIXME: This means that pretty-printing the final AST will produce curly
4453 // braces instead of the original commas.
4454 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4455 &initExprs[0],
4456 initExprs.size(), RParenLoc);
4457 initE->setType(Ty);
4458 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4459}
4460
Nate Begeman2ef13e52009-08-10 23:49:36 +00004461/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4462/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004463ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004464Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4465 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004466 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004467 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004468
John McCall60d7b3a2010-08-24 06:29:42 +00004469 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Nate Begeman2ef13e52009-08-10 23:49:36 +00004471 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004472 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4473 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004474
John McCall9ae2f072010-08-23 23:25:46 +00004475 if (Result.isInvalid()) return ExprError();
4476
4477 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004478}
4479
John McCall60d7b3a2010-08-24 06:29:42 +00004480ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004481 SourceLocation R,
4482 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004483 unsigned nexprs = Val.size();
4484 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004485 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4486 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004487 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004488 expr = new (Context) ParenExpr(L, R, exprs[0]);
4489 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004490 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4491 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004492 return Owned(expr);
4493}
4494
Chandler Carruth82214a82011-02-18 23:54:50 +00004495/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004496/// constant and the other is not a pointer. Returns true if a diagnostic is
4497/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004498bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004499 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004500 Expr *NullExpr = LHSExpr;
4501 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004502 Expr::NullPointerConstantKind NullKind =
4503 NullExpr->isNullPointerConstant(Context,
4504 Expr::NPC_ValueDependentIsNotNull);
4505
4506 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004507 NullExpr = RHSExpr;
4508 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004509 NullKind =
4510 NullExpr->isNullPointerConstant(Context,
4511 Expr::NPC_ValueDependentIsNotNull);
4512 }
4513
4514 if (NullKind == Expr::NPCK_NotNull)
4515 return false;
4516
4517 if (NullKind == Expr::NPCK_ZeroInteger) {
4518 // In this case, check to make sure that we got here from a "NULL"
4519 // string in the source code.
4520 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004521 SourceLocation loc = NullExpr->getExprLoc();
4522 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004523 return false;
4524 }
4525
4526 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4527 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4528 << NonPointerExpr->getType() << DiagType
4529 << NonPointerExpr->getSourceRange();
4530 return true;
4531}
4532
Richard Trieu26f96072011-09-02 01:51:02 +00004533/// \brief Return false if the condition expression is valid, true otherwise.
4534static bool checkCondition(Sema &S, Expr *Cond) {
4535 QualType CondTy = Cond->getType();
4536
4537 // C99 6.5.15p2
4538 if (CondTy->isScalarType()) return false;
4539
4540 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4541 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4542 return false;
4543
4544 // Emit the proper error message.
4545 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4546 diag::err_typecheck_cond_expect_scalar :
4547 diag::err_typecheck_cond_expect_scalar_or_vector)
4548 << CondTy;
4549 return true;
4550}
4551
4552/// \brief Return false if the two expressions can be converted to a vector,
4553/// true otherwise
4554static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4555 ExprResult &RHS,
4556 QualType CondTy) {
4557 // Both operands should be of scalar type.
4558 if (!LHS.get()->getType()->isScalarType()) {
4559 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4560 << CondTy;
4561 return true;
4562 }
4563 if (!RHS.get()->getType()->isScalarType()) {
4564 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4565 << CondTy;
4566 return true;
4567 }
4568
4569 // Implicity convert these scalars to the type of the condition.
4570 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4571 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4572 return false;
4573}
4574
4575/// \brief Handle when one or both operands are void type.
4576static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4577 ExprResult &RHS) {
4578 Expr *LHSExpr = LHS.get();
4579 Expr *RHSExpr = RHS.get();
4580
4581 if (!LHSExpr->getType()->isVoidType())
4582 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4583 << RHSExpr->getSourceRange();
4584 if (!RHSExpr->getType()->isVoidType())
4585 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4586 << LHSExpr->getSourceRange();
4587 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4588 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4589 return S.Context.VoidTy;
4590}
4591
4592/// \brief Return false if the NullExpr can be promoted to PointerTy,
4593/// true otherwise.
4594static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4595 QualType PointerTy) {
4596 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4597 !NullExpr.get()->isNullPointerConstant(S.Context,
4598 Expr::NPC_ValueDependentIsNull))
4599 return true;
4600
4601 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4602 return false;
4603}
4604
4605/// \brief Checks compatibility between two pointers and return the resulting
4606/// type.
4607static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4608 ExprResult &RHS,
4609 SourceLocation Loc) {
4610 QualType LHSTy = LHS.get()->getType();
4611 QualType RHSTy = RHS.get()->getType();
4612
4613 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4614 // Two identical pointers types are always compatible.
4615 return LHSTy;
4616 }
4617
4618 QualType lhptee, rhptee;
4619
4620 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004621 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4622 lhptee = LHSBTy->getPointeeType();
4623 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004624 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004625 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4626 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004627 }
4628
4629 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4630 rhptee.getUnqualifiedType())) {
4631 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4632 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4633 << RHS.get()->getSourceRange();
4634 // In this situation, we assume void* type. No especially good
4635 // reason, but this is what gcc does, and we do have to pick
4636 // to get a consistent AST.
4637 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4638 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4639 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4640 return incompatTy;
4641 }
4642
4643 // The pointer types are compatible.
4644 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4645 // differently qualified versions of compatible types, the result type is
4646 // a pointer to an appropriately qualified version of the *composite*
4647 // type.
4648 // FIXME: Need to calculate the composite type.
4649 // FIXME: Need to add qualifiers
4650
4651 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4652 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4653 return LHSTy;
4654}
4655
4656/// \brief Return the resulting type when the operands are both block pointers.
4657static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4658 ExprResult &LHS,
4659 ExprResult &RHS,
4660 SourceLocation Loc) {
4661 QualType LHSTy = LHS.get()->getType();
4662 QualType RHSTy = RHS.get()->getType();
4663
4664 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4665 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4666 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4667 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4668 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4669 return destType;
4670 }
4671 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4672 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4673 << RHS.get()->getSourceRange();
4674 return QualType();
4675 }
4676
4677 // We have 2 block pointer types.
4678 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4679}
4680
4681/// \brief Return the resulting type when the operands are both pointers.
4682static QualType
4683checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4684 ExprResult &RHS,
4685 SourceLocation Loc) {
4686 // get the pointer types
4687 QualType LHSTy = LHS.get()->getType();
4688 QualType RHSTy = RHS.get()->getType();
4689
4690 // get the "pointed to" types
4691 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4692 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4693
4694 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4695 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4696 // Figure out necessary qualifiers (C99 6.5.15p6)
4697 QualType destPointee
4698 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4699 QualType destType = S.Context.getPointerType(destPointee);
4700 // Add qualifiers if necessary.
4701 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4702 // Promote to void*.
4703 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4704 return destType;
4705 }
4706 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4707 QualType destPointee
4708 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4709 QualType destType = S.Context.getPointerType(destPointee);
4710 // Add qualifiers if necessary.
4711 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4712 // Promote to void*.
4713 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4714 return destType;
4715 }
4716
4717 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4718}
4719
4720/// \brief Return false if the first expression is not an integer and the second
4721/// expression is not a pointer, true otherwise.
4722static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4723 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004724 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004725 if (!PointerExpr->getType()->isPointerType() ||
4726 !Int.get()->getType()->isIntegerType())
4727 return false;
4728
Richard Trieuccd891a2011-09-09 01:45:06 +00004729 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4730 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004731
4732 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4733 << Expr1->getType() << Expr2->getType()
4734 << Expr1->getSourceRange() << Expr2->getSourceRange();
4735 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4736 CK_IntegralToPointer);
4737 return true;
4738}
4739
Richard Trieu33fc7572011-09-06 20:06:39 +00004740/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4741/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004742/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004743QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4744 ExprResult &RHS, ExprValueKind &VK,
4745 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004746 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004747
Richard Trieu33fc7572011-09-06 20:06:39 +00004748 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4749 if (!LHSResult.isUsable()) return QualType();
4750 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004751
Richard Trieu33fc7572011-09-06 20:06:39 +00004752 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4753 if (!RHSResult.isUsable()) return QualType();
4754 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004755
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004756 // C++ is sufficiently different to merit its own checker.
4757 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004758 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004759
4760 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004761 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004762
John Wiegley429bb272011-04-08 18:41:53 +00004763 Cond = UsualUnaryConversions(Cond.take());
4764 if (Cond.isInvalid())
4765 return QualType();
4766 LHS = UsualUnaryConversions(LHS.take());
4767 if (LHS.isInvalid())
4768 return QualType();
4769 RHS = UsualUnaryConversions(RHS.take());
4770 if (RHS.isInvalid())
4771 return QualType();
4772
4773 QualType CondTy = Cond.get()->getType();
4774 QualType LHSTy = LHS.get()->getType();
4775 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004776
Reid Spencer5f016e22007-07-11 17:01:13 +00004777 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004778 if (checkCondition(*this, Cond.get()))
4779 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004780
Chris Lattner70d67a92008-01-06 22:42:25 +00004781 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004782 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004783 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004784
Nate Begeman6155d732010-09-20 22:41:17 +00004785 // OpenCL: If the condition is a vector, and both operands are scalar,
4786 // attempt to implicity convert them to the vector type to act like the
4787 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004788 if (getLangOptions().OpenCL && CondTy->isVectorType())
4789 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004790 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004791
Chris Lattner70d67a92008-01-06 22:42:25 +00004792 // If both operands have arithmetic type, do the usual arithmetic conversions
4793 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004794 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4795 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004796 if (LHS.isInvalid() || RHS.isInvalid())
4797 return QualType();
4798 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004799 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004800
Chris Lattner70d67a92008-01-06 22:42:25 +00004801 // If both operands are the same structure or union type, the result is that
4802 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004803 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4804 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004805 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004806 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004807 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004808 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004809 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004810 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004811
Chris Lattner70d67a92008-01-06 22:42:25 +00004812 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004813 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004814 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004815 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004816 }
Richard Trieu26f96072011-09-02 01:51:02 +00004817
Steve Naroffb6d54e52008-01-08 01:11:38 +00004818 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4819 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004820 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4821 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004822
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004823 // All objective-c pointer type analysis is done here.
4824 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4825 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004826 if (LHS.isInvalid() || RHS.isInvalid())
4827 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004828 if (!compositeType.isNull())
4829 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004830
4831
Steve Naroff7154a772009-07-01 14:36:47 +00004832 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004833 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4834 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4835 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004836
Steve Naroff7154a772009-07-01 14:36:47 +00004837 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004838 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4839 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4840 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004841
John McCall404cd162010-11-13 01:35:44 +00004842 // GCC compatibility: soften pointer/integer mismatch. Note that
4843 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004844 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4845 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004846 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004847 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4848 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004849 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004850
Chandler Carruth82214a82011-02-18 23:54:50 +00004851 // Emit a better diagnostic if one of the expressions is a null pointer
4852 // constant and the other is not a pointer type. In this case, the user most
4853 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004854 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004855 return QualType();
4856
Chris Lattner70d67a92008-01-06 22:42:25 +00004857 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004858 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004859 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4860 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004861 return QualType();
4862}
4863
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004864/// FindCompositeObjCPointerType - Helper method to find composite type of
4865/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004866QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004867 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004868 QualType LHSTy = LHS.get()->getType();
4869 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004870
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004871 // Handle things like Class and struct objc_class*. Here we case the result
4872 // to the pseudo-builtin, because that will be implicitly cast back to the
4873 // redefinition type if an attempt is made to access its fields.
4874 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004875 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004876 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004877 return LHSTy;
4878 }
4879 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004880 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004881 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004882 return RHSTy;
4883 }
4884 // And the same for struct objc_object* / id
4885 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004886 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004887 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004888 return LHSTy;
4889 }
4890 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004891 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004892 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004893 return RHSTy;
4894 }
4895 // And the same for struct objc_selector* / SEL
4896 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004897 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004898 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004899 return LHSTy;
4900 }
4901 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004902 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004903 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004904 return RHSTy;
4905 }
4906 // Check constraints for Objective-C object pointers types.
4907 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004908
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004909 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4910 // Two identical object pointer types are always compatible.
4911 return LHSTy;
4912 }
John McCall1d9b3b22011-09-09 05:25:32 +00004913 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4914 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004915 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004916
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004917 // If both operands are interfaces and either operand can be
4918 // assigned to the other, use that type as the composite
4919 // type. This allows
4920 // xxx ? (A*) a : (B*) b
4921 // where B is a subclass of A.
4922 //
4923 // Additionally, as for assignment, if either type is 'id'
4924 // allow silent coercion. Finally, if the types are
4925 // incompatible then make sure to use 'id' as the composite
4926 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004927
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004928 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4929 // It could return the composite type.
4930 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4931 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4932 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4933 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4934 } else if ((LHSTy->isObjCQualifiedIdType() ||
4935 RHSTy->isObjCQualifiedIdType()) &&
4936 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4937 // Need to handle "id<xx>" explicitly.
4938 // GCC allows qualified id and any Objective-C type to devolve to
4939 // id. Currently localizing to here until clear this should be
4940 // part of ObjCQualifiedIdTypesAreCompatible.
4941 compositeType = Context.getObjCIdType();
4942 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4943 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004944 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004945 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4946 ;
4947 else {
4948 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4949 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004950 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004951 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004952 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4953 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004954 return incompatTy;
4955 }
4956 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004957 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4958 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004959 return compositeType;
4960 }
4961 // Check Objective-C object pointer types and 'void *'
4962 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4963 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4964 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4965 QualType destPointee
4966 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4967 QualType destType = Context.getPointerType(destPointee);
4968 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004969 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004970 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004971 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004972 return destType;
4973 }
4974 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4975 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4976 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4977 QualType destPointee
4978 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4979 QualType destType = Context.getPointerType(destPointee);
4980 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004981 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004982 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004983 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004984 return destType;
4985 }
4986 return QualType();
4987}
4988
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004989/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004990/// ParenRange in parentheses.
4991static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004992 const PartialDiagnostic &Note,
4993 SourceRange ParenRange) {
4994 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4995 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4996 EndLoc.isValid()) {
4997 Self.Diag(Loc, Note)
4998 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4999 << FixItHint::CreateInsertion(EndLoc, ")");
5000 } else {
5001 // We can't display the parentheses, so just show the bare note.
5002 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005003 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005004}
5005
5006static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5007 return Opc >= BO_Mul && Opc <= BO_Shr;
5008}
5009
Hans Wennborg2f072b42011-06-09 17:06:51 +00005010/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5011/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005012/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5013/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005014static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005015 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005016 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5017 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005018 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005019 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005020
5021 // Built-in binary operator.
5022 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5023 if (IsArithmeticOp(OP->getOpcode())) {
5024 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005025 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005026 return true;
5027 }
5028 }
5029
5030 // Overloaded operator.
5031 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5032 if (Call->getNumArgs() != 2)
5033 return false;
5034
5035 // Make sure this is really a binary operator that is safe to pass into
5036 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5037 OverloadedOperatorKind OO = Call->getOperator();
5038 if (OO < OO_Plus || OO > OO_Arrow)
5039 return false;
5040
5041 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5042 if (IsArithmeticOp(OpKind)) {
5043 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005044 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005045 return true;
5046 }
5047 }
5048
5049 return false;
5050}
5051
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005052static bool IsLogicOp(BinaryOperatorKind Opc) {
5053 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5054}
5055
Hans Wennborg2f072b42011-06-09 17:06:51 +00005056/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5057/// or is a logical expression such as (x==y) which has int type, but is
5058/// commonly interpreted as boolean.
5059static bool ExprLooksBoolean(Expr *E) {
5060 E = E->IgnoreParenImpCasts();
5061
5062 if (E->getType()->isBooleanType())
5063 return true;
5064 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5065 return IsLogicOp(OP->getOpcode());
5066 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5067 return OP->getOpcode() == UO_LNot;
5068
5069 return false;
5070}
5071
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005072/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5073/// and binary operator are mixed in a way that suggests the programmer assumed
5074/// the conditional operator has higher precedence, for example:
5075/// "int x = a + someBinaryCondition ? 1 : 2".
5076static void DiagnoseConditionalPrecedence(Sema &Self,
5077 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005078 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005079 Expr *LHSExpr,
5080 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005081 BinaryOperatorKind CondOpcode;
5082 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005083
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005084 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005085 return;
5086 if (!ExprLooksBoolean(CondRHS))
5087 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005088
Hans Wennborg2f072b42011-06-09 17:06:51 +00005089 // The condition is an arithmetic binary expression, with a right-
5090 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005091
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005092 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005093 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005094 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005095
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005096 SuggestParentheses(Self, OpLoc,
5097 Self.PDiag(diag::note_precedence_conditional_silence)
5098 << BinaryOperator::getOpcodeStr(CondOpcode),
5099 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005100
5101 SuggestParentheses(Self, OpLoc,
5102 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005103 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005104}
5105
Steve Narofff69936d2007-09-16 03:34:24 +00005106/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005107/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005108ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005109 SourceLocation ColonLoc,
5110 Expr *CondExpr, Expr *LHSExpr,
5111 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005112 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5113 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005114 OpaqueValueExpr *opaqueValue = 0;
5115 Expr *commonExpr = 0;
5116 if (LHSExpr == 0) {
5117 commonExpr = CondExpr;
5118
5119 // We usually want to apply unary conversions *before* saving, except
5120 // in the special case of a C++ l-value conditional.
5121 if (!(getLangOptions().CPlusPlus
5122 && !commonExpr->isTypeDependent()
5123 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5124 && commonExpr->isGLValue()
5125 && commonExpr->isOrdinaryOrBitFieldObject()
5126 && RHSExpr->isOrdinaryOrBitFieldObject()
5127 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005128 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5129 if (commonRes.isInvalid())
5130 return ExprError();
5131 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005132 }
5133
5134 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5135 commonExpr->getType(),
5136 commonExpr->getValueKind(),
5137 commonExpr->getObjectKind());
5138 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005139 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005140
John McCallf89e55a2010-11-18 06:31:45 +00005141 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005142 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005143 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5144 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005145 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005146 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5147 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005148 return ExprError();
5149
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005150 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5151 RHS.get());
5152
John McCall56ca35d2011-02-17 10:25:35 +00005153 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005154 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5155 LHS.take(), ColonLoc,
5156 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005157
5158 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005159 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005160 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5161 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005162}
5163
John McCalle4be87e2011-01-31 23:13:11 +00005164// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005165// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005166// routine is it effectively iqnores the qualifiers on the top level pointee.
5167// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5168// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005169static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005170checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5171 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5172 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005173
Reid Spencer5f016e22007-07-11 17:01:13 +00005174 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005175 const Type *lhptee, *rhptee;
5176 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005177 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5178 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005179
John McCalle4be87e2011-01-31 23:13:11 +00005180 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005181
5182 // C99 6.5.16.1p1: This following citation is common to constraints
5183 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5184 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005185 Qualifiers lq;
5186
John McCallf85e1932011-06-15 23:02:42 +00005187 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5188 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5189 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5190 // Ignore lifetime for further calculation.
5191 lhq.removeObjCLifetime();
5192 rhq.removeObjCLifetime();
5193 }
5194
John McCall86c05f32011-02-01 00:10:29 +00005195 if (!lhq.compatiblyIncludes(rhq)) {
5196 // Treat address-space mismatches as fatal. TODO: address subspaces
5197 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5198 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5199
John McCallf85e1932011-06-15 23:02:42 +00005200 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005201 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005202 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5203 .compatiblyIncludes(
5204 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005205 && (lhptee->isVoidType() || rhptee->isVoidType()))
5206 ; // keep old
5207
John McCallf85e1932011-06-15 23:02:42 +00005208 // Treat lifetime mismatches as fatal.
5209 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5210 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5211
John McCall86c05f32011-02-01 00:10:29 +00005212 // For GCC compatibility, other qualifier mismatches are treated
5213 // as still compatible in C.
5214 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5215 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005216
Mike Stumpeed9cac2009-02-19 03:04:26 +00005217 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5218 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005219 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005220 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005221 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005222 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005223
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005224 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005225 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005226 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005227 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005228
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005229 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005230 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005231 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005232
5233 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005234 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005235 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005236 }
John McCall86c05f32011-02-01 00:10:29 +00005237
Mike Stumpeed9cac2009-02-19 03:04:26 +00005238 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005239 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005240 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5241 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005242 // Check if the pointee types are compatible ignoring the sign.
5243 // We explicitly check for char so that we catch "char" vs
5244 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005245 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005246 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005247 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005248 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005249
Chris Lattner6a2b9262009-10-17 20:33:28 +00005250 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005251 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005252 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005253 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005254
John McCall86c05f32011-02-01 00:10:29 +00005255 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005256 // Types are compatible ignoring the sign. Qualifier incompatibility
5257 // takes priority over sign incompatibility because the sign
5258 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005259 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005260 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005261
John McCalle4be87e2011-01-31 23:13:11 +00005262 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005263 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005264
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005265 // If we are a multi-level pointer, it's possible that our issue is simply
5266 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5267 // the eventual target type is the same and the pointers have the same
5268 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005269 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005270 do {
John McCall86c05f32011-02-01 00:10:29 +00005271 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5272 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005273 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005274
John McCall86c05f32011-02-01 00:10:29 +00005275 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005276 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005277 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005278
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005279 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005280 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005281 }
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005282 if (!S.getLangOptions().CPlusPlus &&
5283 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5284 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005285 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005286}
5287
John McCalle4be87e2011-01-31 23:13:11 +00005288/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005289/// block pointer types are compatible or whether a block and normal pointer
5290/// are compatible. It is more restrict than comparing two function pointer
5291// types.
John McCalle4be87e2011-01-31 23:13:11 +00005292static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005293checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5294 QualType RHSType) {
5295 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5296 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005297
Steve Naroff1c7d0672008-09-04 15:10:53 +00005298 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005299
Steve Naroff1c7d0672008-09-04 15:10:53 +00005300 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005301 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5302 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005303
John McCalle4be87e2011-01-31 23:13:11 +00005304 // In C++, the types have to match exactly.
5305 if (S.getLangOptions().CPlusPlus)
5306 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005307
John McCalle4be87e2011-01-31 23:13:11 +00005308 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005309
Steve Naroff1c7d0672008-09-04 15:10:53 +00005310 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005311 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5312 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005313
Richard Trieu1da27a12011-09-06 20:21:22 +00005314 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005315 return Sema::IncompatibleBlockPointer;
5316
Steve Naroff1c7d0672008-09-04 15:10:53 +00005317 return ConvTy;
5318}
5319
John McCalle4be87e2011-01-31 23:13:11 +00005320/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005321/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005322static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005323checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5324 QualType RHSType) {
5325 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5326 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005327
Richard Trieu1da27a12011-09-06 20:21:22 +00005328 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005329 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005330 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5331 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005332 return Sema::IncompatiblePointer;
5333 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005334 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005335 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005336 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5337 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005338 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005339 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005340 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005341 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5342 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005343
John McCalle4be87e2011-01-31 23:13:11 +00005344 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5345 return Sema::CompatiblePointerDiscardsQualifiers;
5346
Richard Trieu1da27a12011-09-06 20:21:22 +00005347 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005348 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005349 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005350 return Sema::IncompatibleObjCQualifiedId;
5351 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005352}
5353
John McCall1c23e912010-11-16 02:32:08 +00005354Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005355Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005356 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005357 // Fake up an opaque expression. We don't actually care about what
5358 // cast operations are required, so if CheckAssignmentConstraints
5359 // adds casts to this they'll be wasted, but fortunately that doesn't
5360 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005361 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5362 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005363 CastKind K = CK_Invalid;
5364
Richard Trieu1da27a12011-09-06 20:21:22 +00005365 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005366}
5367
Mike Stumpeed9cac2009-02-19 03:04:26 +00005368/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5369/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005370/// pointers. Here are some objectionable examples that GCC considers warnings:
5371///
5372/// int a, *pint;
5373/// short *pshort;
5374/// struct foo *pfoo;
5375///
5376/// pint = pshort; // warning: assignment from incompatible pointer type
5377/// a = pint; // warning: assignment makes integer from pointer without a cast
5378/// pint = a; // warning: assignment makes pointer from integer without a cast
5379/// pint = pfoo; // warning: assignment from incompatible pointer type
5380///
5381/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005382/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005383///
John McCalldaa8e4e2010-11-15 09:13:47 +00005384/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005385Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005386Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005387 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005388 QualType RHSType = RHS.get()->getType();
5389 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005390
Chris Lattnerfc144e22008-01-04 23:18:45 +00005391 // Get canonical types. We're not formatting these types, just comparing
5392 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005393 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5394 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005395
John McCallb6cfa242011-01-31 22:28:28 +00005396 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005397 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005398 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005399 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005400 }
5401
Douglas Gregor9d293df2008-10-28 00:22:11 +00005402 // If the left-hand side is a reference type, then we are in a
5403 // (rare!) case where we've allowed the use of references in C,
5404 // e.g., as a parameter type in a built-in function. In this case,
5405 // just make sure that the type referenced is compatible with the
5406 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005407 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005408 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005409 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5410 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005411 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005412 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005413 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005414 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005415 }
John McCallb6cfa242011-01-31 22:28:28 +00005416
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005417 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5418 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005419 if (LHSType->isExtVectorType()) {
5420 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005421 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005422 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005423 // CK_VectorSplat does T -> vector T, so first cast to the
5424 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005425 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5426 if (elType != RHSType) {
5427 Kind = PrepareScalarCast(*this, RHS, elType);
5428 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005429 }
5430 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005431 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005432 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005433 }
Mike Stump1eb44332009-09-09 15:08:12 +00005434
John McCallb6cfa242011-01-31 22:28:28 +00005435 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005436 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5437 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005438 // Allow assignments of an AltiVec vector type to an equivalent GCC
5439 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005440 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005441 Kind = CK_BitCast;
5442 return Compatible;
5443 }
5444
Douglas Gregor255210e2010-08-06 10:14:59 +00005445 // If we are allowing lax vector conversions, and LHS and RHS are both
5446 // vectors, the total size only needs to be the same. This is a bitcast;
5447 // no bits are changed but the result type is different.
5448 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005449 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005450 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005451 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005452 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005453 }
5454 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005455 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005456
John McCallb6cfa242011-01-31 22:28:28 +00005457 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005458 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5459 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5460 Kind = PrepareScalarCast(*this, RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005461 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005462 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005463
John McCallb6cfa242011-01-31 22:28:28 +00005464 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005465 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005466 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005467 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005468 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005469 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005470 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005471
John McCallb6cfa242011-01-31 22:28:28 +00005472 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005473 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005474 Kind = CK_IntegralToPointer; // FIXME: null?
5475 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005476 }
John McCallb6cfa242011-01-31 22:28:28 +00005477
5478 // C pointers are not compatible with ObjC object pointers,
5479 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005480 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005481 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005482 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005483 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005484 return Compatible;
5485 }
5486
5487 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005488 if (RHSType->isObjCClassType() &&
5489 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005490 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005491 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005492 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005493 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005494
John McCallb6cfa242011-01-31 22:28:28 +00005495 Kind = CK_BitCast;
5496 return IncompatiblePointer;
5497 }
5498
5499 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005500 if (RHSType->getAs<BlockPointerType>()) {
5501 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005502 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005503 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005504 }
Steve Naroffb4406862008-09-29 18:10:17 +00005505 }
John McCallb6cfa242011-01-31 22:28:28 +00005506
Steve Naroff1c7d0672008-09-04 15:10:53 +00005507 return Incompatible;
5508 }
5509
John McCallb6cfa242011-01-31 22:28:28 +00005510 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005511 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005512 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005513 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005514 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005515 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005516 }
5517
5518 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005519 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005520 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005521 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005522 }
5523
John McCallb6cfa242011-01-31 22:28:28 +00005524 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005525 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005526 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005527 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005528 }
Steve Naroffb4406862008-09-29 18:10:17 +00005529
John McCallb6cfa242011-01-31 22:28:28 +00005530 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005531 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005532 if (RHSPT->getPointeeType()->isVoidType()) {
5533 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005534 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005535 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005536
Chris Lattnerfc144e22008-01-04 23:18:45 +00005537 return Incompatible;
5538 }
5539
John McCallb6cfa242011-01-31 22:28:28 +00005540 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005541 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005542 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005543 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005544 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005545 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005546 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005547 if (getLangOptions().ObjCAutoRefCount &&
5548 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005549 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005550 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005551 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005552 }
5553
5554 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005555 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005556 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005557 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005558 }
5559
John McCallb6cfa242011-01-31 22:28:28 +00005560 // In general, C pointers are not compatible with ObjC object pointers,
5561 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005562 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005563 Kind = CK_CPointerToObjCPointerCast;
5564
John McCallb6cfa242011-01-31 22:28:28 +00005565 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005566 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005567 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005568 }
5569
5570 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005571 if (LHSType->isObjCClassType() &&
5572 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005573 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005574 return Compatible;
5575 }
5576
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005577 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005578 }
John McCallb6cfa242011-01-31 22:28:28 +00005579
5580 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005581 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005582 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005583 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005584 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005585 }
5586
Steve Naroff14108da2009-07-10 23:34:53 +00005587 return Incompatible;
5588 }
John McCallb6cfa242011-01-31 22:28:28 +00005589
5590 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005591 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005592 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005593 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005594 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005595 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005596 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005597
John McCallb6cfa242011-01-31 22:28:28 +00005598 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005599 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005600 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005601 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005602 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005603
Chris Lattnerfc144e22008-01-04 23:18:45 +00005604 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005605 }
John McCallb6cfa242011-01-31 22:28:28 +00005606
5607 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005608 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005609 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005610 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005611 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005612 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005613 }
Steve Naroff14108da2009-07-10 23:34:53 +00005614
John McCallb6cfa242011-01-31 22:28:28 +00005615 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005616 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005617 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005618 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005619 }
5620
Steve Naroff14108da2009-07-10 23:34:53 +00005621 return Incompatible;
5622 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005623
John McCallb6cfa242011-01-31 22:28:28 +00005624 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005625 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5626 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005627 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005628 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005629 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005630 }
John McCallb6cfa242011-01-31 22:28:28 +00005631
Reid Spencer5f016e22007-07-11 17:01:13 +00005632 return Incompatible;
5633}
5634
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005635/// \brief Constructs a transparent union from an expression that is
5636/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005637static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5638 ExprResult &EResult, QualType UnionType,
5639 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005640 // Build an initializer list that designates the appropriate member
5641 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005642 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005643 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005644 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005645 SourceLocation());
5646 Initializer->setType(UnionType);
5647 Initializer->setInitializedFieldInUnion(Field);
5648
5649 // Build a compound literal constructing a value of the transparent
5650 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005651 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005652 EResult = S.Owned(
5653 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5654 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005655}
5656
5657Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005658Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005659 ExprResult &RHS) {
5660 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005661
Mike Stump1eb44332009-09-09 15:08:12 +00005662 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005663 // transparent_union GCC extension.
5664 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005665 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005666 return Incompatible;
5667
5668 // The field to initialize within the transparent union.
5669 RecordDecl *UD = UT->getDecl();
5670 FieldDecl *InitField = 0;
5671 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005672 for (RecordDecl::field_iterator it = UD->field_begin(),
5673 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005674 it != itend; ++it) {
5675 if (it->getType()->isPointerType()) {
5676 // If the transparent union contains a pointer type, we allow:
5677 // 1) void pointer
5678 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005679 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005680 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005681 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005682 InitField = *it;
5683 break;
5684 }
Mike Stump1eb44332009-09-09 15:08:12 +00005685
Richard Trieuf7720da2011-09-06 20:40:12 +00005686 if (RHS.get()->isNullPointerConstant(Context,
5687 Expr::NPC_ValueDependentIsNull)) {
5688 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5689 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005690 InitField = *it;
5691 break;
5692 }
5693 }
5694
John McCalldaa8e4e2010-11-15 09:13:47 +00005695 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005696 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005697 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005698 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005699 InitField = *it;
5700 break;
5701 }
5702 }
5703
5704 if (!InitField)
5705 return Incompatible;
5706
Richard Trieuf7720da2011-09-06 20:40:12 +00005707 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005708 return Compatible;
5709}
5710
Chris Lattner5cf216b2008-01-04 18:04:52 +00005711Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005712Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5713 bool Diagnose) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005714 if (getLangOptions().CPlusPlus) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005715 if (!LHSType->isRecordType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005716 // C++ 5.17p3: If the left operand is not of class type, the
5717 // expression is implicitly converted (C++ 4) to the
5718 // cv-unqualified type of the left operand.
Richard Trieuf7720da2011-09-06 20:40:12 +00005719 ExprResult Res = PerformImplicitConversion(RHS.get(),
5720 LHSType.getUnqualifiedType(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00005721 AA_Assigning, Diagnose);
John Wiegley429bb272011-04-08 18:41:53 +00005722 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005723 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005724 Sema::AssignConvertType result = Compatible;
5725 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005726 !CheckObjCARCUnavailableWeakConversion(LHSType,
5727 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005728 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005729 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005730 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005731 }
5732
5733 // FIXME: Currently, we fall through and treat C++ classes like C
5734 // structures.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005735 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005736
Steve Naroff529a4ad2007-11-27 17:58:44 +00005737 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5738 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005739 if ((LHSType->isPointerType() ||
5740 LHSType->isObjCObjectPointerType() ||
5741 LHSType->isBlockPointerType())
5742 && RHS.get()->isNullPointerConstant(Context,
5743 Expr::NPC_ValueDependentIsNull)) {
5744 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005745 return Compatible;
5746 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005747
Chris Lattner943140e2007-10-16 02:55:40 +00005748 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005749 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005750 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005751 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005752 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005753 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005754 if (!LHSType->isReferenceType()) {
5755 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5756 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005757 return Incompatible;
5758 }
Steve Narofff1120de2007-08-24 22:33:52 +00005759
John McCalldaa8e4e2010-11-15 09:13:47 +00005760 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005761 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005762 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005763
Steve Narofff1120de2007-08-24 22:33:52 +00005764 // C99 6.5.16.1p2: The value of the right operand is converted to the
5765 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005766 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5767 // so that we can use references in built-in functions even in C.
5768 // The getNonReferenceType() call makes sure that the resulting expression
5769 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005770 if (result != Incompatible && RHS.get()->getType() != LHSType)
5771 RHS = ImpCastExprToType(RHS.take(),
5772 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005773 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005774}
5775
Richard Trieuf7720da2011-09-06 20:40:12 +00005776QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5777 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005778 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005779 << LHS.get()->getType() << RHS.get()->getType()
5780 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005781 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005782}
5783
Richard Trieu08062aa2011-09-06 21:01:04 +00005784QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005785 SourceLocation Loc, bool IsCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005786 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005787 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005788 QualType LHSType =
5789 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5790 QualType RHSType =
5791 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005792
Nate Begemanbe2341d2008-07-14 18:02:46 +00005793 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005794 if (LHSType == RHSType)
5795 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005796
Douglas Gregor255210e2010-08-06 10:14:59 +00005797 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005798 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5799 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5800 if (LHSType->isExtVectorType()) {
5801 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5802 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005803 }
5804
Richard Trieuccd891a2011-09-09 01:45:06 +00005805 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005806 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5807 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005808 }
5809
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005810 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005811 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005812 // If we are allowing lax vector conversions, and LHS and RHS are both
5813 // vectors, the total size only needs to be the same. This is a
5814 // bitcast; no bits are changed but the result type is different.
5815 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005816 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5817 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005818 }
5819
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005820 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5821 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5822 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005823 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005824 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005825 std::swap(RHS, LHS);
5826 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005827 }
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Nate Begemandde25982009-06-28 19:12:57 +00005829 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005830 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005831 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005832 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5833 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005834 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005835 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005836 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005837 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5838 if (swapped) std::swap(RHS, LHS);
5839 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005840 }
5841 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005842 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5843 RHSType->isRealFloatingType()) {
5844 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005845 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005846 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005847 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005848 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5849 if (swapped) std::swap(RHS, LHS);
5850 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005851 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005852 }
5853 }
Mike Stump1eb44332009-09-09 15:08:12 +00005854
Nate Begemandde25982009-06-28 19:12:57 +00005855 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005856 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005857 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005858 << LHS.get()->getType() << RHS.get()->getType()
5859 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005860 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005861}
5862
Richard Trieu481037f2011-09-16 00:53:10 +00005863// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5864// expression. These are mainly cases where the null pointer is used as an
5865// integer instead of a pointer.
5866static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5867 SourceLocation Loc, bool IsCompare) {
5868 // The canonical way to check for a GNU null is with isNullPointerConstant,
5869 // but we use a bit of a hack here for speed; this is a relatively
5870 // hot path, and isNullPointerConstant is slow.
5871 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5872 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5873
5874 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5875
5876 // Avoid analyzing cases where the result will either be invalid (and
5877 // diagnosed as such) or entirely valid and not something to warn about.
5878 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5879 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5880 return;
5881
5882 // Comparison operations would not make sense with a null pointer no matter
5883 // what the other expression is.
5884 if (!IsCompare) {
5885 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5886 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5887 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5888 return;
5889 }
5890
5891 // The rest of the operations only make sense with a null pointer
5892 // if the other expression is a pointer.
5893 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5894 NonNullType->canDecayToPointerType())
5895 return;
5896
5897 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5898 << LHSNull /* LHS is NULL */ << NonNullType
5899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5900}
5901
Richard Trieu08062aa2011-09-06 21:01:04 +00005902QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005903 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005904 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00005905 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5906
Richard Trieu08062aa2011-09-06 21:01:04 +00005907 if (LHS.get()->getType()->isVectorType() ||
5908 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005909 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005910
Richard Trieuccd891a2011-09-09 01:45:06 +00005911 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005912 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005913 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005914
Richard Trieu08062aa2011-09-06 21:01:04 +00005915 if (!LHS.get()->getType()->isArithmeticType() ||
5916 !RHS.get()->getType()->isArithmeticType())
5917 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005918
Chris Lattner7ef655a2010-01-12 21:23:57 +00005919 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005920 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005921 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005922 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005923 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5924 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005925
Chris Lattner7ef655a2010-01-12 21:23:57 +00005926 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005927}
5928
Chris Lattner7ef655a2010-01-12 21:23:57 +00005929QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005930 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00005931 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5932
Richard Trieu08062aa2011-09-06 21:01:04 +00005933 if (LHS.get()->getType()->isVectorType() ||
5934 RHS.get()->getType()->isVectorType()) {
5935 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5936 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005937 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005938 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005939 }
Steve Naroff90045e82007-07-13 23:32:42 +00005940
Richard Trieuccd891a2011-09-09 01:45:06 +00005941 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005942 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005943 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005944
Richard Trieu08062aa2011-09-06 21:01:04 +00005945 if (!LHS.get()->getType()->isIntegerType() ||
5946 !RHS.get()->getType()->isIntegerType())
5947 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005948
Chris Lattner7ef655a2010-01-12 21:23:57 +00005949 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005950 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005951 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005952 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5953 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005954
Chris Lattner7ef655a2010-01-12 21:23:57 +00005955 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005956}
5957
Chandler Carruth13b21be2011-06-27 08:02:19 +00005958/// \brief Diagnose invalid arithmetic on two void pointers.
5959static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005960 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005961 S.Diag(Loc, S.getLangOptions().CPlusPlus
5962 ? diag::err_typecheck_pointer_arith_void_type
5963 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005964 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5965 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005966}
5967
5968/// \brief Diagnose invalid arithmetic on a void pointer.
5969static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5970 Expr *Pointer) {
5971 S.Diag(Loc, S.getLangOptions().CPlusPlus
5972 ? diag::err_typecheck_pointer_arith_void_type
5973 : diag::ext_gnu_void_ptr)
5974 << 0 /* one pointer */ << Pointer->getSourceRange();
5975}
5976
5977/// \brief Diagnose invalid arithmetic on two function pointers.
5978static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5979 Expr *LHS, Expr *RHS) {
5980 assert(LHS->getType()->isAnyPointerType());
5981 assert(RHS->getType()->isAnyPointerType());
5982 S.Diag(Loc, S.getLangOptions().CPlusPlus
5983 ? diag::err_typecheck_pointer_arith_function_type
5984 : diag::ext_gnu_ptr_func_arith)
5985 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5986 // We only show the second type if it differs from the first.
5987 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5988 RHS->getType())
5989 << RHS->getType()->getPointeeType()
5990 << LHS->getSourceRange() << RHS->getSourceRange();
5991}
5992
5993/// \brief Diagnose invalid arithmetic on a function pointer.
5994static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5995 Expr *Pointer) {
5996 assert(Pointer->getType()->isAnyPointerType());
5997 S.Diag(Loc, S.getLangOptions().CPlusPlus
5998 ? diag::err_typecheck_pointer_arith_function_type
5999 : diag::ext_gnu_ptr_func_arith)
6000 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6001 << 0 /* one pointer, so only one type */
6002 << Pointer->getSourceRange();
6003}
6004
Richard Trieud9f19342011-09-12 18:08:02 +00006005/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006006///
6007/// \returns True if pointer has incomplete type
6008static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6009 Expr *Operand) {
6010 if ((Operand->getType()->isPointerType() &&
6011 !Operand->getType()->isDependentType()) ||
6012 Operand->getType()->isObjCObjectPointerType()) {
6013 QualType PointeeTy = Operand->getType()->getPointeeType();
6014 if (S.RequireCompleteType(
6015 Loc, PointeeTy,
6016 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6017 << PointeeTy << Operand->getSourceRange()))
6018 return true;
6019 }
6020 return false;
6021}
6022
Chandler Carruth13b21be2011-06-27 08:02:19 +00006023/// \brief Check the validity of an arithmetic pointer operand.
6024///
6025/// If the operand has pointer type, this code will check for pointer types
6026/// which are invalid in arithmetic operations. These will be diagnosed
6027/// appropriately, including whether or not the use is supported as an
6028/// extension.
6029///
6030/// \returns True when the operand is valid to use (even if as an extension).
6031static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6032 Expr *Operand) {
6033 if (!Operand->getType()->isAnyPointerType()) return true;
6034
6035 QualType PointeeTy = Operand->getType()->getPointeeType();
6036 if (PointeeTy->isVoidType()) {
6037 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6038 return !S.getLangOptions().CPlusPlus;
6039 }
6040 if (PointeeTy->isFunctionType()) {
6041 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6042 return !S.getLangOptions().CPlusPlus;
6043 }
6044
Richard Trieu097ecd22011-09-02 02:15:37 +00006045 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006046
6047 return true;
6048}
6049
6050/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6051/// operands.
6052///
6053/// This routine will diagnose any invalid arithmetic on pointer operands much
6054/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6055/// for emitting a single diagnostic even for operations where both LHS and RHS
6056/// are (potentially problematic) pointers.
6057///
6058/// \returns True when the operand is valid to use (even if as an extension).
6059static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006060 Expr *LHSExpr, Expr *RHSExpr) {
6061 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6062 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006063 if (!isLHSPointer && !isRHSPointer) return true;
6064
6065 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006066 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6067 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006068
6069 // Check for arithmetic on pointers to incomplete types.
6070 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6071 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6072 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006073 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6074 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6075 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006076
6077 return !S.getLangOptions().CPlusPlus;
6078 }
6079
6080 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6081 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6082 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006083 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6084 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6085 RHSExpr);
6086 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006087
6088 return !S.getLangOptions().CPlusPlus;
6089 }
6090
Richard Trieudef75842011-09-06 21:13:51 +00006091 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6092 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006093
Chandler Carruth13b21be2011-06-27 08:02:19 +00006094 return true;
6095}
6096
Richard Trieudb44a6b2011-09-01 22:53:23 +00006097/// \brief Check bad cases where we step over interface counts.
6098static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6099 SourceLocation OpLoc,
6100 Expr *Op) {
6101 assert(Op->getType()->isAnyPointerType());
6102 QualType PointeeTy = Op->getType()->getPointeeType();
6103 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6104 return true;
6105
6106 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6107 << PointeeTy << Op->getSourceRange();
6108 return false;
6109}
6110
Richard Trieud9f19342011-09-12 18:08:02 +00006111/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006112static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006113 Expr *LHSExpr, Expr *RHSExpr) {
6114 assert(LHSExpr->getType()->isAnyPointerType());
6115 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006116 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006117 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6118 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006119}
6120
Chris Lattner7ef655a2010-01-12 21:23:57 +00006121QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006122 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006123 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6124
Richard Trieudef75842011-09-06 21:13:51 +00006125 if (LHS.get()->getType()->isVectorType() ||
6126 RHS.get()->getType()->isVectorType()) {
6127 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006128 if (CompLHSTy) *CompLHSTy = compType;
6129 return compType;
6130 }
Steve Naroff49b45262007-07-13 16:58:59 +00006131
Richard Trieudef75842011-09-06 21:13:51 +00006132 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6133 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006134 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006135
Reid Spencer5f016e22007-07-11 17:01:13 +00006136 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006137 if (LHS.get()->getType()->isArithmeticType() &&
6138 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006139 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006140 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006141 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006142
Eli Friedmand72d16e2008-05-18 18:08:51 +00006143 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006144 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006145 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006146 std::swap(PExp, IExp);
6147
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006148 if (!PExp->getType()->isAnyPointerType())
6149 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006150
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006151 if (!IExp->getType()->isIntegerType())
6152 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006153
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006154 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6155 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006156
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006157 // Diagnose bad cases where we step over interface counts.
6158 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6159 return QualType();
6160
6161 // Check array bounds for pointer arithemtic
6162 CheckArrayAccess(PExp, IExp);
6163
6164 if (CompLHSTy) {
6165 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6166 if (LHSTy.isNull()) {
6167 LHSTy = LHS.get()->getType();
6168 if (LHSTy->isPromotableIntegerType())
6169 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006170 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006171 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006172 }
6173
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006174 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006175}
6176
Chris Lattnereca7be62008-04-07 05:30:13 +00006177// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006178QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006179 SourceLocation Loc,
6180 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006181 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6182
Richard Trieudef75842011-09-06 21:13:51 +00006183 if (LHS.get()->getType()->isVectorType() ||
6184 RHS.get()->getType()->isVectorType()) {
6185 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006186 if (CompLHSTy) *CompLHSTy = compType;
6187 return compType;
6188 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006189
Richard Trieudef75842011-09-06 21:13:51 +00006190 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6191 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006192 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006193
Chris Lattner6e4ab612007-12-09 21:53:25 +00006194 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006195
Chris Lattner6e4ab612007-12-09 21:53:25 +00006196 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006197 if (LHS.get()->getType()->isArithmeticType() &&
6198 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006199 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006200 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006201 }
Mike Stump1eb44332009-09-09 15:08:12 +00006202
Chris Lattner6e4ab612007-12-09 21:53:25 +00006203 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006204 if (LHS.get()->getType()->isAnyPointerType()) {
6205 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006206
Chris Lattnerb5f15622009-04-24 23:50:08 +00006207 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006208 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006209 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006210
Chris Lattner6e4ab612007-12-09 21:53:25 +00006211 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006212 if (RHS.get()->getType()->isIntegerType()) {
6213 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006214 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006215
Richard Trieudef75842011-09-06 21:13:51 +00006216 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006217 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6218 OK_Ordinary, IExpr->getExprLoc());
6219 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006220 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006221
Richard Trieudef75842011-09-06 21:13:51 +00006222 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6223 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006225
Chris Lattner6e4ab612007-12-09 21:53:25 +00006226 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006227 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006228 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006229 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006230
Eli Friedman88d936b2009-05-16 13:54:38 +00006231 if (getLangOptions().CPlusPlus) {
6232 // Pointee types must be the same: C++ [expr.add]
6233 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006234 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006235 }
6236 } else {
6237 // Pointee types must be compatible C99 6.5.6p3
6238 if (!Context.typesAreCompatible(
6239 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6240 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006241 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006242 return QualType();
6243 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006244 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006245
Chandler Carruth13b21be2011-06-27 08:02:19 +00006246 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006247 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006248 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006249
Richard Trieudef75842011-09-06 21:13:51 +00006250 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006251 return Context.getPointerDiffType();
6252 }
6253 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006254
Richard Trieudef75842011-09-06 21:13:51 +00006255 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006256}
6257
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006258static bool isScopedEnumerationType(QualType T) {
6259 if (const EnumType *ET = dyn_cast<EnumType>(T))
6260 return ET->getDecl()->isScoped();
6261 return false;
6262}
6263
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006264static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006265 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006266 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006267 llvm::APSInt Right;
6268 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006269 if (RHS.get()->isValueDependent() ||
6270 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006271 return;
6272
6273 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006274 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006275 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006276 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006277 return;
6278 }
6279 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006280 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006281 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006282 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006283 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006284 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006285 return;
6286 }
6287 if (Opc != BO_Shl)
6288 return;
6289
6290 // When left shifting an ICE which is signed, we can check for overflow which
6291 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6292 // integers have defined behavior modulo one more than the maximum value
6293 // representable in the result type, so never warn for those.
6294 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006295 if (LHS.get()->isValueDependent() ||
6296 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6297 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006298 return;
6299 llvm::APInt ResultBits =
6300 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6301 if (LeftBits.uge(ResultBits))
6302 return;
6303 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6304 Result = Result.shl(Right);
6305
Ted Kremenekfa821382011-06-15 00:54:52 +00006306 // Print the bit representation of the signed integer as an unsigned
6307 // hexadecimal number.
6308 llvm::SmallString<40> HexResult;
6309 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6310
Chandler Carruth21206d52011-02-23 23:34:11 +00006311 // If we are only missing a sign bit, this is less likely to result in actual
6312 // bugs -- if the result is cast back to an unsigned type, it will have the
6313 // expected value. Thus we place this behind a different warning that can be
6314 // turned off separately if needed.
6315 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006316 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006317 << HexResult.str() << LHSType
6318 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006319 return;
6320 }
6321
6322 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006323 << HexResult.str() << Result.getMinSignedBits() << LHSType
6324 << Left.getBitWidth() << LHS.get()->getSourceRange()
6325 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006326}
6327
Chris Lattnereca7be62008-04-07 05:30:13 +00006328// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006329QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006330 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006331 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006332 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6333
Chris Lattnerca5eede2007-12-12 05:47:28 +00006334 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006335 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6336 !RHS.get()->getType()->hasIntegerRepresentation())
6337 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006338
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006339 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6340 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006341 if (isScopedEnumerationType(LHS.get()->getType()) ||
6342 isScopedEnumerationType(RHS.get()->getType())) {
6343 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006344 }
6345
Nate Begeman2207d792009-10-25 02:26:48 +00006346 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006347 if (LHS.get()->getType()->isVectorType() ||
6348 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006349 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006350
Chris Lattnerca5eede2007-12-12 05:47:28 +00006351 // Shifts don't perform usual arithmetic conversions, they just do integer
6352 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006353
John McCall1bc80af2010-12-16 19:28:59 +00006354 // For the LHS, do usual unary conversions, but then reset them away
6355 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006356 ExprResult OldLHS = LHS;
6357 LHS = UsualUnaryConversions(LHS.take());
6358 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006359 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006360 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006361 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006362
6363 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006364 RHS = UsualUnaryConversions(RHS.take());
6365 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006366 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006367
Ryan Flynnd0439682009-08-07 16:20:20 +00006368 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006369 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006370
Chris Lattnerca5eede2007-12-12 05:47:28 +00006371 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006372 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006373}
6374
Chandler Carruth99919472010-07-10 12:30:03 +00006375static bool IsWithinTemplateSpecialization(Decl *D) {
6376 if (DeclContext *DC = D->getDeclContext()) {
6377 if (isa<ClassTemplateSpecializationDecl>(DC))
6378 return true;
6379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6380 return FD->isFunctionTemplateSpecialization();
6381 }
6382 return false;
6383}
6384
Richard Trieue648ac32011-09-02 03:48:46 +00006385/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006386static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6387 ExprResult &RHS) {
6388 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6389 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006390
6391 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6392 if (!LHSEnumType)
6393 return;
6394 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6395 if (!RHSEnumType)
6396 return;
6397
6398 // Ignore anonymous enums.
6399 if (!LHSEnumType->getDecl()->getIdentifier())
6400 return;
6401 if (!RHSEnumType->getDecl()->getIdentifier())
6402 return;
6403
6404 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6405 return;
6406
6407 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6408 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006409 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006410}
6411
Richard Trieu7be1be02011-09-02 02:55:45 +00006412/// \brief Diagnose bad pointer comparisons.
6413static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006414 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006415 bool IsError) {
6416 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006417 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006418 << LHS.get()->getType() << RHS.get()->getType()
6419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006420}
6421
6422/// \brief Returns false if the pointers are converted to a composite type,
6423/// true otherwise.
6424static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006425 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006426 // C++ [expr.rel]p2:
6427 // [...] Pointer conversions (4.10) and qualification
6428 // conversions (4.4) are performed on pointer operands (or on
6429 // a pointer operand and a null pointer constant) to bring
6430 // them to their composite pointer type. [...]
6431 //
6432 // C++ [expr.eq]p1 uses the same notion for (in)equality
6433 // comparisons of pointers.
6434
6435 // C++ [expr.eq]p2:
6436 // In addition, pointers to members can be compared, or a pointer to
6437 // member and a null pointer constant. Pointer to member conversions
6438 // (4.11) and qualification conversions (4.4) are performed to bring
6439 // them to a common type. If one operand is a null pointer constant,
6440 // the common type is the type of the other operand. Otherwise, the
6441 // common type is a pointer to member type similar (4.4) to the type
6442 // of one of the operands, with a cv-qualification signature (4.4)
6443 // that is the union of the cv-qualification signatures of the operand
6444 // types.
6445
Richard Trieuba261492011-09-06 21:27:33 +00006446 QualType LHSType = LHS.get()->getType();
6447 QualType RHSType = RHS.get()->getType();
6448 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6449 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006450
6451 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006452 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006453 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006454 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006455 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006456 return true;
6457 }
6458
6459 if (NonStandardCompositeType)
6460 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006461 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6462 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006463
Richard Trieuba261492011-09-06 21:27:33 +00006464 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6465 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006466 return false;
6467}
6468
6469static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006470 ExprResult &LHS,
6471 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006472 bool IsError) {
6473 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6474 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006475 << LHS.get()->getType() << RHS.get()->getType()
6476 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006477}
6478
Douglas Gregor0c6db942009-05-04 06:07:12 +00006479// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006480QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006481 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006482 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006483 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6484
John McCall2de56d12010-08-25 11:45:40 +00006485 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006486
Chris Lattner02dd4b12009-12-05 05:40:13 +00006487 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006488 if (LHS.get()->getType()->isVectorType() ||
6489 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006490 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006491
Richard Trieuf1775fb2011-09-06 21:43:51 +00006492 QualType LHSType = LHS.get()->getType();
6493 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006494
Richard Trieuf1775fb2011-09-06 21:43:51 +00006495 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6496 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006497
Richard Trieuf1775fb2011-09-06 21:43:51 +00006498 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006499
Richard Trieuf1775fb2011-09-06 21:43:51 +00006500 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006501 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006502 !LHS.get()->getLocStart().isMacroID() &&
6503 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006504 // For non-floating point types, check for self-comparisons of the form
6505 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6506 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006507 //
6508 // NOTE: Don't warn about comparison expressions resulting from macro
6509 // expansion. Also don't warn about comparisons which are only self
6510 // comparisons within a template specialization. The warnings should catch
6511 // obvious cases in the definition of the template anyways. The idea is to
6512 // warn when the typed comparison operator will always evaluate to the same
6513 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006514 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006515 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006516 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006517 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006518 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006519 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006520 << (Opc == BO_EQ
6521 || Opc == BO_LE
6522 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006523 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006524 !DRL->getDecl()->getType()->isReferenceType() &&
6525 !DRR->getDecl()->getType()->isReferenceType()) {
6526 // what is it always going to eval to?
6527 char always_evals_to;
6528 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006529 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006530 always_evals_to = 0; // false
6531 break;
John McCall2de56d12010-08-25 11:45:40 +00006532 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006533 always_evals_to = 1; // true
6534 break;
6535 default:
6536 // best we can say is 'a constant'
6537 always_evals_to = 2; // e.g. array1 <= array2
6538 break;
6539 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006540 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006541 << 1 // array
6542 << always_evals_to);
6543 }
6544 }
Chandler Carruth99919472010-07-10 12:30:03 +00006545 }
Mike Stump1eb44332009-09-09 15:08:12 +00006546
Chris Lattner55660a72009-03-08 19:39:53 +00006547 if (isa<CastExpr>(LHSStripped))
6548 LHSStripped = LHSStripped->IgnoreParenCasts();
6549 if (isa<CastExpr>(RHSStripped))
6550 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006551
Chris Lattner55660a72009-03-08 19:39:53 +00006552 // Warn about comparisons against a string constant (unless the other
6553 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006554 Expr *literalString = 0;
6555 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006556 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006557 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006558 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006559 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006560 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006561 } else if ((isa<StringLiteral>(RHSStripped) ||
6562 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006563 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006564 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006565 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006566 literalStringStripped = RHSStripped;
6567 }
6568
6569 if (literalString) {
6570 std::string resultComparison;
6571 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006572 case BO_LT: resultComparison = ") < 0"; break;
6573 case BO_GT: resultComparison = ") > 0"; break;
6574 case BO_LE: resultComparison = ") <= 0"; break;
6575 case BO_GE: resultComparison = ") >= 0"; break;
6576 case BO_EQ: resultComparison = ") == 0"; break;
6577 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006578 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006579 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006580
Ted Kremenek351ba912011-02-23 01:52:04 +00006581 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006582 PDiag(diag::warn_stringcompare)
6583 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006584 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006585 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006586 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006587
Douglas Gregord64fdd02010-06-08 19:50:34 +00006588 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006589 if (LHS.get()->getType()->isArithmeticType() &&
6590 RHS.get()->getType()->isArithmeticType()) {
6591 UsualArithmeticConversions(LHS, RHS);
6592 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006593 return QualType();
6594 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006595 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006596 LHS = UsualUnaryConversions(LHS.take());
6597 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006598 return QualType();
6599
Richard Trieuf1775fb2011-09-06 21:43:51 +00006600 RHS = UsualUnaryConversions(RHS.take());
6601 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006602 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006603 }
6604
Richard Trieuf1775fb2011-09-06 21:43:51 +00006605 LHSType = LHS.get()->getType();
6606 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006607
Douglas Gregor447b69e2008-11-19 03:25:36 +00006608 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006609 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006610
Richard Trieuccd891a2011-09-09 01:45:06 +00006611 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006612 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006613 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006614 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006615 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006616 if (LHSType->hasFloatingRepresentation())
6617 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006618
Richard Trieuf1775fb2011-09-06 21:43:51 +00006619 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006620 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006621 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006622
Richard Trieuf1775fb2011-09-06 21:43:51 +00006623 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006624 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006625 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006626 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006627
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006628 // All of the following pointer-related warnings are GCC extensions, except
6629 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006630 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006631 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006632 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006633 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006634 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006635
Douglas Gregor0c6db942009-05-04 06:07:12 +00006636 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006637 if (LCanPointeeTy == RCanPointeeTy)
6638 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006639 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006640 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6641 // Valid unless comparison between non-null pointer and function pointer
6642 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006643 // In a SFINAE context, we treat this as a hard error to maintain
6644 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006645 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6646 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006647 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006648 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006649
6650 if (isSFINAEContext())
6651 return QualType();
6652
Richard Trieuf1775fb2011-09-06 21:43:51 +00006653 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006654 return ResultTy;
6655 }
6656 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006657
Richard Trieuf1775fb2011-09-06 21:43:51 +00006658 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006659 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006660 else
6661 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006662 }
Eli Friedman3075e762009-08-23 00:27:47 +00006663 // C99 6.5.9p2 and C99 6.5.8p2
6664 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6665 RCanPointeeTy.getUnqualifiedType())) {
6666 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006667 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006668 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006669 << LHSType << RHSType << LHS.get()->getSourceRange()
6670 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006671 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006672 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006673 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6674 // Valid unless comparison between non-null pointer and function pointer
6675 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006676 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006677 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006678 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006679 } else {
6680 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006681 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006682 }
John McCall34d6f932011-03-11 04:25:25 +00006683 if (LCanPointeeTy != RCanPointeeTy) {
6684 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006685 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006686 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006687 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006688 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006689 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006690 }
Mike Stump1eb44332009-09-09 15:08:12 +00006691
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006692 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006693 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006694 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006695 return ResultTy;
6696
Mike Stump1eb44332009-09-09 15:08:12 +00006697 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006698 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006699 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006700 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006701 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006702 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6703 RHS = ImpCastExprToType(RHS.take(), LHSType,
6704 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006705 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006706 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006707 return ResultTy;
6708 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006709 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006710 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006711 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006712 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6713 LHS = ImpCastExprToType(LHS.take(), RHSType,
6714 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006715 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006716 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006717 return ResultTy;
6718 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006719
6720 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006721 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006722 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6723 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006724 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006725 else
6726 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006727 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006728
6729 // Handle scoped enumeration types specifically, since they don't promote
6730 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006731 if (LHS.get()->getType()->isEnumeralType() &&
6732 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6733 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006734 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006735 }
Mike Stump1eb44332009-09-09 15:08:12 +00006736
Steve Naroff1c7d0672008-09-04 15:10:53 +00006737 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006738 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006739 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006740 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6741 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006742
Steve Naroff1c7d0672008-09-04 15:10:53 +00006743 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006744 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006745 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006746 << LHSType << RHSType << LHS.get()->getSourceRange()
6747 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006748 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006749 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006750 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006751 }
John Wiegley429bb272011-04-08 18:41:53 +00006752
Steve Naroff59f53942008-09-28 01:11:11 +00006753 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006754 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006755 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6756 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006757 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006758 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006759 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006760 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006761 ->getPointeeType()->isVoidType())))
6762 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006763 << LHSType << RHSType << LHS.get()->getSourceRange()
6764 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006765 }
John McCall34d6f932011-03-11 04:25:25 +00006766 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006767 LHS = ImpCastExprToType(LHS.take(), RHSType,
6768 RHSType->isPointerType() ? CK_BitCast
6769 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006770 else
John McCall1d9b3b22011-09-09 05:25:32 +00006771 RHS = ImpCastExprToType(RHS.take(), LHSType,
6772 LHSType->isPointerType() ? CK_BitCast
6773 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006774 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006775 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006776
Richard Trieuf1775fb2011-09-06 21:43:51 +00006777 if (LHSType->isObjCObjectPointerType() ||
6778 RHSType->isObjCObjectPointerType()) {
6779 const PointerType *LPT = LHSType->getAs<PointerType>();
6780 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006781 if (LPT || RPT) {
6782 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6783 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006784
Steve Naroffa8069f12008-11-17 19:49:16 +00006785 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006786 !Context.typesAreCompatible(LHSType, RHSType)) {
6787 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006788 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006789 }
John McCall34d6f932011-03-11 04:25:25 +00006790 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006791 LHS = ImpCastExprToType(LHS.take(), RHSType,
6792 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006793 else
John McCall1d9b3b22011-09-09 05:25:32 +00006794 RHS = ImpCastExprToType(RHS.take(), LHSType,
6795 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006796 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006797 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006798 if (LHSType->isObjCObjectPointerType() &&
6799 RHSType->isObjCObjectPointerType()) {
6800 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6801 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006802 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006803 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006804 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006805 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006806 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006807 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006808 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006809 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006810 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6811 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006812 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006813 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006814 if ((LHSIsNull && LHSType->isIntegerType()) ||
6815 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006816 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006817 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006818 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006819 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006820 else if (getLangOptions().CPlusPlus) {
6821 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6822 isError = true;
6823 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006824 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006825
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006826 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006827 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006828 << LHSType << RHSType << LHS.get()->getSourceRange()
6829 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006830 if (isError)
6831 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006832 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006833
Richard Trieuf1775fb2011-09-06 21:43:51 +00006834 if (LHSType->isIntegerType())
6835 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006836 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006837 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006838 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006839 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006840 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006841 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006842
Steve Naroff39218df2008-09-04 16:56:14 +00006843 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006844 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006845 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6846 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006847 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006848 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006849 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006850 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6851 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006852 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006853 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006854
Richard Trieuf1775fb2011-09-06 21:43:51 +00006855 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006856}
6857
Nate Begemanbe2341d2008-07-14 18:02:46 +00006858/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006859/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006860/// like a scalar comparison, a vector comparison produces a vector of integer
6861/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006862QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006863 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006864 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006865 // Check to make sure we're operating on vectors of the same type and width,
6866 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006867 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006868 if (vType.isNull())
6869 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006870
Richard Trieu9f60dee2011-09-07 01:19:57 +00006871 QualType LHSType = LHS.get()->getType();
6872 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006873
Anton Yartsev7870b132011-03-27 15:36:07 +00006874 // If AltiVec, the comparison results in a numeric type, i.e.
6875 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006876 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006877 return Context.getLogicalOperationType();
6878
Nate Begemanbe2341d2008-07-14 18:02:46 +00006879 // For non-floating point types, check for self-comparisons of the form
6880 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6881 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006882 if (!LHSType->hasFloatingRepresentation()) {
6883 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6884 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006885 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006886 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006887 PDiag(diag::warn_comparison_always)
6888 << 0 // self-
6889 << 2 // "a constant"
6890 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006891 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006892
Nate Begemanbe2341d2008-07-14 18:02:46 +00006893 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006894 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006895 assert (RHSType->hasFloatingRepresentation());
6896 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006897 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006898
Nate Begemanbe2341d2008-07-14 18:02:46 +00006899 // Return the type for the comparison, which is the same as vector type for
6900 // integer vectors, or an integer type of identical size and number of
6901 // elements for floating point vectors.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006902 if (LHSType->hasIntegerRepresentation())
6903 return LHSType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006904
Richard Trieu9f60dee2011-09-07 01:19:57 +00006905 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006906 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006907 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006908 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006909 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006910 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6911
Mike Stumpeed9cac2009-02-19 03:04:26 +00006912 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006913 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006914 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6915}
6916
Reid Spencer5f016e22007-07-11 17:01:13 +00006917inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006918 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006919 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6920
Richard Trieu9f60dee2011-09-07 01:19:57 +00006921 if (LHS.get()->getType()->isVectorType() ||
6922 RHS.get()->getType()->isVectorType()) {
6923 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6924 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006925 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006926
Richard Trieu9f60dee2011-09-07 01:19:57 +00006927 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006928 }
Steve Naroff90045e82007-07-13 23:32:42 +00006929
Richard Trieu9f60dee2011-09-07 01:19:57 +00006930 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6931 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006932 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006933 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006934 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006935 LHS = LHSResult.take();
6936 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006937
Richard Trieu9f60dee2011-09-07 01:19:57 +00006938 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6939 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006940 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006941 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006942}
6943
6944inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006945 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006946
6947 // Diagnose cases where the user write a logical and/or but probably meant a
6948 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6949 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006950 if (LHS.get()->getType()->isIntegerType() &&
6951 !LHS.get()->getType()->isBooleanType() &&
6952 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006953 // Don't warn in macros or template instantiations.
6954 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006955 // If the RHS can be constant folded, and if it constant folds to something
6956 // that isn't 0 or 1 (which indicate a potential logical operation that
6957 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006958 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006959 Expr::EvalResult Result;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006960 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6961 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruth0683a142011-05-31 05:41:42 +00006962 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6963 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006964 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006965 << (Opc == BO_LAnd ? "&&" : "||");
6966 // Suggest replacing the logical operator with the bitwise version
6967 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6968 << (Opc == BO_LAnd ? "&" : "|")
6969 << FixItHint::CreateReplacement(SourceRange(
6970 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6971 getLangOptions())),
6972 Opc == BO_LAnd ? "&" : "|");
6973 if (Opc == BO_LAnd)
6974 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6975 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6976 << FixItHint::CreateRemoval(
6977 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006978 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006979 0, getSourceManager(),
6980 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006981 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006982 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006983 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006984
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006985 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006986 LHS = UsualUnaryConversions(LHS.take());
6987 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006988 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006989
Richard Trieu9f60dee2011-09-07 01:19:57 +00006990 RHS = UsualUnaryConversions(RHS.take());
6991 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006992 return QualType();
6993
Richard Trieu9f60dee2011-09-07 01:19:57 +00006994 if (!LHS.get()->getType()->isScalarType() ||
6995 !RHS.get()->getType()->isScalarType())
6996 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006997
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006998 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006999 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007000
John McCall75f7c0f2010-06-04 00:29:51 +00007001 // The following is safe because we only use this method for
7002 // non-overloadable operands.
7003
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007004 // C++ [expr.log.and]p1
7005 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007006 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007007 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7008 if (LHSRes.isInvalid())
7009 return InvalidOperands(Loc, LHS, RHS);
7010 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007011
Richard Trieu9f60dee2011-09-07 01:19:57 +00007012 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7013 if (RHSRes.isInvalid())
7014 return InvalidOperands(Loc, LHS, RHS);
7015 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007016
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007017 // C++ [expr.log.and]p2
7018 // C++ [expr.log.or]p2
7019 // The result is a bool.
7020 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007021}
7022
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007023/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7024/// is a read-only property; return true if so. A readonly property expression
7025/// depends on various declarations and thus must be treated specially.
7026///
Mike Stump1eb44332009-09-09 15:08:12 +00007027static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007028 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7029 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007030 if (PropExpr->isImplicitProperty()) return false;
7031
7032 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7033 QualType BaseType = PropExpr->isSuperReceiver() ?
7034 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007035 PropExpr->getBase()->getType();
7036
John McCall12f78a62010-12-02 01:19:52 +00007037 if (const ObjCObjectPointerType *OPT =
7038 BaseType->getAsObjCInterfacePointerType())
7039 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7040 if (S.isPropertyReadonly(PDecl, IFace))
7041 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007042 }
7043 return false;
7044}
7045
Fariborz Jahanian14086762011-03-28 23:47:18 +00007046static bool IsConstProperty(Expr *E, Sema &S) {
7047 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7048 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7049 if (PropExpr->isImplicitProperty()) return false;
7050
7051 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7052 QualType T = PDecl->getType();
7053 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007054 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007055 CanQualType CT = S.Context.getCanonicalType(T);
7056 return CT.isConstQualified();
7057 }
7058 return false;
7059}
7060
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007061static bool IsReadonlyMessage(Expr *E, Sema &S) {
7062 if (E->getStmtClass() != Expr::MemberExprClass)
7063 return false;
7064 const MemberExpr *ME = cast<MemberExpr>(E);
7065 NamedDecl *Member = ME->getMemberDecl();
7066 if (isa<FieldDecl>(Member)) {
7067 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7068 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7069 return false;
7070 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7071 }
7072 return false;
7073}
7074
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007075/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7076/// emit an error and return true. If so, return false.
7077static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007078 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007079 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007080 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007081 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7082 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007083 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7084 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007085 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7086 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007087 if (IsLV == Expr::MLV_Valid)
7088 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007089
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007090 unsigned Diag = 0;
7091 bool NeedType = false;
7092 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007093 case Expr::MLV_ConstQualified:
7094 Diag = diag::err_typecheck_assign_const;
7095
John McCall7acddac2011-06-17 06:42:21 +00007096 // In ARC, use some specialized diagnostics for occasions where we
7097 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00007098 if (S.getLangOptions().ObjCAutoRefCount) {
7099 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7100 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7101 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7102
John McCall7acddac2011-06-17 06:42:21 +00007103 // Use the normal diagnostic if it's pseudo-__strong but the
7104 // user actually wrote 'const'.
7105 if (var->isARCPseudoStrong() &&
7106 (!var->getTypeSourceInfo() ||
7107 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7108 // There are two pseudo-strong cases:
7109 // - self
John McCallf85e1932011-06-15 23:02:42 +00007110 ObjCMethodDecl *method = S.getCurMethodDecl();
7111 if (method && var == method->getSelfDecl())
7112 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007113
7114 // - fast enumeration variables
7115 else
John McCallf85e1932011-06-15 23:02:42 +00007116 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007117
John McCallf85e1932011-06-15 23:02:42 +00007118 SourceRange Assign;
7119 if (Loc != OrigLoc)
7120 Assign = SourceRange(OrigLoc, OrigLoc);
7121 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7122 // We need to preserve the AST regardless, so migration tool
7123 // can do its job.
7124 return false;
7125 }
7126 }
7127 }
7128
7129 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007130 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007131 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7132 NeedType = true;
7133 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007134 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007135 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7136 NeedType = true;
7137 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007138 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007139 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7140 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007141 case Expr::MLV_Valid:
7142 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007143 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007144 case Expr::MLV_MemberFunction:
7145 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007146 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7147 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007148 case Expr::MLV_IncompleteType:
7149 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007150 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007151 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007152 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007153 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007154 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7155 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007156 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007157 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7158 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007159 case Expr::MLV_ReadonlyProperty:
7160 Diag = diag::error_readonly_property_assignment;
7161 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007162 case Expr::MLV_NoSetterProperty:
7163 Diag = diag::error_nosetter_property_assignment;
7164 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007165 case Expr::MLV_InvalidMessageExpression:
7166 Diag = diag::error_readonly_message_assignment;
7167 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007168 case Expr::MLV_SubObjCPropertySetting:
7169 Diag = diag::error_no_subobject_property_setting;
7170 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007171 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007172
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007173 SourceRange Assign;
7174 if (Loc != OrigLoc)
7175 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007176 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007177 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007178 else
Mike Stump1eb44332009-09-09 15:08:12 +00007179 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007180 return true;
7181}
7182
7183
7184
7185// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007186QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007187 SourceLocation Loc,
7188 QualType CompoundType) {
7189 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007190 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007191 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007192
Richard Trieu268942b2011-09-07 01:33:52 +00007193 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007194 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7195 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007196 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007197 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007198 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007199 // Simple assignment "x = y".
Richard Trieu268942b2011-09-07 01:33:52 +00007200 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7201 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley429bb272011-04-08 18:41:53 +00007202 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7203 if (LHSResult.isInvalid())
7204 return QualType();
Richard Trieu268942b2011-09-07 01:33:52 +00007205 LHSExpr = LHSResult.take();
John Wiegley429bb272011-04-08 18:41:53 +00007206 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007207 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007208 if (RHS.isInvalid())
7209 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007210 // Special case of NSObject attributes on c-style pointer types.
7211 if (ConvTy == IncompatiblePointer &&
7212 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007213 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007214 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007215 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007216 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007217
John McCallf89e55a2010-11-18 06:31:45 +00007218 if (ConvTy == Compatible &&
7219 getLangOptions().ObjCNonFragileABI &&
7220 LHSType->isObjCObjectType())
7221 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7222 << LHSType;
7223
Chris Lattner2c156472008-08-21 18:04:13 +00007224 // If the RHS is a unary plus or minus, check to see if they = and + are
7225 // right next to each other. If so, the user may have typo'd "x =+ 4"
7226 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007227 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007228 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7229 RHSCheck = ICE->getSubExpr();
7230 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007231 if ((UO->getOpcode() == UO_Plus ||
7232 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007233 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007234 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007235 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007236 // And there is a space or other character before the subexpr of the
7237 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007238 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007239 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007240 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007241 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007242 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007243 }
Chris Lattner2c156472008-08-21 18:04:13 +00007244 }
John McCallf85e1932011-06-15 23:02:42 +00007245
7246 if (ConvTy == Compatible) {
7247 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007248 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007249 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007250 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007251 }
Chris Lattner2c156472008-08-21 18:04:13 +00007252 } else {
7253 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007254 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007255 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007256
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007257 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007258 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007259 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007260
Richard Trieu268942b2011-09-07 01:33:52 +00007261 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007262
Reid Spencer5f016e22007-07-11 17:01:13 +00007263 // C99 6.5.16p3: The type of an assignment expression is the type of the
7264 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007265 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007266 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7267 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007268 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007269 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007270 return (getLangOptions().CPlusPlus
7271 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007272}
7273
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007274// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007275static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007276 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007277 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007278
John McCallfb8721c2011-04-10 19:13:55 +00007279 LHS = S.CheckPlaceholderExpr(LHS.take());
7280 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007281 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007282 return QualType();
7283
John McCallcf2e5062010-10-12 07:14:40 +00007284 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7285 // operands, but not unary promotions.
7286 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007287
John McCallf6a16482010-12-04 03:47:34 +00007288 // So we treat the LHS as a ignored value, and in C++ we allow the
7289 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007290 LHS = S.IgnoredValueConversions(LHS.take());
7291 if (LHS.isInvalid())
7292 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007293
7294 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007295 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7296 if (RHS.isInvalid())
7297 return QualType();
7298 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007299 S.RequireCompleteType(Loc, RHS.get()->getType(),
7300 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007301 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007302
John Wiegley429bb272011-04-08 18:41:53 +00007303 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007304}
7305
Steve Naroff49b45262007-07-13 16:58:59 +00007306/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7307/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007308static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7309 ExprValueKind &VK,
7310 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007311 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007312 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007313 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007314
Chris Lattner3528d352008-11-21 07:05:48 +00007315 QualType ResType = Op->getType();
7316 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007317
John McCall09431682010-11-18 19:01:18 +00007318 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007319 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007320 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007321 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007322 return QualType();
7323 }
7324 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007325 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007326 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007327 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007328 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007329 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007330 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007331 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007332
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007333 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007334 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007335 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007336 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007337 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007338 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007339 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007340 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007341 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007342 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007343 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007344 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007345 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7346 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007347 } else {
John McCall09431682010-11-18 19:01:18 +00007348 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007349 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007350 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007351 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007352 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007353 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007354 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007355 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007356 // In C++, a prefix increment is the same type as the operand. Otherwise
7357 // (in C or with postfix), the increment is the unqualified type of the
7358 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007359 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007360 VK = VK_LValue;
7361 return ResType;
7362 } else {
7363 VK = VK_RValue;
7364 return ResType.getUnqualifiedType();
7365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007366}
7367
John Wiegley429bb272011-04-08 18:41:53 +00007368ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007369 assert(E->getValueKind() == VK_LValue &&
7370 E->getObjectKind() == OK_ObjCProperty);
7371 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7372
Douglas Gregor926df6c2011-06-11 01:09:30 +00007373 QualType T = E->getType();
7374 QualType ReceiverType;
7375 if (PRE->isObjectReceiver())
7376 ReceiverType = PRE->getBase()->getType();
7377 else if (PRE->isSuperReceiver())
7378 ReceiverType = PRE->getSuperReceiverType();
7379 else
7380 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7381
John McCallf6a16482010-12-04 03:47:34 +00007382 ExprValueKind VK = VK_RValue;
7383 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007384 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007385 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007386 T = getMessageSendResultType(ReceiverType, GetterMethod,
7387 PRE->isClassReceiver(),
7388 PRE->isSuperReceiver());
7389 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007390 }
7391 else {
7392 Diag(PRE->getLocation(), diag::err_getter_not_found)
7393 << PRE->getBase()->getType();
7394 }
John McCallf6a16482010-12-04 03:47:34 +00007395 }
Fariborz Jahanianc6ac3222011-10-03 17:58:21 +00007396 else {
7397 // lvalue-ness of an explicit property is determined by
7398 // property type.
7399 ObjCPropertyDecl *PDecl = PRE->getExplicitProperty();
7400 VK = Expr::getValueKindForType(PDecl->getType());
7401 }
7402
Douglas Gregor926df6c2011-06-11 01:09:30 +00007403 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007404 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007405
7406 ExprResult Result = MaybeBindToTemporary(E);
7407 if (!Result.isInvalid())
7408 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007409
7410 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007411}
7412
Richard Trieu67e29332011-08-02 04:35:43 +00007413void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7414 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007415 assert(LHS.get()->getValueKind() == VK_LValue &&
7416 LHS.get()->getObjectKind() == OK_ObjCProperty);
7417 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007418
John McCallf85e1932011-06-15 23:02:42 +00007419 bool Consumed = false;
7420
John Wiegley429bb272011-04-08 18:41:53 +00007421 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007422 // If using property-dot syntax notation for assignment, and there is a
7423 // setter, RHS expression is being passed to the setter argument. So,
7424 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007425 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00007426 ObjCMethodDecl::param_const_iterator P = SetterMD->param_begin();
John McCallf6a16482010-12-04 03:47:34 +00007427 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007428 Consumed = (getLangOptions().ObjCAutoRefCount &&
7429 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007430
7431 // Otherwise, if the getter returns an l-value, just call that.
7432 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007433 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007434 ExprValueKind VK = Expr::getValueKindForType(Result);
7435 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007436 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7437 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007438 return;
John McCall12f78a62010-12-02 01:19:52 +00007439 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007440 }
John McCallf85e1932011-06-15 23:02:42 +00007441 } else if (getLangOptions().ObjCAutoRefCount) {
7442 const ObjCMethodDecl *setter
7443 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7444 if (setter) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00007445 ObjCMethodDecl::param_const_iterator P = setter->param_begin();
John McCallf85e1932011-06-15 23:02:42 +00007446 LHSTy = (*P)->getType();
7447 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7448 }
John McCallf6a16482010-12-04 03:47:34 +00007449 }
7450
John McCallf85e1932011-06-15 23:02:42 +00007451 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7452 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007453 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007454 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007455 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007456 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007457 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007458 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7459 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7460 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007461 }
7462}
7463
7464
Anders Carlsson369dee42008-02-01 07:15:58 +00007465/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007466/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007467/// where the declaration is needed for type checking. We only need to
7468/// handle cases when the expression references a function designator
7469/// or is an lvalue. Here are some examples:
7470/// - &(x) => x
7471/// - &*****f => f for f a function designator.
7472/// - &s.xx => s
7473/// - &s.zz[1].yy -> s, if zz is an array
7474/// - *(x + 1) -> x, if x is an array
7475/// - &"123"[2] -> 0
7476/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007477static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007478 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007479 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007480 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007481 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007482 // If this is an arrow operator, the address is an offset from
7483 // the base's value, so the object the base refers to is
7484 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007485 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007486 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007487 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007488 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007489 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007490 // FIXME: This code shouldn't be necessary! We should catch the implicit
7491 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007492 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7493 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7494 if (ICE->getSubExpr()->getType()->isArrayType())
7495 return getPrimaryDecl(ICE->getSubExpr());
7496 }
7497 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007498 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007499 case Stmt::UnaryOperatorClass: {
7500 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007501
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007502 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007503 case UO_Real:
7504 case UO_Imag:
7505 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007506 return getPrimaryDecl(UO->getSubExpr());
7507 default:
7508 return 0;
7509 }
7510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007511 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007512 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007513 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007514 // If the result of an implicit cast is an l-value, we care about
7515 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007516 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007517 default:
7518 return 0;
7519 }
7520}
7521
Richard Trieu5520f232011-09-07 21:46:33 +00007522namespace {
7523 enum {
7524 AO_Bit_Field = 0,
7525 AO_Vector_Element = 1,
7526 AO_Property_Expansion = 2,
7527 AO_Register_Variable = 3,
7528 AO_No_Error = 4
7529 };
7530}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007531/// \brief Diagnose invalid operand for address of operations.
7532///
7533/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007534static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7535 Expr *E, unsigned Type) {
7536 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7537}
7538
Reid Spencer5f016e22007-07-11 17:01:13 +00007539/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007540/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007541/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007542/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007543/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007544/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007545/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007546static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7547 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007548 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007549 return S.Context.DependentTy;
7550 if (OrigOp->getType() == S.Context.OverloadTy)
7551 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007552 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7553 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007554 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7555 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7556 << OrigOp->getSourceRange();
7557 return QualType();
7558 }
John McCall9c72c602010-08-27 09:08:28 +00007559
John McCall755d8492011-04-12 00:42:48 +00007560 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007561
John McCall9c72c602010-08-27 09:08:28 +00007562 // Make sure to ignore parentheses in subsequent checks
7563 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007564
John McCall09431682010-11-18 19:01:18 +00007565 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007566 // Implement C99-only parts of addressof rules.
7567 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007568 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007569 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7570 // (assuming the deref expression is valid).
7571 return uOp->getSubExpr()->getType();
7572 }
7573 // Technically, there should be a check for array subscript
7574 // expressions here, but the result of one is always an lvalue anyway.
7575 }
John McCall5808ce42011-02-03 08:15:49 +00007576 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007577 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007578 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007579
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007580 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007581 bool sfinae = S.isSFINAEContext();
7582 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7583 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007584 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007585 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007586 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007587 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007588 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007589 } else if (lval == Expr::LV_MemberFunction) {
7590 // If it's an instance method, make a member pointer.
7591 // The expression must have exactly the form &A::foo.
7592
7593 // If the underlying expression isn't a decl ref, give up.
7594 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007595 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007596 << OrigOp->getSourceRange();
7597 return QualType();
7598 }
7599 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7600 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7601
7602 // The id-expression was parenthesized.
7603 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007604 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007605 << OrigOp->getSourceRange();
7606
7607 // The method was named without a qualifier.
7608 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007609 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007610 << op->getSourceRange();
7611 }
7612
John McCall09431682010-11-18 19:01:18 +00007613 return S.Context.getMemberPointerType(op->getType(),
7614 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007615 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007616 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007617 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007618 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007619 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007620 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007621 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007622 return QualType();
7623 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007624 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007625 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007626 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007627 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007628 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007629 AddressOfError = AO_Vector_Element;
John McCall7eb0a9e2010-11-24 05:12:34 +00007630 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007631 // cannot take address of a property expression.
Richard Trieu5520f232011-09-07 21:46:33 +00007632 AddressOfError = AO_Property_Expansion;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007633 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007634 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007635 // with the register storage-class specifier.
7636 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007637 // in C++ it is not error to take address of a register
7638 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007639 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007640 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007641 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007642 }
John McCallba135432009-11-21 08:51:07 +00007643 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007644 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007645 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007646 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007647 // Could be a pointer to member, though, if there is an explicit
7648 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007649 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007650 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007651 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007652 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007653 S.Diag(OpLoc,
7654 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007655 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007656 return QualType();
7657 }
Mike Stump1eb44332009-09-09 15:08:12 +00007658
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007659 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7660 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007661 return S.Context.getMemberPointerType(op->getType(),
7662 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007663 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007664 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007665 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007666 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007667 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007668
Richard Trieu5520f232011-09-07 21:46:33 +00007669 if (AddressOfError != AO_No_Error) {
7670 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7671 return QualType();
7672 }
7673
Eli Friedman441cf102009-05-16 23:27:50 +00007674 if (lval == Expr::LV_IncompleteVoidType) {
7675 // Taking the address of a void variable is technically illegal, but we
7676 // allow it in cases which are otherwise valid.
7677 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007678 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007679 }
7680
Reid Spencer5f016e22007-07-11 17:01:13 +00007681 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007682 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007683 return S.Context.getObjCObjectPointerType(op->getType());
7684 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007685}
7686
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007687/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007688static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7689 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007690 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007691 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007692
John Wiegley429bb272011-04-08 18:41:53 +00007693 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7694 if (ConvResult.isInvalid())
7695 return QualType();
7696 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007697 QualType OpTy = Op->getType();
7698 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007699
7700 if (isa<CXXReinterpretCastExpr>(Op)) {
7701 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7702 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7703 Op->getSourceRange());
7704 }
7705
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007706 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7707 // is an incomplete type or void. It would be possible to warn about
7708 // dereferencing a void pointer, but it's completely well-defined, and such a
7709 // warning is unlikely to catch any mistakes.
7710 if (const PointerType *PT = OpTy->getAs<PointerType>())
7711 Result = PT->getPointeeType();
7712 else if (const ObjCObjectPointerType *OPT =
7713 OpTy->getAs<ObjCObjectPointerType>())
7714 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007715 else {
John McCallfb8721c2011-04-10 19:13:55 +00007716 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007717 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007718 if (PR.take() != Op)
7719 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007720 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007721
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007722 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007723 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007724 << OpTy << Op->getSourceRange();
7725 return QualType();
7726 }
John McCall09431682010-11-18 19:01:18 +00007727
7728 // Dereferences are usually l-values...
7729 VK = VK_LValue;
7730
7731 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007732 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007733 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007734
7735 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007736}
7737
John McCall2de56d12010-08-25 11:45:40 +00007738static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007739 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007740 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007741 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007742 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007743 case tok::periodstar: Opc = BO_PtrMemD; break;
7744 case tok::arrowstar: Opc = BO_PtrMemI; break;
7745 case tok::star: Opc = BO_Mul; break;
7746 case tok::slash: Opc = BO_Div; break;
7747 case tok::percent: Opc = BO_Rem; break;
7748 case tok::plus: Opc = BO_Add; break;
7749 case tok::minus: Opc = BO_Sub; break;
7750 case tok::lessless: Opc = BO_Shl; break;
7751 case tok::greatergreater: Opc = BO_Shr; break;
7752 case tok::lessequal: Opc = BO_LE; break;
7753 case tok::less: Opc = BO_LT; break;
7754 case tok::greaterequal: Opc = BO_GE; break;
7755 case tok::greater: Opc = BO_GT; break;
7756 case tok::exclaimequal: Opc = BO_NE; break;
7757 case tok::equalequal: Opc = BO_EQ; break;
7758 case tok::amp: Opc = BO_And; break;
7759 case tok::caret: Opc = BO_Xor; break;
7760 case tok::pipe: Opc = BO_Or; break;
7761 case tok::ampamp: Opc = BO_LAnd; break;
7762 case tok::pipepipe: Opc = BO_LOr; break;
7763 case tok::equal: Opc = BO_Assign; break;
7764 case tok::starequal: Opc = BO_MulAssign; break;
7765 case tok::slashequal: Opc = BO_DivAssign; break;
7766 case tok::percentequal: Opc = BO_RemAssign; break;
7767 case tok::plusequal: Opc = BO_AddAssign; break;
7768 case tok::minusequal: Opc = BO_SubAssign; break;
7769 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7770 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7771 case tok::ampequal: Opc = BO_AndAssign; break;
7772 case tok::caretequal: Opc = BO_XorAssign; break;
7773 case tok::pipeequal: Opc = BO_OrAssign; break;
7774 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007775 }
7776 return Opc;
7777}
7778
John McCall2de56d12010-08-25 11:45:40 +00007779static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007780 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007781 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007782 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007783 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007784 case tok::plusplus: Opc = UO_PreInc; break;
7785 case tok::minusminus: Opc = UO_PreDec; break;
7786 case tok::amp: Opc = UO_AddrOf; break;
7787 case tok::star: Opc = UO_Deref; break;
7788 case tok::plus: Opc = UO_Plus; break;
7789 case tok::minus: Opc = UO_Minus; break;
7790 case tok::tilde: Opc = UO_Not; break;
7791 case tok::exclaim: Opc = UO_LNot; break;
7792 case tok::kw___real: Opc = UO_Real; break;
7793 case tok::kw___imag: Opc = UO_Imag; break;
7794 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007795 }
7796 return Opc;
7797}
7798
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007799/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7800/// This warning is only emitted for builtin assignment operations. It is also
7801/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007802static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007803 SourceLocation OpLoc) {
7804 if (!S.ActiveTemplateInstantiations.empty())
7805 return;
7806 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7807 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007808 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7809 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7810 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7811 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7812 if (!LHSDeclRef || !RHSDeclRef ||
7813 LHSDeclRef->getLocation().isMacroID() ||
7814 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007815 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007816 const ValueDecl *LHSDecl =
7817 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7818 const ValueDecl *RHSDecl =
7819 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7820 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007821 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007822 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007823 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007824 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007825 if (RefTy->getPointeeType().isVolatileQualified())
7826 return;
7827
7828 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007829 << LHSDeclRef->getType()
7830 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007831}
7832
Douglas Gregoreaebc752008-11-06 23:29:22 +00007833/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7834/// operator @p Opc at location @c TokLoc. This routine only supports
7835/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007836ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007837 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007838 Expr *LHSExpr, Expr *RHSExpr) {
7839 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007840 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007841 // The following two variables are used for compound assignment operators
7842 QualType CompLHSTy; // Type of LHS after promotions for computation
7843 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007844 ExprValueKind VK = VK_RValue;
7845 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007846
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007847 // Check if a 'foo<int>' involved in a binary op, identifies a single
7848 // function unambiguously (i.e. an lvalue ala 13.4)
7849 // But since an assignment can trigger target based overload, exclude it in
7850 // our blind search. i.e:
7851 // template<class T> void f(); template<class T, class U> void f(U);
7852 // f<int> == 0; // resolve f<int> blindly
7853 // void (*p)(int); p = f<int>; // resolve f<int> using target
7854 if (Opc != BO_Assign) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00007855 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007856 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007857 LHS = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007858
Richard Trieu78ea78b2011-09-07 01:49:20 +00007859 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007860 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007861 RHS = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007862 }
7863
Douglas Gregoreaebc752008-11-06 23:29:22 +00007864 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007865 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007866 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007867 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007868 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7869 VK = LHS.get()->getValueKind();
7870 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007871 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007872 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007873 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007874 break;
John McCall2de56d12010-08-25 11:45:40 +00007875 case BO_PtrMemD:
7876 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007877 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007878 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007879 break;
John McCall2de56d12010-08-25 11:45:40 +00007880 case BO_Mul:
7881 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007882 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007883 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007884 break;
John McCall2de56d12010-08-25 11:45:40 +00007885 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007886 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007887 break;
John McCall2de56d12010-08-25 11:45:40 +00007888 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007889 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007890 break;
John McCall2de56d12010-08-25 11:45:40 +00007891 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007892 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007893 break;
John McCall2de56d12010-08-25 11:45:40 +00007894 case BO_Shl:
7895 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007896 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007897 break;
John McCall2de56d12010-08-25 11:45:40 +00007898 case BO_LE:
7899 case BO_LT:
7900 case BO_GE:
7901 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007902 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007903 break;
John McCall2de56d12010-08-25 11:45:40 +00007904 case BO_EQ:
7905 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007906 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007907 break;
John McCall2de56d12010-08-25 11:45:40 +00007908 case BO_And:
7909 case BO_Xor:
7910 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007911 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007912 break;
John McCall2de56d12010-08-25 11:45:40 +00007913 case BO_LAnd:
7914 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007915 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007916 break;
John McCall2de56d12010-08-25 11:45:40 +00007917 case BO_MulAssign:
7918 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007919 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007920 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007921 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007922 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7923 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007924 break;
John McCall2de56d12010-08-25 11:45:40 +00007925 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007926 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007927 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007928 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7929 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007930 break;
John McCall2de56d12010-08-25 11:45:40 +00007931 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007932 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7933 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7934 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007935 break;
John McCall2de56d12010-08-25 11:45:40 +00007936 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007937 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7938 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7939 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007940 break;
John McCall2de56d12010-08-25 11:45:40 +00007941 case BO_ShlAssign:
7942 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007943 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007944 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007945 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7946 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007947 break;
John McCall2de56d12010-08-25 11:45:40 +00007948 case BO_AndAssign:
7949 case BO_XorAssign:
7950 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007951 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007952 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007953 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7954 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007955 break;
John McCall2de56d12010-08-25 11:45:40 +00007956 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007957 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7958 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7959 VK = RHS.get()->getValueKind();
7960 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007961 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007962 break;
7963 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007964 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007965 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007966
7967 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007968 CheckArrayAccess(LHS.get());
7969 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007970
Eli Friedmanab3a8522009-03-28 01:22:36 +00007971 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007972 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007973 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007974 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007975 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007976 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007977 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007978 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007979 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007980 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007981 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007982}
7983
Sebastian Redlaee3c932009-10-27 12:10:02 +00007984/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7985/// operators are mixed in a way that suggests that the programmer forgot that
7986/// comparison operators have higher precedence. The most typical example of
7987/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007988static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007989 SourceLocation OpLoc, Expr *LHSExpr,
7990 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007991 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007992 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7993 RHSopc = static_cast<BinOp::Opcode>(-1);
7994 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7995 LHSopc = BO->getOpcode();
7996 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7997 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007998
7999 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008000 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008001 return;
8002
8003 // Bitwise operations are sometimes used as eager logical ops.
8004 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008005 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8006 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008007 return;
8008
Richard Trieu78ea78b2011-09-07 01:49:20 +00008009 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8010 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008011 if (!isLeftComp && !isRightComp) return;
8012
Richard Trieu78ea78b2011-09-07 01:49:20 +00008013 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8014 OpLoc)
8015 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8016 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8017 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008018 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008019 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8020 RHSExpr->getLocEnd())
8021 : SourceRange(LHSExpr->getLocStart(),
8022 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008023
8024 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8025 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8026 SuggestParentheses(Self, OpLoc,
8027 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008028 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008029 SuggestParentheses(Self, OpLoc,
8030 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8031 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008032}
8033
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008034/// \brief It accepts a '&' expr that is inside a '|' one.
8035/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8036/// in parentheses.
8037static void
8038EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8039 BinaryOperator *Bop) {
8040 assert(Bop->getOpcode() == BO_And);
8041 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8042 << Bop->getSourceRange() << OpLoc;
8043 SuggestParentheses(Self, Bop->getOperatorLoc(),
8044 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8045 Bop->getSourceRange());
8046}
8047
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008048/// \brief It accepts a '&&' expr that is inside a '||' one.
8049/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8050/// in parentheses.
8051static void
8052EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008053 BinaryOperator *Bop) {
8054 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008055 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8056 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008057 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008058 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008059 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008060}
8061
8062/// \brief Returns true if the given expression can be evaluated as a constant
8063/// 'true'.
8064static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8065 bool Res;
8066 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8067}
8068
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008069/// \brief Returns true if the given expression can be evaluated as a constant
8070/// 'false'.
8071static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8072 bool Res;
8073 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8074}
8075
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008076/// \brief Look for '&&' in the left hand of a '||' expr.
8077static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008078 Expr *LHSExpr, Expr *RHSExpr) {
8079 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008080 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008081 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008082 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008083 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008084 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8085 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8086 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8087 } else if (Bop->getOpcode() == BO_LOr) {
8088 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8089 // If it's "a || b && 1 || c" we didn't warn earlier for
8090 // "a || b && 1", but warn now.
8091 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8092 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8093 }
8094 }
8095 }
8096}
8097
8098/// \brief Look for '&&' in the right hand of a '||' expr.
8099static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008100 Expr *LHSExpr, Expr *RHSExpr) {
8101 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008102 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008103 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008104 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008105 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008106 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8107 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8108 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008109 }
8110 }
8111}
8112
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008113/// \brief Look for '&' in the left or right hand of a '|' expr.
8114static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8115 Expr *OrArg) {
8116 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8117 if (Bop->getOpcode() == BO_And)
8118 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8119 }
8120}
8121
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008122/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008123/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008124static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008125 SourceLocation OpLoc, Expr *LHSExpr,
8126 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008127 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008128 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008129 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008130
8131 // Diagnose "arg1 & arg2 | arg3"
8132 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008133 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8134 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008135 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008136
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008137 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8138 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008139 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008140 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8141 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008142 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008143}
8144
Reid Spencer5f016e22007-07-11 17:01:13 +00008145// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008146ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008147 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008148 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008149 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008150 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8151 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008152
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008153 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008154 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008155
Richard Trieubefece12011-09-07 02:02:10 +00008156 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008157}
8158
John McCall60d7b3a2010-08-24 06:29:42 +00008159ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008160 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008161 Expr *LHSExpr, Expr *RHSExpr) {
John McCall01b2e4e2010-12-06 05:26:58 +00008162 if (getLangOptions().CPlusPlus) {
8163 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008164
Richard Trieubefece12011-09-07 02:02:10 +00008165 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall01b2e4e2010-12-06 05:26:58 +00008166 UseBuiltinOperator = false;
Richard Trieubefece12011-09-07 02:02:10 +00008167 } else if (Opc == BO_Assign &&
8168 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall01b2e4e2010-12-06 05:26:58 +00008169 UseBuiltinOperator = true;
8170 } else {
Richard Trieubefece12011-09-07 02:02:10 +00008171 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8172 !RHSExpr->getType()->isOverloadableType();
John McCall01b2e4e2010-12-06 05:26:58 +00008173 }
8174
8175 if (!UseBuiltinOperator) {
8176 // Find all of the overloaded operators visible from this
8177 // point. We perform both an operator-name lookup from the local
8178 // scope and an argument-dependent lookup based on the types of
8179 // the arguments.
8180 UnresolvedSet<16> Functions;
8181 OverloadedOperatorKind OverOp
8182 = BinaryOperator::getOverloadedOperator(Opc);
8183 if (S && OverOp != OO_None)
Richard Trieubefece12011-09-07 02:02:10 +00008184 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8185 RHSExpr->getType(), Functions);
John McCall01b2e4e2010-12-06 05:26:58 +00008186
8187 // Build the (potentially-overloaded, potentially-dependent)
8188 // binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008189 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall01b2e4e2010-12-06 05:26:58 +00008190 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008191 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008192
Douglas Gregoreaebc752008-11-06 23:29:22 +00008193 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008194 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008195}
8196
John McCall60d7b3a2010-08-24 06:29:42 +00008197ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008198 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008199 Expr *InputExpr) {
8200 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008201 ExprValueKind VK = VK_RValue;
8202 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008203 QualType resultType;
8204 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008205 case UO_PreInc:
8206 case UO_PreDec:
8207 case UO_PostInc:
8208 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008209 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008210 Opc == UO_PreInc ||
8211 Opc == UO_PostInc,
8212 Opc == UO_PreInc ||
8213 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008214 break;
John McCall2de56d12010-08-25 11:45:40 +00008215 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008216 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008217 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008218 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008219 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008220 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008221 Input = move(resolved);
8222 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8223 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008224 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008225 }
John McCall2de56d12010-08-25 11:45:40 +00008226 case UO_Plus:
8227 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008228 Input = UsualUnaryConversions(Input.take());
8229 if (Input.isInvalid()) return ExprError();
8230 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008231 if (resultType->isDependentType())
8232 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008233 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8234 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008235 break;
8236 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8237 resultType->isEnumeralType())
8238 break;
8239 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008240 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008241 resultType->isPointerType())
8242 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008243 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008244 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008245 if (Input.isInvalid()) return ExprError();
8246 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008247 }
Douglas Gregor74253732008-11-19 15:42:04 +00008248
Sebastian Redl0eb23302009-01-19 00:08:26 +00008249 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008250 << resultType << Input.get()->getSourceRange());
8251
John McCall2de56d12010-08-25 11:45:40 +00008252 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008253 Input = UsualUnaryConversions(Input.take());
8254 if (Input.isInvalid()) return ExprError();
8255 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008256 if (resultType->isDependentType())
8257 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008258 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8259 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8260 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008261 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008262 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008263 else if (resultType->hasIntegerRepresentation())
8264 break;
8265 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008266 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008267 if (Input.isInvalid()) return ExprError();
8268 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008269 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008270 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008271 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008272 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008273 break;
John Wiegley429bb272011-04-08 18:41:53 +00008274
John McCall2de56d12010-08-25 11:45:40 +00008275 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008276 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008277 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8278 if (Input.isInvalid()) return ExprError();
8279 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008280 if (resultType->isDependentType())
8281 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008282 if (resultType->isScalarType()) {
8283 // C99 6.5.3.3p1: ok, fallthrough;
8284 if (Context.getLangOptions().CPlusPlus) {
8285 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8286 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008287 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8288 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008289 }
John McCall2cd11fe2010-10-12 02:09:17 +00008290 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008291 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008292 if (Input.isInvalid()) return ExprError();
8293 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008294 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008295 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008296 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008297 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008298
Reid Spencer5f016e22007-07-11 17:01:13 +00008299 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008300 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008301 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008302 break;
John McCall2de56d12010-08-25 11:45:40 +00008303 case UO_Real:
8304 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008305 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008306 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008307 if (Input.isInvalid()) return ExprError();
8308 if (Input.get()->getValueKind() != VK_RValue &&
8309 Input.get()->getObjectKind() == OK_Ordinary)
8310 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008311 break;
John McCall2de56d12010-08-25 11:45:40 +00008312 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008313 resultType = Input.get()->getType();
8314 VK = Input.get()->getValueKind();
8315 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008316 break;
8317 }
John Wiegley429bb272011-04-08 18:41:53 +00008318 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008319 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008320
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008321 // Check for array bounds violations in the operand of the UnaryOperator,
8322 // except for the '*' and '&' operators that have to be handled specially
8323 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8324 // that are explicitly defined as valid by the standard).
8325 if (Opc != UO_AddrOf && Opc != UO_Deref)
8326 CheckArrayAccess(Input.get());
8327
John Wiegley429bb272011-04-08 18:41:53 +00008328 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008329 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008330}
8331
John McCall60d7b3a2010-08-24 06:29:42 +00008332ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008333 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008334 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008335 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008336 // Find all of the overloaded operators visible from this
8337 // point. We perform both an operator-name lookup from the local
8338 // scope and an argument-dependent lookup based on the types of
8339 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008340 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008341 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008342 if (S && OverOp != OO_None)
8343 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8344 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008345
John McCall9ae2f072010-08-23 23:25:46 +00008346 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008347 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008348
John McCall9ae2f072010-08-23 23:25:46 +00008349 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008350}
8351
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008352// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008353ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008354 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008355 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008356}
8357
Steve Naroff1b273c42007-09-16 14:56:35 +00008358/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008359ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008360 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008361 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008362 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008363 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008364 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008365}
8366
John McCallf85e1932011-06-15 23:02:42 +00008367/// Given the last statement in a statement-expression, check whether
8368/// the result is a producing expression (like a call to an
8369/// ns_returns_retained function) and, if so, rebuild it to hoist the
8370/// release out of the full-expression. Otherwise, return null.
8371/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008372static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008373 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008374 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008375 if (!cleanups) return 0;
8376
8377 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008378 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008379 return 0;
8380
8381 // Splice out the cast. This shouldn't modify any interesting
8382 // features of the statement.
8383 Expr *producer = cast->getSubExpr();
8384 assert(producer->getType() == cast->getType());
8385 assert(producer->getValueKind() == cast->getValueKind());
8386 cleanups->setSubExpr(producer);
8387 return cleanups;
8388}
8389
John McCall60d7b3a2010-08-24 06:29:42 +00008390ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008391Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008392 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008393 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8394 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8395
Douglas Gregordd8f5692010-03-10 04:54:39 +00008396 bool isFileScope
8397 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008398 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008399 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008400
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008401 // FIXME: there are a variety of strange constraints to enforce here, for
8402 // example, it is not possible to goto into a stmt expression apparently.
8403 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008404
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008405 // If there are sub stmts in the compound stmt, take the type of the last one
8406 // as the type of the stmtexpr.
8407 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008408 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008409 if (!Compound->body_empty()) {
8410 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008411 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008412 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008413 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8414 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008415 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008416 }
John McCallf85e1932011-06-15 23:02:42 +00008417
John Wiegley429bb272011-04-08 18:41:53 +00008418 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008419 // Do function/array conversion on the last expression, but not
8420 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008421 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8422 if (LastExpr.isInvalid())
8423 return ExprError();
8424 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008425
John Wiegley429bb272011-04-08 18:41:53 +00008426 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008427 // In ARC, if the final expression ends in a consume, splice
8428 // the consume out and bind it later. In the alternate case
8429 // (when dealing with a retainable type), the result
8430 // initialization will create a produce. In both cases the
8431 // result will be +1, and we'll need to balance that out with
8432 // a bind.
8433 if (Expr *rebuiltLastStmt
8434 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8435 LastExpr = rebuiltLastStmt;
8436 } else {
8437 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008438 InitializedEntity::InitializeResult(LPLoc,
8439 Ty,
8440 false),
8441 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008442 LastExpr);
8443 }
8444
John Wiegley429bb272011-04-08 18:41:53 +00008445 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008446 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008447 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008448 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008449 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008450 else
John Wiegley429bb272011-04-08 18:41:53 +00008451 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008452 StmtExprMayBindToTemp = true;
8453 }
8454 }
8455 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008456 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008457
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008458 // FIXME: Check that expression type is complete/non-abstract; statement
8459 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008460 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8461 if (StmtExprMayBindToTemp)
8462 return MaybeBindToTemporary(ResStmtExpr);
8463 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008464}
Steve Naroffd34e9152007-08-01 22:05:33 +00008465
John McCall60d7b3a2010-08-24 06:29:42 +00008466ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008467 TypeSourceInfo *TInfo,
8468 OffsetOfComponent *CompPtr,
8469 unsigned NumComponents,
8470 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008471 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008472 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008473 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008474
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008475 // We must have at least one component that refers to the type, and the first
8476 // one is known to be a field designator. Verify that the ArgTy represents
8477 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008478 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008479 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8480 << ArgTy << TypeRange);
8481
8482 // Type must be complete per C99 7.17p3 because a declaring a variable
8483 // with an incomplete type would be ill-formed.
8484 if (!Dependent
8485 && RequireCompleteType(BuiltinLoc, ArgTy,
8486 PDiag(diag::err_offsetof_incomplete_type)
8487 << TypeRange))
8488 return ExprError();
8489
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008490 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8491 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008492 // FIXME: This diagnostic isn't actually visible because the location is in
8493 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008494 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008495 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8496 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008497
8498 bool DidWarnAboutNonPOD = false;
8499 QualType CurrentType = ArgTy;
8500 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008501 SmallVector<OffsetOfNode, 4> Comps;
8502 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008503 for (unsigned i = 0; i != NumComponents; ++i) {
8504 const OffsetOfComponent &OC = CompPtr[i];
8505 if (OC.isBrackets) {
8506 // Offset of an array sub-field. TODO: Should we allow vector elements?
8507 if (!CurrentType->isDependentType()) {
8508 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8509 if(!AT)
8510 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8511 << CurrentType);
8512 CurrentType = AT->getElementType();
8513 } else
8514 CurrentType = Context.DependentTy;
8515
8516 // The expression must be an integral expression.
8517 // FIXME: An integral constant expression?
8518 Expr *Idx = static_cast<Expr*>(OC.U.E);
8519 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8520 !Idx->getType()->isIntegerType())
8521 return ExprError(Diag(Idx->getLocStart(),
8522 diag::err_typecheck_subscript_not_integer)
8523 << Idx->getSourceRange());
8524
8525 // Record this array index.
8526 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8527 Exprs.push_back(Idx);
8528 continue;
8529 }
8530
8531 // Offset of a field.
8532 if (CurrentType->isDependentType()) {
8533 // We have the offset of a field, but we can't look into the dependent
8534 // type. Just record the identifier of the field.
8535 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8536 CurrentType = Context.DependentTy;
8537 continue;
8538 }
8539
8540 // We need to have a complete type to look into.
8541 if (RequireCompleteType(OC.LocStart, CurrentType,
8542 diag::err_offsetof_incomplete_type))
8543 return ExprError();
8544
8545 // Look for the designated field.
8546 const RecordType *RC = CurrentType->getAs<RecordType>();
8547 if (!RC)
8548 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8549 << CurrentType);
8550 RecordDecl *RD = RC->getDecl();
8551
8552 // C++ [lib.support.types]p5:
8553 // The macro offsetof accepts a restricted set of type arguments in this
8554 // International Standard. type shall be a POD structure or a POD union
8555 // (clause 9).
8556 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8557 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008558 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008559 PDiag(diag::warn_offsetof_non_pod_type)
8560 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8561 << CurrentType))
8562 DidWarnAboutNonPOD = true;
8563 }
8564
8565 // Look for the field.
8566 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8567 LookupQualifiedName(R, RD);
8568 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008569 IndirectFieldDecl *IndirectMemberDecl = 0;
8570 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008571 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008572 MemberDecl = IndirectMemberDecl->getAnonField();
8573 }
8574
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008575 if (!MemberDecl)
8576 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8577 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8578 OC.LocEnd));
8579
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008580 // C99 7.17p3:
8581 // (If the specified member is a bit-field, the behavior is undefined.)
8582 //
8583 // We diagnose this as an error.
8584 if (MemberDecl->getBitWidth()) {
8585 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8586 << MemberDecl->getDeclName()
8587 << SourceRange(BuiltinLoc, RParenLoc);
8588 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8589 return ExprError();
8590 }
Eli Friedman19410a72010-08-05 10:11:36 +00008591
8592 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008593 if (IndirectMemberDecl)
8594 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008595
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008596 // If the member was found in a base class, introduce OffsetOfNodes for
8597 // the base class indirections.
8598 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8599 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008600 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008601 CXXBasePath &Path = Paths.front();
8602 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8603 B != BEnd; ++B)
8604 Comps.push_back(OffsetOfNode(B->Base));
8605 }
Eli Friedman19410a72010-08-05 10:11:36 +00008606
Francois Pichet87c2e122010-11-21 06:08:52 +00008607 if (IndirectMemberDecl) {
8608 for (IndirectFieldDecl::chain_iterator FI =
8609 IndirectMemberDecl->chain_begin(),
8610 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8611 assert(isa<FieldDecl>(*FI));
8612 Comps.push_back(OffsetOfNode(OC.LocStart,
8613 cast<FieldDecl>(*FI), OC.LocEnd));
8614 }
8615 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008616 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008617
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008618 CurrentType = MemberDecl->getType().getNonReferenceType();
8619 }
8620
8621 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8622 TInfo, Comps.data(), Comps.size(),
8623 Exprs.data(), Exprs.size(), RParenLoc));
8624}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008625
John McCall60d7b3a2010-08-24 06:29:42 +00008626ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008627 SourceLocation BuiltinLoc,
8628 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008629 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008630 OffsetOfComponent *CompPtr,
8631 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008632 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008633
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008634 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008635 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008636 if (ArgTy.isNull())
8637 return ExprError();
8638
Eli Friedman5a15dc12010-08-05 10:15:45 +00008639 if (!ArgTInfo)
8640 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8641
8642 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008643 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008644}
8645
8646
John McCall60d7b3a2010-08-24 06:29:42 +00008647ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008648 Expr *CondExpr,
8649 Expr *LHSExpr, Expr *RHSExpr,
8650 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008651 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8652
John McCallf89e55a2010-11-18 06:31:45 +00008653 ExprValueKind VK = VK_RValue;
8654 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008655 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008656 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008657 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008658 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008659 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008660 } else {
8661 // The conditional expression is required to be a constant expression.
8662 llvm::APSInt condEval(32);
8663 SourceLocation ExpLoc;
8664 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008665 return ExprError(Diag(ExpLoc,
8666 diag::err_typecheck_choose_expr_requires_constant)
8667 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008668
Sebastian Redl28507842009-02-26 14:39:58 +00008669 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008670 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8671
8672 resType = ActiveExpr->getType();
8673 ValueDependent = ActiveExpr->isValueDependent();
8674 VK = ActiveExpr->getValueKind();
8675 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008676 }
8677
Sebastian Redlf53597f2009-03-15 17:47:39 +00008678 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008679 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008680 resType->isDependentType(),
8681 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008682}
8683
Steve Naroff4eb206b2008-09-03 18:15:37 +00008684//===----------------------------------------------------------------------===//
8685// Clang Extensions.
8686//===----------------------------------------------------------------------===//
8687
8688/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008689void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008690 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008691 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008692 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008693 if (CurScope)
8694 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008695 else
8696 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008697}
8698
Mike Stump98eb8a72009-02-04 22:31:32 +00008699void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008700 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008701 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008702 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008703
John McCallbf1a0282010-06-04 23:28:52 +00008704 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008705 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008706
John McCall711c52b2011-01-05 12:14:39 +00008707 // GetTypeForDeclarator always produces a function type for a block
8708 // literal signature. Furthermore, it is always a FunctionProtoType
8709 // unless the function was written with a typedef.
8710 assert(T->isFunctionType() &&
8711 "GetTypeForDeclarator made a non-function block signature");
8712
8713 // Look for an explicit signature in that function type.
8714 FunctionProtoTypeLoc ExplicitSignature;
8715
8716 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8717 if (isa<FunctionProtoTypeLoc>(tmp)) {
8718 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8719
8720 // Check whether that explicit signature was synthesized by
8721 // GetTypeForDeclarator. If so, don't save that as part of the
8722 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008723 if (ExplicitSignature.getLocalRangeBegin() ==
8724 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008725 // This would be much cheaper if we stored TypeLocs instead of
8726 // TypeSourceInfos.
8727 TypeLoc Result = ExplicitSignature.getResultLoc();
8728 unsigned Size = Result.getFullDataSize();
8729 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8730 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8731
8732 ExplicitSignature = FunctionProtoTypeLoc();
8733 }
John McCall82dc0092010-06-04 11:21:44 +00008734 }
Mike Stump1eb44332009-09-09 15:08:12 +00008735
John McCall711c52b2011-01-05 12:14:39 +00008736 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8737 CurBlock->FunctionType = T;
8738
8739 const FunctionType *Fn = T->getAs<FunctionType>();
8740 QualType RetTy = Fn->getResultType();
8741 bool isVariadic =
8742 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8743
John McCallc71a4912010-06-04 19:02:56 +00008744 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008745
John McCall82dc0092010-06-04 11:21:44 +00008746 // Don't allow returning a objc interface by value.
8747 if (RetTy->isObjCObjectType()) {
8748 Diag(ParamInfo.getSourceRange().getBegin(),
8749 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8750 return;
8751 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008752
John McCall82dc0092010-06-04 11:21:44 +00008753 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008754 // return type. TODO: what should we do with declarators like:
8755 // ^ * { ... }
8756 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008757 if (RetTy != Context.DependentTy)
8758 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008759
John McCall82dc0092010-06-04 11:21:44 +00008760 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008761 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008762 if (ExplicitSignature) {
8763 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8764 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008765 if (Param->getIdentifier() == 0 &&
8766 !Param->isImplicit() &&
8767 !Param->isInvalidDecl() &&
8768 !getLangOptions().CPlusPlus)
8769 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008770 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008771 }
John McCall82dc0092010-06-04 11:21:44 +00008772
8773 // Fake up parameter variables if we have a typedef, like
8774 // ^ fntype { ... }
8775 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8776 for (FunctionProtoType::arg_type_iterator
8777 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8778 ParmVarDecl *Param =
8779 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8780 ParamInfo.getSourceRange().getBegin(),
8781 *I);
John McCallc71a4912010-06-04 19:02:56 +00008782 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008783 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008784 }
John McCall82dc0092010-06-04 11:21:44 +00008785
John McCallc71a4912010-06-04 19:02:56 +00008786 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008787 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00008788 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00008789 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8790 CurBlock->TheDecl->param_end(),
8791 /*CheckParameterNames=*/false);
8792 }
8793
John McCall82dc0092010-06-04 11:21:44 +00008794 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008795 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008796
John McCallc71a4912010-06-04 19:02:56 +00008797 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008798 Diag(ParamInfo.getAttributes()->getLoc(),
8799 diag::warn_attribute_sentinel_not_variadic) << 1;
8800 // FIXME: remove the attribute.
8801 }
8802
8803 // Put the parameter variables in scope. We can bail out immediately
8804 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008805 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008806 return;
8807
Steve Naroff090276f2008-10-10 01:28:17 +00008808 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008809 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8810 (*AI)->setOwningFunction(CurBlock->TheDecl);
8811
Steve Naroff090276f2008-10-10 01:28:17 +00008812 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008813 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008814 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008815
Steve Naroff090276f2008-10-10 01:28:17 +00008816 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008817 }
John McCall7a9813c2010-01-22 00:28:27 +00008818 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008819}
8820
8821/// ActOnBlockError - If there is an error parsing a block, this callback
8822/// is invoked to pop the information about the block from the action impl.
8823void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008824 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008825 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008826 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008827}
8828
8829/// ActOnBlockStmtExpr - This is called when the body of a block statement
8830/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008831ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008832 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008833 // If blocks are disabled, emit an error.
8834 if (!LangOpts.Blocks)
8835 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008836
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008837 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008838
Steve Naroff090276f2008-10-10 01:28:17 +00008839 PopDeclContext();
8840
Steve Naroff4eb206b2008-09-03 18:15:37 +00008841 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008842 if (!BSI->ReturnType.isNull())
8843 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008844
Mike Stump56925862009-07-28 22:04:01 +00008845 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008846 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008847
John McCall469a1eb2011-02-02 13:00:07 +00008848 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008849 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8850 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008851
John McCallc71a4912010-06-04 19:02:56 +00008852 // If the user wrote a function type in some form, try to use that.
8853 if (!BSI->FunctionType.isNull()) {
8854 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8855
8856 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8857 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8858
8859 // Turn protoless block types into nullary block types.
8860 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008861 FunctionProtoType::ExtProtoInfo EPI;
8862 EPI.ExtInfo = Ext;
8863 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008864
8865 // Otherwise, if we don't need to change anything about the function type,
8866 // preserve its sugar structure.
8867 } else if (FTy->getResultType() == RetTy &&
8868 (!NoReturn || FTy->getNoReturnAttr())) {
8869 BlockTy = BSI->FunctionType;
8870
8871 // Otherwise, make the minimal modifications to the function type.
8872 } else {
8873 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008874 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8875 EPI.TypeQuals = 0; // FIXME: silently?
8876 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008877 BlockTy = Context.getFunctionType(RetTy,
8878 FPT->arg_type_begin(),
8879 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008880 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008881 }
8882
8883 // If we don't have a function type, just build one from nothing.
8884 } else {
John McCalle23cf432010-12-14 08:05:40 +00008885 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008886 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008887 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008888 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008889
John McCallc71a4912010-06-04 19:02:56 +00008890 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8891 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008892 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008893
Chris Lattner17a78302009-04-19 05:28:12 +00008894 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008895 if (getCurFunction()->NeedsScopeChecking() &&
8896 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008897 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008898
Chris Lattnere476bdc2011-02-17 23:58:47 +00008899 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008900
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008901 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8902 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8903 const VarDecl *variable = ci->getVariable();
8904 QualType T = variable->getType();
8905 QualType::DestructionKind destructKind = T.isDestructedType();
8906 if (destructKind != QualType::DK_none)
8907 getCurFunction()->setHasBranchProtectedScope();
8908 }
8909
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008910 computeNRVO(Body, getCurBlock());
8911
Benjamin Kramerd2486192011-07-12 14:11:05 +00008912 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8913 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8914 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8915
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008916 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008917}
8918
John McCall60d7b3a2010-08-24 06:29:42 +00008919ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008920 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008921 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008922 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008923 GetTypeFromParser(Ty, &TInfo);
8924 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008925}
8926
John McCall60d7b3a2010-08-24 06:29:42 +00008927ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008928 Expr *E, TypeSourceInfo *TInfo,
8929 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008930 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008931
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008932 // Get the va_list type
8933 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008934 if (VaListType->isArrayType()) {
8935 // Deal with implicit array decay; for example, on x86-64,
8936 // va_list is an array, but it's supposed to decay to
8937 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008938 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008939 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008940 ExprResult Result = UsualUnaryConversions(E);
8941 if (Result.isInvalid())
8942 return ExprError();
8943 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008944 } else {
8945 // Otherwise, the va_list argument must be an l-value because
8946 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008947 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008948 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008949 return ExprError();
8950 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008951
Douglas Gregordd027302009-05-19 23:10:31 +00008952 if (!E->isTypeDependent() &&
8953 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008954 return ExprError(Diag(E->getLocStart(),
8955 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008956 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008957 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008958
David Majnemer0adde122011-06-14 05:17:32 +00008959 if (!TInfo->getType()->isDependentType()) {
8960 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8961 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8962 << TInfo->getTypeLoc().getSourceRange()))
8963 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008964
David Majnemer0adde122011-06-14 05:17:32 +00008965 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8966 TInfo->getType(),
8967 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8968 << TInfo->getTypeLoc().getSourceRange()))
8969 return ExprError();
8970
Douglas Gregor4eb75222011-07-30 06:45:27 +00008971 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008972 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008973 TInfo->getType()->isObjCLifetimeType()
8974 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8975 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008976 << TInfo->getType()
8977 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008978 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008979
8980 // Check for va_arg where arguments of the given type will be promoted
8981 // (i.e. this va_arg is guaranteed to have undefined behavior).
8982 QualType PromoteType;
8983 if (TInfo->getType()->isPromotableIntegerType()) {
8984 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8985 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8986 PromoteType = QualType();
8987 }
8988 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8989 PromoteType = Context.DoubleTy;
8990 if (!PromoteType.isNull())
8991 Diag(TInfo->getTypeLoc().getBeginLoc(),
8992 diag::warn_second_parameter_to_va_arg_never_compatible)
8993 << TInfo->getType()
8994 << PromoteType
8995 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008996 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008997
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008998 QualType T = TInfo->getType().getNonLValueExprType(Context);
8999 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009000}
9001
John McCall60d7b3a2010-08-24 06:29:42 +00009002ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009003 // The type of __null will be int or long, depending on the size of
9004 // pointers on the target.
9005 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009006 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9007 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009008 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009009 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009010 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009011 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009012 Ty = Context.LongLongTy;
9013 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009014 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009015 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009016
Sebastian Redlf53597f2009-03-15 17:47:39 +00009017 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009018}
9019
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009020static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009021 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009022 if (!SemaRef.getLangOptions().ObjC1)
9023 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009024
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009025 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9026 if (!PT)
9027 return;
9028
9029 // Check if the destination is of type 'id'.
9030 if (!PT->isObjCIdType()) {
9031 // Check if the destination is the 'NSString' interface.
9032 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9033 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9034 return;
9035 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009036
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009037 // Strip off any parens and casts.
9038 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00009039 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009040 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009041
Douglas Gregor849b2432010-03-31 17:46:05 +00009042 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009043}
9044
Chris Lattner5cf216b2008-01-04 18:04:52 +00009045bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9046 SourceLocation Loc,
9047 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009048 Expr *SrcExpr, AssignmentAction Action,
9049 bool *Complained) {
9050 if (Complained)
9051 *Complained = false;
9052
Chris Lattner5cf216b2008-01-04 18:04:52 +00009053 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009054 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009055 bool isInvalid = false;
9056 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009057 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009058 ConversionFixItGenerator ConvHints;
9059 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009060
Chris Lattner5cf216b2008-01-04 18:04:52 +00009061 switch (ConvTy) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009062 default: llvm_unreachable("Unknown conversion type");
Chris Lattner5cf216b2008-01-04 18:04:52 +00009063 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009064 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009065 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009066 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9067 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009068 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009069 case IntToPointer:
9070 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009071 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9072 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009073 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009074 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009075 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009076 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009077 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9078 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009079 if (Hint.isNull() && !CheckInferredResultType) {
9080 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9081 }
9082 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009083 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009084 case IncompatiblePointerSign:
9085 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9086 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009087 case FunctionVoidPointer:
9088 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9089 break;
John McCall86c05f32011-02-01 00:10:29 +00009090 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009091 // Perform array-to-pointer decay if necessary.
9092 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9093
John McCall86c05f32011-02-01 00:10:29 +00009094 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9095 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9096 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9097 DiagKind = diag::err_typecheck_incompatible_address_space;
9098 break;
John McCallf85e1932011-06-15 23:02:42 +00009099
9100
9101 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009102 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009103 break;
John McCall86c05f32011-02-01 00:10:29 +00009104 }
9105
9106 llvm_unreachable("unknown error case for discarding qualifiers!");
9107 // fallthrough
9108 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009109 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009110 // If the qualifiers lost were because we were applying the
9111 // (deprecated) C++ conversion from a string literal to a char*
9112 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9113 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009114 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009115 // bit of refactoring (so that the second argument is an
9116 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009117 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009118 // C++ semantics.
9119 if (getLangOptions().CPlusPlus &&
9120 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9121 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009122 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9123 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009124 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009125 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009126 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009127 case IntToBlockPointer:
9128 DiagKind = diag::err_int_to_block_pointer;
9129 break;
9130 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009131 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009132 break;
Steve Naroff39579072008-10-14 22:18:38 +00009133 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009134 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009135 // it can give a more specific diagnostic.
9136 DiagKind = diag::warn_incompatible_qualified_id;
9137 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009138 case IncompatibleVectors:
9139 DiagKind = diag::warn_incompatible_vectors;
9140 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009141 case IncompatibleObjCWeakRef:
9142 DiagKind = diag::err_arc_weak_unavailable_assign;
9143 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009144 case Incompatible:
9145 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009146 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9147 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009148 isInvalid = true;
9149 break;
9150 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009151
Douglas Gregord4eea832010-04-09 00:35:39 +00009152 QualType FirstType, SecondType;
9153 switch (Action) {
9154 case AA_Assigning:
9155 case AA_Initializing:
9156 // The destination type comes first.
9157 FirstType = DstType;
9158 SecondType = SrcType;
9159 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009160
Douglas Gregord4eea832010-04-09 00:35:39 +00009161 case AA_Returning:
9162 case AA_Passing:
9163 case AA_Converting:
9164 case AA_Sending:
9165 case AA_Casting:
9166 // The source type comes first.
9167 FirstType = SrcType;
9168 SecondType = DstType;
9169 break;
9170 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009171
Anna Zaks67221552011-07-28 19:51:27 +00009172 PartialDiagnostic FDiag = PDiag(DiagKind);
9173 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9174
9175 // If we can fix the conversion, suggest the FixIts.
9176 assert(ConvHints.isNull() || Hint.isNull());
9177 if (!ConvHints.isNull()) {
9178 for (llvm::SmallVector<FixItHint, 1>::iterator
9179 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9180 HI != HE; ++HI)
9181 FDiag << *HI;
9182 } else {
9183 FDiag << Hint;
9184 }
9185 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9186
9187 Diag(Loc, FDiag);
9188
Douglas Gregor926df6c2011-06-11 01:09:30 +00009189 if (CheckInferredResultType)
9190 EmitRelatedResultTypeNote(SrcExpr);
9191
Douglas Gregora41a8c52010-04-22 00:20:18 +00009192 if (Complained)
9193 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009194 return isInvalid;
9195}
Anders Carlssone21555e2008-11-30 19:50:32 +00009196
Chris Lattner3bf68932009-04-25 21:59:05 +00009197bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009198 llvm::APSInt ICEResult;
9199 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9200 if (Result)
9201 *Result = ICEResult;
9202 return false;
9203 }
9204
Anders Carlssone21555e2008-11-30 19:50:32 +00009205 Expr::EvalResult EvalResult;
9206
Mike Stumpeed9cac2009-02-19 03:04:26 +00009207 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009208 EvalResult.HasSideEffects) {
9209 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9210
9211 if (EvalResult.Diag) {
9212 // We only show the note if it's not the usual "invalid subexpression"
9213 // or if it's actually in a subexpression.
9214 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9215 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9216 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9217 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009218
Anders Carlssone21555e2008-11-30 19:50:32 +00009219 return true;
9220 }
9221
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009222 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9223 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009224
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009225 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009226 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikied6471f72011-09-25 23:23:43 +00009227 != DiagnosticsEngine::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009228 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009229
Anders Carlssone21555e2008-11-30 19:50:32 +00009230 if (Result)
9231 *Result = EvalResult.Val.getInt();
9232 return false;
9233}
Douglas Gregore0762c92009-06-19 23:52:42 +00009234
Douglas Gregor2afce722009-11-26 00:44:06 +00009235void
Mike Stump1eb44332009-09-09 15:08:12 +00009236Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009237 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009238 ExpressionEvaluationContextRecord(NewContext,
9239 ExprTemporaries.size(),
9240 ExprNeedsCleanups));
9241 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009242}
9243
Richard Trieu67e29332011-08-02 04:35:43 +00009244void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009245 // Pop the current expression evaluation context off the stack.
9246 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9247 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009248
Douglas Gregor06d33692009-12-12 07:57:52 +00009249 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9250 if (Rec.PotentiallyReferenced) {
9251 // Mark any remaining declarations in the current position of the stack
9252 // as "referenced". If they were not meant to be referenced, semantic
9253 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009254 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009255 I = Rec.PotentiallyReferenced->begin(),
9256 IEnd = Rec.PotentiallyReferenced->end();
9257 I != IEnd; ++I)
9258 MarkDeclarationReferenced(I->first, I->second);
9259 }
9260
9261 if (Rec.PotentiallyDiagnosed) {
9262 // Emit any pending diagnostics.
9263 for (PotentiallyEmittedDiagnostics::iterator
9264 I = Rec.PotentiallyDiagnosed->begin(),
9265 IEnd = Rec.PotentiallyDiagnosed->end();
9266 I != IEnd; ++I)
9267 Diag(I->first, I->second);
9268 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009269 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009270
9271 // When are coming out of an unevaluated context, clear out any
9272 // temporaries that we may have created as part of the evaluation of
9273 // the expression in that context: they aren't relevant because they
9274 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009275 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009276 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9277 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009278 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9279
9280 // Otherwise, merge the contexts together.
9281 } else {
9282 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9283 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009284
9285 // Destroy the popped expression evaluation record.
9286 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009287}
Douglas Gregore0762c92009-06-19 23:52:42 +00009288
John McCallf85e1932011-06-15 23:02:42 +00009289void Sema::DiscardCleanupsInEvaluationContext() {
9290 ExprTemporaries.erase(
9291 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9292 ExprTemporaries.end());
9293 ExprNeedsCleanups = false;
9294}
9295
Douglas Gregore0762c92009-06-19 23:52:42 +00009296/// \brief Note that the given declaration was referenced in the source code.
9297///
9298/// This routine should be invoke whenever a given declaration is referenced
9299/// in the source code, and where that reference occurred. If this declaration
9300/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9301/// C99 6.9p3), then the declaration will be marked as used.
9302///
9303/// \param Loc the location where the declaration was referenced.
9304///
9305/// \param D the declaration that has been referenced by the source code.
9306void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9307 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009308
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009309 D->setReferenced();
9310
Douglas Gregorc070cc62010-06-17 23:14:26 +00009311 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009312 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009313
Richard Trieu67e29332011-08-02 04:35:43 +00009314 // Mark a parameter or variable declaration "used", regardless of whether
9315 // we're in a template or not. The reason for this is that unevaluated
9316 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9317 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009318 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009319 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009320 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009321 return;
9322 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009323
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009324 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9325 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009326
Douglas Gregore0762c92009-06-19 23:52:42 +00009327 // Do not mark anything as "used" within a dependent context; wait for
9328 // an instantiation.
9329 if (CurContext->isDependentContext())
9330 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009331
Douglas Gregor2afce722009-11-26 00:44:06 +00009332 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009333 case Unevaluated:
9334 // We are in an expression that is not potentially evaluated; do nothing.
9335 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009336
Douglas Gregorac7610d2009-06-22 20:57:11 +00009337 case PotentiallyEvaluated:
9338 // We are in a potentially-evaluated expression, so this declaration is
9339 // "used"; handle this below.
9340 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009341
Douglas Gregorac7610d2009-06-22 20:57:11 +00009342 case PotentiallyPotentiallyEvaluated:
9343 // We are in an expression that may be potentially evaluated; queue this
9344 // declaration reference until we know whether the expression is
9345 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009346 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009347 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009348
9349 case PotentiallyEvaluatedIfUsed:
9350 // Referenced declarations will only be used if the construct in the
9351 // containing expression is used.
9352 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009353 }
Mike Stump1eb44332009-09-09 15:08:12 +00009354
Douglas Gregore0762c92009-06-19 23:52:42 +00009355 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009356 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 if (Constructor->isDefaulted()) {
9358 if (Constructor->isDefaultConstructor()) {
9359 if (Constructor->isTrivial())
9360 return;
9361 if (!Constructor->isUsed(false))
9362 DefineImplicitDefaultConstructor(Loc, Constructor);
9363 } else if (Constructor->isCopyConstructor()) {
9364 if (!Constructor->isUsed(false))
9365 DefineImplicitCopyConstructor(Loc, Constructor);
9366 } else if (Constructor->isMoveConstructor()) {
9367 if (!Constructor->isUsed(false))
9368 DefineImplicitMoveConstructor(Loc, Constructor);
9369 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009370 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009371
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009372 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009373 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009374 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009375 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009376 if (Destructor->isVirtual())
9377 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009378 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009379 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009380 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009381 if (!MethodDecl->isUsed(false)) {
9382 if (MethodDecl->isCopyAssignmentOperator())
9383 DefineImplicitCopyAssignment(Loc, MethodDecl);
9384 else
9385 DefineImplicitMoveAssignment(Loc, MethodDecl);
9386 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009387 } else if (MethodDecl->isVirtual())
9388 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009389 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009390 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009391 // Recursive functions should be marked when used from another function.
9392 if (CurContext == Function) return;
9393
Mike Stump1eb44332009-09-09 15:08:12 +00009394 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009395 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009396 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009397 bool AlreadyInstantiated = false;
9398 if (FunctionTemplateSpecializationInfo *SpecInfo
9399 = Function->getTemplateSpecializationInfo()) {
9400 if (SpecInfo->getPointOfInstantiation().isInvalid())
9401 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009402 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009403 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009404 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009405 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009406 = Function->getMemberSpecializationInfo()) {
9407 if (MSInfo->getPointOfInstantiation().isInvalid())
9408 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009409 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009410 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009411 AlreadyInstantiated = true;
9412 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009413
Douglas Gregor60406be2010-01-16 22:29:39 +00009414 if (!AlreadyInstantiated) {
9415 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9416 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9417 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9418 Loc));
9419 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009420 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009421 }
John McCall15e310a2011-02-19 02:53:41 +00009422 } else {
9423 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009424 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9425 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009426 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009427 MarkDeclarationReferenced(Loc, *i);
9428 }
John McCall15e310a2011-02-19 02:53:41 +00009429 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009430
John McCall15e310a2011-02-19 02:53:41 +00009431 // Keep track of used but undefined functions.
9432 if (!Function->isPure() && !Function->hasBody() &&
9433 Function->getLinkage() != ExternalLinkage) {
9434 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9435 if (old.isInvalid()) old = Loc;
9436 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009437
John McCall15e310a2011-02-19 02:53:41 +00009438 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009439 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009440 }
Mike Stump1eb44332009-09-09 15:08:12 +00009441
Douglas Gregore0762c92009-06-19 23:52:42 +00009442 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009443 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009444 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009445 Var->getInstantiatedFromStaticDataMember()) {
9446 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9447 assert(MSInfo && "Missing member specialization information?");
9448 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9449 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9450 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009451 // This is a modification of an existing AST node. Notify listeners.
9452 if (ASTMutationListener *L = getASTMutationListener())
9453 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009454 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009455 }
9456 }
Mike Stump1eb44332009-09-09 15:08:12 +00009457
John McCall77efc682011-02-21 19:25:48 +00009458 // Keep track of used but undefined variables. We make a hole in
9459 // the warning for static const data members with in-line
9460 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009461 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009462 && Var->getLinkage() != ExternalLinkage
9463 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009464 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9465 if (old.isInvalid()) old = Loc;
9466 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009467
Douglas Gregore0762c92009-06-19 23:52:42 +00009468 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009469 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009470 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009471}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009472
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009473namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009474 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009475 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009476 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009477 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9478 Sema &S;
9479 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009480
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009481 public:
9482 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009483
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009484 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009485
9486 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9487 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009488 };
9489}
9490
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009491bool MarkReferencedDecls::TraverseTemplateArgument(
9492 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009493 if (Arg.getKind() == TemplateArgument::Declaration) {
9494 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9495 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009496
9497 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009498}
9499
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009500bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009501 if (ClassTemplateSpecializationDecl *Spec
9502 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9503 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009504 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009505 }
9506
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009507 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009508}
9509
9510void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9511 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009512 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009513}
9514
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009515namespace {
9516 /// \brief Helper class that marks all of the declarations referenced by
9517 /// potentially-evaluated subexpressions as "referenced".
9518 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9519 Sema &S;
9520
9521 public:
9522 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9523
9524 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9525
9526 void VisitDeclRefExpr(DeclRefExpr *E) {
9527 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9528 }
9529
9530 void VisitMemberExpr(MemberExpr *E) {
9531 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009532 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009533 }
9534
9535 void VisitCXXNewExpr(CXXNewExpr *E) {
9536 if (E->getConstructor())
9537 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9538 if (E->getOperatorNew())
9539 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9540 if (E->getOperatorDelete())
9541 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009542 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009543 }
9544
9545 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9546 if (E->getOperatorDelete())
9547 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009548 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9549 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9550 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9551 S.MarkDeclarationReferenced(E->getLocStart(),
9552 S.LookupDestructor(Record));
9553 }
9554
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009555 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009556 }
9557
9558 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9559 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009560 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009561 }
9562
9563 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9564 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9565 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009566
9567 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9568 Visit(E->getExpr());
9569 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009570 };
9571}
9572
9573/// \brief Mark any declarations that appear within this expression or any
9574/// potentially-evaluated subexpressions as "referenced".
9575void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9576 EvaluatedExprMarker(*this).Visit(E);
9577}
9578
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009579/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9580/// of the program being compiled.
9581///
9582/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009583/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009584/// possibility that the code will actually be executable. Code in sizeof()
9585/// expressions, code used only during overload resolution, etc., are not
9586/// potentially evaluated. This routine will suppress such diagnostics or,
9587/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009588/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009589/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009590///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009591/// This routine should be used for all diagnostics that describe the run-time
9592/// behavior of a program, such as passing a non-POD value through an ellipsis.
9593/// Failure to do so will likely result in spurious diagnostics or failures
9594/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009595bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009596 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009597 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009598 case Unevaluated:
9599 // The argument will never be evaluated, so don't complain.
9600 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009601
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009602 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009603 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009604 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009605 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009606 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009607 }
9608 else
9609 Diag(Loc, PD);
9610
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009611 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009612
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009613 case PotentiallyPotentiallyEvaluated:
9614 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9615 break;
9616 }
9617
9618 return false;
9619}
9620
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009621bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9622 CallExpr *CE, FunctionDecl *FD) {
9623 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9624 return false;
9625
9626 PartialDiagnostic Note =
9627 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9628 << FD->getDeclName() : PDiag();
9629 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009630
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009631 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009632 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009633 PDiag(diag::err_call_function_incomplete_return)
9634 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009635 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009636 << CE->getSourceRange(),
9637 std::make_pair(NoteLoc, Note)))
9638 return true;
9639
9640 return false;
9641}
9642
Douglas Gregor92c3a042011-01-19 16:50:08 +00009643// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009644// will prevent this condition from triggering, which is what we want.
9645void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9646 SourceLocation Loc;
9647
John McCalla52ef082009-11-11 02:41:58 +00009648 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009649 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009650
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009651 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009652 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009653 return;
9654
Douglas Gregor92c3a042011-01-19 16:50:08 +00009655 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9656
John McCallc8d8ac52009-11-12 00:06:05 +00009657 // Greylist some idioms by putting them into a warning subcategory.
9658 if (ObjCMessageExpr *ME
9659 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9660 Selector Sel = ME->getSelector();
9661
John McCallc8d8ac52009-11-12 00:06:05 +00009662 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +00009663 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009664 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9665
9666 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009667 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009668 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9669 }
John McCalla52ef082009-11-11 02:41:58 +00009670
John McCall5a881bb2009-10-12 21:59:07 +00009671 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009672 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009673 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009674 return;
9675
Douglas Gregor92c3a042011-01-19 16:50:08 +00009676 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009677 Loc = Op->getOperatorLoc();
9678 } else {
9679 // Not an assignment.
9680 return;
9681 }
9682
Douglas Gregor55b38842010-04-14 16:09:52 +00009683 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009684
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009685 SourceLocation Open = E->getSourceRange().getBegin();
9686 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9687 Diag(Loc, diag::note_condition_assign_silence)
9688 << FixItHint::CreateInsertion(Open, "(")
9689 << FixItHint::CreateInsertion(Close, ")");
9690
Douglas Gregor92c3a042011-01-19 16:50:08 +00009691 if (IsOrAssign)
9692 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9693 << FixItHint::CreateReplacement(Loc, "!=");
9694 else
9695 Diag(Loc, diag::note_condition_assign_to_comparison)
9696 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009697}
9698
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009699/// \brief Redundant parentheses over an equality comparison can indicate
9700/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009701void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009702 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009703 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009704 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9705 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009706 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009707 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009708 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009709
Richard Trieuccd891a2011-09-09 01:45:06 +00009710 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009711
9712 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009713 if (opE->getOpcode() == BO_EQ &&
9714 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9715 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009716 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009717
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009718 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009719 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009720 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9721 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009722 Diag(Loc, diag::note_equality_comparison_to_assign)
9723 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009724 }
9725}
9726
John Wiegley429bb272011-04-08 18:41:53 +00009727ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009728 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009729 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9730 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009731
John McCall864c0412011-04-26 20:42:42 +00009732 ExprResult result = CheckPlaceholderExpr(E);
9733 if (result.isInvalid()) return ExprError();
9734 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009735
John McCall864c0412011-04-26 20:42:42 +00009736 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009737 if (getLangOptions().CPlusPlus)
9738 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9739
John Wiegley429bb272011-04-08 18:41:53 +00009740 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9741 if (ERes.isInvalid())
9742 return ExprError();
9743 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009744
9745 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009746 if (!T->isScalarType()) { // C99 6.8.4.1p1
9747 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9748 << T << E->getSourceRange();
9749 return ExprError();
9750 }
John McCall5a881bb2009-10-12 21:59:07 +00009751 }
9752
John Wiegley429bb272011-04-08 18:41:53 +00009753 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009754}
Douglas Gregor586596f2010-05-06 17:25:47 +00009755
John McCall60d7b3a2010-08-24 06:29:42 +00009756ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009757 Expr *SubExpr) {
9758 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009759 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009760
Richard Trieuccd891a2011-09-09 01:45:06 +00009761 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009762}
John McCall2a984ca2010-10-12 00:20:44 +00009763
John McCall1de4d4e2011-04-07 08:22:57 +00009764namespace {
John McCall755d8492011-04-12 00:42:48 +00009765 /// A visitor for rebuilding a call to an __unknown_any expression
9766 /// to have an appropriate type.
9767 struct RebuildUnknownAnyFunction
9768 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9769
9770 Sema &S;
9771
9772 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9773
9774 ExprResult VisitStmt(Stmt *S) {
9775 llvm_unreachable("unexpected statement!");
9776 return ExprError();
9777 }
9778
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009779 ExprResult VisitExpr(Expr *E) {
9780 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9781 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009782 return ExprError();
9783 }
9784
9785 /// Rebuild an expression which simply semantically wraps another
9786 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009787 template <class T> ExprResult rebuildSugarExpr(T *E) {
9788 ExprResult SubResult = Visit(E->getSubExpr());
9789 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009790
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009791 Expr *SubExpr = SubResult.take();
9792 E->setSubExpr(SubExpr);
9793 E->setType(SubExpr->getType());
9794 E->setValueKind(SubExpr->getValueKind());
9795 assert(E->getObjectKind() == OK_Ordinary);
9796 return E;
John McCall755d8492011-04-12 00:42:48 +00009797 }
9798
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009799 ExprResult VisitParenExpr(ParenExpr *E) {
9800 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009801 }
9802
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009803 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9804 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009805 }
9806
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009807 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9808 ExprResult SubResult = Visit(E->getSubExpr());
9809 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009810
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009811 Expr *SubExpr = SubResult.take();
9812 E->setSubExpr(SubExpr);
9813 E->setType(S.Context.getPointerType(SubExpr->getType()));
9814 assert(E->getValueKind() == VK_RValue);
9815 assert(E->getObjectKind() == OK_Ordinary);
9816 return E;
John McCall755d8492011-04-12 00:42:48 +00009817 }
9818
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009819 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9820 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009821
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009822 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009823
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009824 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009825 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009826 !(isa<CXXMethodDecl>(VD) &&
9827 cast<CXXMethodDecl>(VD)->isInstance()))
9828 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009829
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009830 return E;
John McCall755d8492011-04-12 00:42:48 +00009831 }
9832
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009833 ExprResult VisitMemberExpr(MemberExpr *E) {
9834 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009835 }
9836
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009837 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9838 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009839 }
9840 };
9841}
9842
9843/// Given a function expression of unknown-any type, try to rebuild it
9844/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009845static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9846 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9847 if (Result.isInvalid()) return ExprError();
9848 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009849}
9850
9851namespace {
John McCall379b5152011-04-11 07:02:50 +00009852 /// A visitor for rebuilding an expression of type __unknown_anytype
9853 /// into one which resolves the type directly on the referring
9854 /// expression. Strict preservation of the original source
9855 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009856 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009857 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009858
9859 Sema &S;
9860
9861 /// The current destination type.
9862 QualType DestType;
9863
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009864 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9865 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009866
John McCalla5fc4722011-04-09 22:50:59 +00009867 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009868 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009869 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009870 }
9871
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009872 ExprResult VisitExpr(Expr *E) {
9873 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9874 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009875 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009876 }
9877
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009878 ExprResult VisitCallExpr(CallExpr *E);
9879 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009880
John McCalla5fc4722011-04-09 22:50:59 +00009881 /// Rebuild an expression which simply semantically wraps another
9882 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009883 template <class T> ExprResult rebuildSugarExpr(T *E) {
9884 ExprResult SubResult = Visit(E->getSubExpr());
9885 if (SubResult.isInvalid()) return ExprError();
9886 Expr *SubExpr = SubResult.take();
9887 E->setSubExpr(SubExpr);
9888 E->setType(SubExpr->getType());
9889 E->setValueKind(SubExpr->getValueKind());
9890 assert(E->getObjectKind() == OK_Ordinary);
9891 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009892 }
John McCall1de4d4e2011-04-07 08:22:57 +00009893
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009894 ExprResult VisitParenExpr(ParenExpr *E) {
9895 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009896 }
9897
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009898 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9899 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009900 }
9901
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009902 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9903 const PointerType *Ptr = DestType->getAs<PointerType>();
9904 if (!Ptr) {
9905 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9906 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009907 return ExprError();
9908 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009909 assert(E->getValueKind() == VK_RValue);
9910 assert(E->getObjectKind() == OK_Ordinary);
9911 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009912
9913 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009914 DestType = Ptr->getPointeeType();
9915 ExprResult SubResult = Visit(E->getSubExpr());
9916 if (SubResult.isInvalid()) return ExprError();
9917 E->setSubExpr(SubResult.take());
9918 return E;
John McCall755d8492011-04-12 00:42:48 +00009919 }
9920
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009921 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009922
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009923 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009924
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009925 ExprResult VisitMemberExpr(MemberExpr *E) {
9926 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009927 }
John McCalla5fc4722011-04-09 22:50:59 +00009928
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009929 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9930 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009931 }
9932 };
9933}
9934
John McCall379b5152011-04-11 07:02:50 +00009935/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009936ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9937 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009938
9939 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009940 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009941 FK_FunctionPointer,
9942 FK_BlockPointer
9943 };
9944
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009945 FnKind Kind;
9946 QualType CalleeType = CalleeExpr->getType();
9947 if (CalleeType == S.Context.BoundMemberTy) {
9948 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9949 Kind = FK_MemberFunction;
9950 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9951 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9952 CalleeType = Ptr->getPointeeType();
9953 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009954 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009955 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9956 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009957 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009958 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009959
9960 // Verify that this is a legal result type of a function.
9961 if (DestType->isArrayType() || DestType->isFunctionType()) {
9962 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009963 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009964 diagID = diag::err_block_returning_array_function;
9965
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009966 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009967 << DestType->isFunctionType() << DestType;
9968 return ExprError();
9969 }
9970
9971 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009972 E->setType(DestType.getNonLValueExprType(S.Context));
9973 E->setValueKind(Expr::getValueKindForType(DestType));
9974 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009975
9976 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009977 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009978 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009979 Proto->arg_type_begin(),
9980 Proto->getNumArgs(),
9981 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009982 else
9983 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009984 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009985
9986 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009987 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009988 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009989 // Nothing to do.
9990 break;
9991
9992 case FK_FunctionPointer:
9993 DestType = S.Context.getPointerType(DestType);
9994 break;
9995
9996 case FK_BlockPointer:
9997 DestType = S.Context.getBlockPointerType(DestType);
9998 break;
9999 }
10000
10001 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010002 ExprResult CalleeResult = Visit(CalleeExpr);
10003 if (!CalleeResult.isUsable()) return ExprError();
10004 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000010005
10006 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010007 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010008}
10009
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010010ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010011 // Verify that this is a legal result type of a call.
10012 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010013 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000010014 << DestType->isFunctionType() << DestType;
10015 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010016 }
10017
John McCall48218c62011-07-13 17:56:40 +000010018 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010019 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10020 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10021 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000010022 }
John McCall755d8492011-04-12 00:42:48 +000010023
John McCall379b5152011-04-11 07:02:50 +000010024 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010025 E->setType(DestType.getNonReferenceType());
10026 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010027
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010028 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010029}
10030
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010031ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010032 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010033 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10034 assert(E->getValueKind() == VK_RValue);
10035 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000010036
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010037 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000010038
John McCall379b5152011-04-11 07:02:50 +000010039 // Rebuild the sub-expression as the pointee (function) type.
10040 DestType = DestType->castAs<PointerType>()->getPointeeType();
10041
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010042 ExprResult Result = Visit(E->getSubExpr());
10043 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010044
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010045 E->setSubExpr(Result.take());
10046 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010047}
10048
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010049ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10050 ExprValueKind ValueKind = VK_LValue;
10051 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000010052
10053 // We know how to make this work for certain kinds of decls:
10054
10055 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010056 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10057 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10058 DestType = Ptr->getPointeeType();
10059 ExprResult Result = resolveDecl(E, VD);
10060 if (Result.isInvalid()) return ExprError();
10061 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000010062 CK_FunctionToPointerDecay, VK_RValue);
10063 }
10064
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010065 if (!Type->isFunctionType()) {
10066 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10067 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000010068 return ExprError();
10069 }
John McCall379b5152011-04-11 07:02:50 +000010070
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010071 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10072 if (MD->isInstance()) {
10073 ValueKind = VK_RValue;
10074 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000010075 }
10076
John McCall379b5152011-04-11 07:02:50 +000010077 // Function references aren't l-values in C.
10078 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010079 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000010080
10081 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010082 } else if (isa<VarDecl>(VD)) {
10083 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10084 Type = RefTy->getPointeeType();
10085 } else if (Type->isFunctionType()) {
10086 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10087 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000010088 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010089 }
10090
10091 // - nothing else
10092 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010093 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10094 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010095 return ExprError();
10096 }
10097
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010098 VD->setType(DestType);
10099 E->setType(Type);
10100 E->setValueKind(ValueKind);
10101 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010102}
10103
John McCall1de4d4e2011-04-07 08:22:57 +000010104/// Check a cast of an unknown-any type. We intentionally only
10105/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000010106ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10107 Expr *CastExpr, CastKind &CastKind,
10108 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010109 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010110 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010111 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010112
Richard Trieuccd891a2011-09-09 01:45:06 +000010113 CastExpr = result.take();
10114 VK = CastExpr->getValueKind();
10115 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010116
Richard Trieuccd891a2011-09-09 01:45:06 +000010117 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010118}
10119
Richard Trieuccd891a2011-09-09 01:45:06 +000010120static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10121 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010122 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010123 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010124 E = E->IgnoreParenImpCasts();
10125 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10126 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010127 diagID = diag::err_uncasted_call_of_unknown_any;
10128 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010129 break;
John McCall379b5152011-04-11 07:02:50 +000010130 }
John McCall1de4d4e2011-04-07 08:22:57 +000010131 }
10132
John McCall379b5152011-04-11 07:02:50 +000010133 SourceLocation loc;
10134 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010135 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010136 loc = ref->getLocation();
10137 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010138 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010139 loc = mem->getMemberLoc();
10140 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010141 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010142 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000010143 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000010144 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010145 if (!d) {
10146 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10147 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10148 << orig->getSourceRange();
10149 return ExprError();
10150 }
John McCall379b5152011-04-11 07:02:50 +000010151 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010152 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10153 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010154 return ExprError();
10155 }
10156
10157 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010158
10159 // Never recoverable.
10160 return ExprError();
10161}
10162
John McCall2a984ca2010-10-12 00:20:44 +000010163/// Check for operands with placeholder types and complain if found.
10164/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010165ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010166 // Placeholder types are always *exactly* the appropriate builtin type.
10167 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010168
John McCall1de4d4e2011-04-07 08:22:57 +000010169 // Overloaded expressions.
10170 if (type == Context.OverloadTy)
10171 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010172 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010173 QualType(),
10174 diag::err_ovl_unresolvable);
10175
John McCall864c0412011-04-26 20:42:42 +000010176 // Bound member functions.
10177 if (type == Context.BoundMemberTy) {
10178 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10179 << E->getSourceRange();
10180 return ExprError();
10181 }
10182
John McCall1de4d4e2011-04-07 08:22:57 +000010183 // Expressions of unknown type.
10184 if (type == Context.UnknownAnyTy)
10185 return diagnoseUnknownAnyExpr(*this, E);
10186
10187 assert(!type->isPlaceholderType());
10188 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010189}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010190
Richard Trieuccd891a2011-09-09 01:45:06 +000010191bool Sema::CheckCaseExpression(Expr *E) {
10192 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010193 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010194 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10195 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010196 return false;
10197}