blob: 5fd7e4e22bbeb49471cbf1869f94d7a79e1e5c9c [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
Sebastian Redlb49c46c2011-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 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000056
57 // See if this function is unavailable.
58 if (D->getAvailability() == AR_Unavailable &&
59 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
60 return false;
61
Sebastian Redlb49c46c2011-09-24 17:48:00 +000062 return true;
63}
David Chisnall9f57c292009-08-17 16:35:33 +000064
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000065static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
66 NamedDecl *D, SourceLocation Loc,
67 const ObjCInterfaceDecl *UnknownObjCClass) {
68 // See if this declaration is unavailable or deprecated.
69 std::string Message;
70 AvailabilityResult Result = D->getAvailability(&Message);
71 switch (Result) {
72 case AR_Available:
73 case AR_NotYetIntroduced:
74 break;
75
76 case AR_Deprecated:
77 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
78 break;
79
80 case AR_Unavailable:
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000081 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 if (Message.empty()) {
83 if (!UnknownObjCClass)
84 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
85 else
86 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
87 << D->getDeclName();
88 }
89 else
90 S.Diag(Loc, diag::err_unavailable_message)
91 << D->getDeclName() << Message;
92 S.Diag(D->getLocation(), diag::note_unavailable_here)
93 << isa<FunctionDecl>(D) << false;
94 }
95 break;
96 }
97 return Result;
98}
99
Douglas Gregor171c45a2009-02-18 21:56:37 +0000100/// \brief Determine whether the use of this declaration is valid, and
101/// emit any corresponding diagnostics.
102///
103/// This routine diagnoses various problems with referencing
104/// declarations that can occur when using a declaration. For example,
105/// it might warn if a deprecated or unavailable declaration is being
106/// used, or produce an error (and return true) if a C++0x deleted
107/// function is being used.
108///
109/// \returns true if there was an error (this declaration cannot be
110/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000111///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000112bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000113 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000114 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
115 // If there were any diagnostics suppressed by template argument deduction,
116 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000117 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000118 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
119 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000121 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
122 Diag(Suppressed[I].first, Suppressed[I].second);
123
124 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000125 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000126 // entry from the table, because we want to avoid ever emitting these
127 // diagnostics again.
128 Suppressed.clear();
129 }
130 }
131
Richard Smith30482bc2011-02-20 03:19:35 +0000132 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000133 if (ParsingInitForAutoVars.count(D)) {
134 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
135 << D->getDeclName();
136 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000137 }
138
Douglas Gregor171c45a2009-02-18 21:56:37 +0000139 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000141 if (FD->isDeleted()) {
142 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000143 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000144 return true;
145 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000146 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000147 AvailabilityResult Result =
148 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000149
Anders Carlsson73067a02010-10-22 23:37:08 +0000150 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000151 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000152 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000153 // For available enumerator, it will become unavailable/deprecated
154 // if its enum declaration is as such.
155 if (Result == AR_Available)
156 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
157 const DeclContext *DC = ECD->getDeclContext();
158 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000159 DiagnoseAvailabilityOfDecl(*this,
160 const_cast< EnumDecl *>(TheEnumDecl),
161 Loc, UnknownObjCClass);
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000162 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000163 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000164}
165
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000166/// \brief Retrieve the message suffix that should be added to a
167/// diagnostic complaining about the given function being deleted or
168/// unavailable.
169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170 // FIXME: C++0x implicitly-deleted special member functions could be
171 // detected here so that we could improve diagnostics to say, e.g.,
172 // "base class 'A' had a deleted copy constructor".
173 if (FD->isDeleted())
174 return std::string();
175
176 std::string Message;
177 if (FD->getAvailability(&Message))
178 return ": " + Message;
179
180 return std::string();
181}
182
John McCallb46f2872011-09-09 07:56:05 +0000183/// DiagnoseSentinelCalls - This routine checks whether a call or
184/// message-send is to a declaration with the sentinel attribute, and
185/// if so, it checks that the requirements of the sentinel are
186/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000188 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000189 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000190 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000191 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000192
John McCallb46f2872011-09-09 07:56:05 +0000193 // The number of formal parameters of the declaration.
194 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000195
John McCallb46f2872011-09-09 07:56:05 +0000196 // The kind of declaration. This is also an index into a %select in
197 // the diagnostic.
198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000201 numFormalParams = MD->param_size();
202 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000204 numFormalParams = FD->param_size();
205 calleeType = CT_Function;
206 } else if (isa<VarDecl>(D)) {
207 QualType type = cast<ValueDecl>(D)->getType();
208 const FunctionType *fn = 0;
209 if (const PointerType *ptr = type->getAs<PointerType>()) {
210 fn = ptr->getPointeeType()->getAs<FunctionType>();
211 if (!fn) return;
212 calleeType = CT_Function;
213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214 fn = ptr->getPointeeType()->castAs<FunctionType>();
215 calleeType = CT_Block;
216 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000217 return;
John McCallb46f2872011-09-09 07:56:05 +0000218 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000219
John McCallb46f2872011-09-09 07:56:05 +0000220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221 numFormalParams = proto->getNumArgs();
222 } else {
223 numFormalParams = 0;
224 }
225 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000226 return;
227 }
John McCallb46f2872011-09-09 07:56:05 +0000228
229 // "nullPos" is the number of formal parameters at the end which
230 // effectively count as part of the variadic arguments. This is
231 // useful if you would prefer to not have *any* formal parameters,
232 // but the language forces you to have at least one.
233 unsigned nullPos = attr->getNullPos();
234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236
237 // The number of arguments which should follow the sentinel.
238 unsigned numArgsAfterSentinel = attr->getSentinel();
239
240 // If there aren't enough arguments for all the formal parameters,
241 // the sentinel, and the args after the sentinel, complain.
242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000245 return;
246 }
John McCallb46f2872011-09-09 07:56:05 +0000247
248 // Otherwise, find the sentinel expression.
249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000250 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000251 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000252
253 // nullptr_t is always treated as null.
254 if (sentinelExpr->getType()->isNullPtrType()) return;
255
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000256 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000257 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
258 Expr::NPC_ValueDependentIsNull))
259 return;
260
261 // Unfortunately, __null has type 'int'.
262 if (isa<GNUNullExpr>(sentinelExpr)) return;
263
John McCallb46f2872011-09-09 07:56:05 +0000264 // Pick a reasonable string to insert. Optimistically use 'nil' or
265 // 'NULL' if those are actually defined in the context. Only use
266 // 'nil' for ObjC methods, where it's much more likely that the
267 // variadic arguments form a list of object pointers.
268 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000269 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
270 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000271 if (calleeType == CT_Method &&
272 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000273 NullValue = "nil";
274 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
275 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000276 else
John McCallb46f2872011-09-09 07:56:05 +0000277 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000278
279 if (MissingNilLoc.isInvalid())
280 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
281 else
282 Diag(MissingNilLoc, diag::warn_missing_sentinel)
283 << calleeType
284 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000285 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000286}
287
Richard Trieuba63ce62011-09-09 01:45:06 +0000288SourceRange Sema::getExprRange(Expr *E) const {
289 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000290}
291
Chris Lattner513165e2008-07-25 21:10:04 +0000292//===----------------------------------------------------------------------===//
293// Standard Promotions and Conversions
294//===----------------------------------------------------------------------===//
295
Chris Lattner513165e2008-07-25 21:10:04 +0000296/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000297ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000298 // Handle any placeholder expressions which made it here.
299 if (E->getType()->isPlaceholderType()) {
300 ExprResult result = CheckPlaceholderExpr(E);
301 if (result.isInvalid()) return ExprError();
302 E = result.take();
303 }
304
Chris Lattner513165e2008-07-25 21:10:04 +0000305 QualType Ty = E->getType();
306 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
307
Chris Lattner513165e2008-07-25 21:10:04 +0000308 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000309 E = ImpCastExprToType(E, Context.getPointerType(Ty),
310 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000311 else if (Ty->isArrayType()) {
312 // In C90 mode, arrays only promote to pointers if the array expression is
313 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
314 // type 'array of type' is converted to an expression that has type 'pointer
315 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
316 // that has type 'array of type' ...". The relevant change is "an lvalue"
317 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000318 //
319 // C++ 4.2p1:
320 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
321 // T" can be converted to an rvalue of type "pointer to T".
322 //
John McCall086a4642010-11-24 05:12:34 +0000323 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000324 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
325 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000326 }
John Wiegley01296292011-04-08 18:41:53 +0000327 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000328}
329
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000330static void CheckForNullPointerDereference(Sema &S, Expr *E) {
331 // Check to see if we are dereferencing a null pointer. If so,
332 // and if not volatile-qualified, this is undefined behavior that the
333 // optimizer will delete, so warn about it. People sometimes try to use this
334 // to get a deterministic trap and are surprised by clang's behavior. This
335 // only handles the pattern "*null", which is a very syntactic check.
336 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
337 if (UO->getOpcode() == UO_Deref &&
338 UO->getSubExpr()->IgnoreParenCasts()->
339 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
340 !UO->getType().isVolatileQualified()) {
341 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
342 S.PDiag(diag::warn_indirection_through_null)
343 << UO->getSubExpr()->getSourceRange());
344 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
345 S.PDiag(diag::note_indirection_through_null));
346 }
347}
348
John Wiegley01296292011-04-08 18:41:53 +0000349ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000350 // Handle any placeholder expressions which made it here.
351 if (E->getType()->isPlaceholderType()) {
352 ExprResult result = CheckPlaceholderExpr(E);
353 if (result.isInvalid()) return ExprError();
354 E = result.take();
355 }
356
John McCallf3735e02010-12-01 04:43:34 +0000357 // C++ [conv.lval]p1:
358 // A glvalue of a non-function, non-array type T can be
359 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000360 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000361
John McCall27584242010-12-06 20:48:59 +0000362 QualType T = E->getType();
363 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000364
Eli Friedman0dfb8892011-10-06 23:00:33 +0000365 // We can't do lvalue-to-rvalue on atomics yet.
366 if (T->getAs<AtomicType>())
367 return Owned(E);
368
John McCall27584242010-12-06 20:48:59 +0000369 // Create a load out of an ObjCProperty l-value, if necessary.
370 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000371 ExprResult Res = ConvertPropertyForRValue(E);
372 if (Res.isInvalid())
373 return Owned(E);
374 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000375 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000376 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000377 }
John McCall27584242010-12-06 20:48:59 +0000378
379 // We don't want to throw lvalue-to-rvalue casts on top of
380 // expressions of certain types in C++.
381 if (getLangOptions().CPlusPlus &&
382 (E->getType() == Context.OverloadTy ||
383 T->isDependentType() ||
384 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000385 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000386
387 // The C standard is actually really unclear on this point, and
388 // DR106 tells us what the result should be but not why. It's
389 // generally best to say that void types just doesn't undergo
390 // lvalue-to-rvalue at all. Note that expressions of unqualified
391 // 'void' type are never l-values, but qualified void can be.
392 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000393 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000394
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000395 CheckForNullPointerDereference(*this, E);
396
John McCall27584242010-12-06 20:48:59 +0000397 // C++ [conv.lval]p1:
398 // [...] If T is a non-class type, the type of the prvalue is the
399 // cv-unqualified version of T. Otherwise, the type of the
400 // rvalue is T.
401 //
402 // C99 6.3.2.1p2:
403 // If the lvalue has qualified type, the value has the unqualified
404 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000405 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000406 if (T.hasQualifiers())
407 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000408
409 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
410 E, 0, VK_RValue));
411
412 return Res;
John McCall27584242010-12-06 20:48:59 +0000413}
414
John Wiegley01296292011-04-08 18:41:53 +0000415ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
416 ExprResult Res = DefaultFunctionArrayConversion(E);
417 if (Res.isInvalid())
418 return ExprError();
419 Res = DefaultLvalueConversion(Res.take());
420 if (Res.isInvalid())
421 return ExprError();
422 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000423}
424
425
Chris Lattner513165e2008-07-25 21:10:04 +0000426/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000427/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000428/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000429/// apply if the array is an argument to the sizeof or address (&) operators.
430/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000431ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000432 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000433 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
434 if (Res.isInvalid())
435 return Owned(E);
436 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000437
John McCallf3735e02010-12-01 04:43:34 +0000438 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000439 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000440
441 // Half FP is a bit different: it's a storage-only type, meaning that any
442 // "use" of it should be promoted to float.
443 if (Ty->isHalfType())
444 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
445
John McCallf3735e02010-12-01 04:43:34 +0000446 // Try to perform integral promotions if the object has a theoretically
447 // promotable type.
448 if (Ty->isIntegralOrUnscopedEnumerationType()) {
449 // C99 6.3.1.1p2:
450 //
451 // The following may be used in an expression wherever an int or
452 // unsigned int may be used:
453 // - an object or expression with an integer type whose integer
454 // conversion rank is less than or equal to the rank of int
455 // and unsigned int.
456 // - A bit-field of type _Bool, int, signed int, or unsigned int.
457 //
458 // If an int can represent all values of the original type, the
459 // value is converted to an int; otherwise, it is converted to an
460 // unsigned int. These are called the integer promotions. All
461 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000462
John McCallf3735e02010-12-01 04:43:34 +0000463 QualType PTy = Context.isPromotableBitField(E);
464 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000465 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
466 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000467 }
468 if (Ty->isPromotableIntegerType()) {
469 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000470 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
471 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000472 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000473 }
John Wiegley01296292011-04-08 18:41:53 +0000474 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000475}
476
Chris Lattner2ce500f2008-07-25 22:25:12 +0000477/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000478/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000479/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000480ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
481 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000482 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000483
John Wiegley01296292011-04-08 18:41:53 +0000484 ExprResult Res = UsualUnaryConversions(E);
485 if (Res.isInvalid())
486 return Owned(E);
487 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000488
Chris Lattner2ce500f2008-07-25 22:25:12 +0000489 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000490 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000491 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
492
John McCall4bb057d2011-08-27 22:06:17 +0000493 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000494 // promotion, even on class types, but note:
495 // C++11 [conv.lval]p2:
496 // When an lvalue-to-rvalue conversion occurs in an unevaluated
497 // operand or a subexpression thereof the value contained in the
498 // referenced object is not accessed. Otherwise, if the glvalue
499 // has a class type, the conversion copy-initializes a temporary
500 // of type T from the glvalue and the result of the conversion
501 // is a prvalue for the temporary.
502 // FIXME: add some way to gate this entire thing for correctness in
503 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000504 if (getLangOptions().CPlusPlus && E->isGLValue() &&
505 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000506 ExprResult Temp = PerformCopyInitialization(
507 InitializedEntity::InitializeTemporary(E->getType()),
508 E->getExprLoc(),
509 Owned(E));
510 if (Temp.isInvalid())
511 return ExprError();
512 E = Temp.get();
513 }
514
John Wiegley01296292011-04-08 18:41:53 +0000515 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000516}
517
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000518/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
519/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000520/// interfaces passed by value.
521ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000522 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000523 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
524 // Strip the unbridged-cast placeholder expression off, if applicable.
525 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
526 (CT == VariadicMethod ||
527 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
528 E = stripARCUnbridgedCast(E);
529
530 // Otherwise, do normal placeholder checking.
531 } else {
532 ExprResult ExprRes = CheckPlaceholderExpr(E);
533 if (ExprRes.isInvalid())
534 return ExprError();
535 E = ExprRes.take();
536 }
537 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000538
John McCall4124c492011-10-17 18:40:02 +0000539 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000540 if (ExprRes.isInvalid())
541 return ExprError();
542 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000543
Douglas Gregor347e0f22011-05-21 19:26:31 +0000544 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000545 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000546 DiagRuntimeBehavior(E->getLocStart(), 0,
547 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
548 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000549 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000550
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000551 // Complain about passing non-POD types through varargs. However, don't
552 // perform this check for incomplete types, which we can get here when we're
553 // in an unevaluated context.
554 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000555 // C++0x [expr.call]p7:
556 // Passing a potentially-evaluated argument of class type (Clause 9)
557 // having a non-trivial copy constructor, a non-trivial move constructor,
558 // or a non-trivial destructor, with no corresponding parameter,
559 // is conditionally-supported with implementation-defined semantics.
560 bool TrivialEnough = false;
561 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
562 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
563 if (Record->hasTrivialCopyConstructor() &&
564 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000565 Record->hasTrivialDestructor()) {
566 DiagRuntimeBehavior(E->getLocStart(), 0,
567 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
568 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000569 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000570 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000571 }
572 }
John McCall31168b02011-06-15 23:02:42 +0000573
574 if (!TrivialEnough &&
575 getLangOptions().ObjCAutoRefCount &&
576 E->getType()->isObjCLifetimeType())
577 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000578
579 if (TrivialEnough) {
580 // Nothing to diagnose. This is okay.
581 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000582 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000583 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000584 << CT)) {
585 // Turn this into a trap.
586 CXXScopeSpec SS;
587 UnqualifiedId Name;
588 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
589 E->getLocStart());
590 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
591 if (TrapFn.isInvalid())
592 return ExprError();
593
594 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
595 MultiExprArg(), E->getLocEnd());
596 if (Call.isInvalid())
597 return ExprError();
598
599 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
600 Call.get(), E);
601 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000602 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000603 E = Comma.get();
604 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000605 }
606
John Wiegley01296292011-04-08 18:41:53 +0000607 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000608}
609
Richard Trieu7aa58f12011-09-02 20:58:51 +0000610/// \brief Converts an integer to complex float type. Helper function of
611/// UsualArithmeticConversions()
612///
613/// \return false if the integer expression is an integer type and is
614/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000615static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
616 ExprResult &ComplexExpr,
617 QualType IntTy,
618 QualType ComplexTy,
619 bool SkipCast) {
620 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
621 if (SkipCast) return false;
622 if (IntTy->isIntegerType()) {
623 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
624 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
625 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000626 CK_FloatingRealToComplex);
627 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000628 assert(IntTy->isComplexIntegerType());
629 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000630 CK_IntegralComplexToFloatingComplex);
631 }
632 return false;
633}
634
635/// \brief Takes two complex float types and converts them to the same type.
636/// Helper function of UsualArithmeticConversions()
637static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000638handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
639 ExprResult &RHS, QualType LHSType,
640 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000641 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000642 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643
644 if (order < 0) {
645 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000646 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000647 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
648 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000649 }
650 if (order > 0)
651 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000652 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
653 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000654}
655
656/// \brief Converts otherExpr to complex float and promotes complexExpr if
657/// necessary. Helper function of UsualArithmeticConversions()
658static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000659 ExprResult &ComplexExpr,
660 ExprResult &OtherExpr,
661 QualType ComplexTy,
662 QualType OtherTy,
663 bool ConvertComplexExpr,
664 bool ConvertOtherExpr) {
665 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000666
667 // If just the complexExpr is complex, the otherExpr needs to be converted,
668 // and the complexExpr might need to be promoted.
669 if (order > 0) { // complexExpr is wider
670 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000671 if (ConvertOtherExpr) {
672 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
673 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
674 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675 CK_FloatingRealToComplex);
676 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000677 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000678 }
679
680 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000681 QualType result = (order == 0 ? ComplexTy :
682 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000683
684 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000685 if (ConvertOtherExpr)
686 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000687 CK_FloatingRealToComplex);
688
689 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000690 if (ConvertComplexExpr && order < 0)
691 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692 CK_FloatingComplexCast);
693
694 return result;
695}
696
697/// \brief Handle arithmetic conversion with complex types. Helper function of
698/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000699static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
700 ExprResult &RHS, QualType LHSType,
701 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000702 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000703 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000704 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000705 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000706 return LHSType;
707 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000708 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000709 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000710
711 // This handles complex/complex, complex/float, or float/complex.
712 // When both operands are complex, the shorter operand is converted to the
713 // type of the longer, and that is the type of the result. This corresponds
714 // to what is done when combining two real floating-point operands.
715 // The fun begins when size promotion occur across type domains.
716 // From H&S 6.3.4: When one operand is complex and the other is a real
717 // floating-point type, the less precise type is converted, within it's
718 // real or complex domain, to the precision of the other type. For example,
719 // when combining a "long double" with a "double _Complex", the
720 // "double _Complex" is promoted to "long double _Complex".
721
Richard Trieu5065cdd2011-09-06 18:25:09 +0000722 bool LHSComplexFloat = LHSType->isComplexType();
723 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000724
725 // If both are complex, just cast to the more precise type.
726 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000727 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
728 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000729 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000730
731 // If only one operand is complex, promote it if necessary and convert the
732 // other operand to complex.
733 if (LHSComplexFloat)
734 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000735 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000736 /*convertOtherExpr*/ true);
737
738 assert(RHSComplexFloat);
739 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000740 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000741 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000742}
743
744/// \brief Hande arithmetic conversion from integer to float. Helper function
745/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000746static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
747 ExprResult &IntExpr,
748 QualType FloatTy, QualType IntTy,
749 bool ConvertFloat, bool ConvertInt) {
750 if (IntTy->isIntegerType()) {
751 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000752 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000753 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000755 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000756 }
757
758 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000759 assert(IntTy->isComplexIntegerType());
760 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000761
762 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000763 if (ConvertInt)
764 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000765 CK_IntegralComplexToFloatingComplex);
766
767 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000768 if (ConvertFloat)
769 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000770 CK_FloatingRealToComplex);
771
772 return result;
773}
774
775/// \brief Handle arithmethic conversion with floating point types. Helper
776/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000777static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
778 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000779 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000780 bool LHSFloat = LHSType->isRealFloatingType();
781 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782
783 // If we have two real floating types, convert the smaller operand
784 // to the bigger result.
785 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000786 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000787 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000788 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
789 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000790 }
791
792 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000793 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000794 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
795 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000796 }
797
798 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000799 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000800 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000801 /*convertInt=*/ true);
802 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000803 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000805 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000806}
807
808/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000809/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000810// FIXME: if the operands are (int, _Complex long), we currently
811// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000812static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
813 ExprResult &RHS, QualType LHSType,
814 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000815 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000816 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
817 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000818
Richard Trieucfe3f212011-09-06 18:38:41 +0000819 if (LHSComplexInt && RHSComplexInt) {
820 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
821 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000822 assert(order && "inequal types with equal element ordering");
823 if (order > 0) {
824 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000825 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
826 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000827 }
828
Richard Trieuba63ce62011-09-09 01:45:06 +0000829 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000830 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
831 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000832 }
833
Richard Trieucfe3f212011-09-06 18:38:41 +0000834 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000835 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000836 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
837 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000838 }
839
Richard Trieucfe3f212011-09-06 18:38:41 +0000840 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000841 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000842 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000843 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
844 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000845}
846
847/// \brief Handle integer arithmetic conversions. Helper function of
848/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000849static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
850 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000851 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000852 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000853 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
854 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
855 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
856 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000857 // Same signedness; use the higher-ranked type
858 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000859 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
860 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000861 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000862 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
863 return RHSType;
864 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000865 // The unsigned type has greater than or equal rank to the
866 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 if (RHSSigned) {
868 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
869 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000871 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
872 return RHSType;
873 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000874 // The two types are different widths; if we are here, that
875 // means the signed type is larger than the unsigned type, so
876 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 if (LHSSigned) {
878 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
879 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000880 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000881 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
882 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 } else {
884 // The signed type is higher-ranked than the unsigned type,
885 // but isn't actually any bigger (like unsigned int and long
886 // on most 32-bit systems). Use the unsigned type corresponding
887 // to the signed type.
888 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000889 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
890 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000891 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000892 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000893 return result;
894 }
895}
896
Chris Lattner513165e2008-07-25 21:10:04 +0000897/// UsualArithmeticConversions - Performs various conversions that are common to
898/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000899/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000900/// responsible for emitting appropriate error diagnostics.
901/// FIXME: verify the conversion rules for "complex int" are consistent with
902/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000903QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000904 bool IsCompAssign) {
905 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000906 LHS = UsualUnaryConversions(LHS.take());
907 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000908 return QualType();
909 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000910
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000911 RHS = UsualUnaryConversions(RHS.take());
912 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000913 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000914
Mike Stump11289f42009-09-09 15:08:12 +0000915 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000916 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000917 QualType LHSType =
918 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
919 QualType RHSType =
920 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000921
922 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000923 if (LHSType == RHSType)
924 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000925
926 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
927 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000928 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
929 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000930
John McCalld005ac92010-11-13 08:17:45 +0000931 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000932 QualType LHSUnpromotedType = LHSType;
933 if (LHSType->isPromotableIntegerType())
934 LHSType = Context.getPromotedIntegerType(LHSType);
935 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000936 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000937 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000938 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000939 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000940
John McCalld005ac92010-11-13 08:17:45 +0000941 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000942 if (LHSType == RHSType)
943 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000944
945 // At this point, we have two different arithmetic types.
946
947 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000948 if (LHSType->isComplexType() || RHSType->isComplexType())
949 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000950 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000951
952 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000953 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
954 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000955 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000956
957 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000958 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000959 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000960 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000961
962 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000963 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000964 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000965}
966
Chris Lattner513165e2008-07-25 21:10:04 +0000967//===----------------------------------------------------------------------===//
968// Semantic Analysis for various Expression Types
969//===----------------------------------------------------------------------===//
970
971
Peter Collingbourne91147592011-04-15 00:35:48 +0000972ExprResult
973Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
974 SourceLocation DefaultLoc,
975 SourceLocation RParenLoc,
976 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000977 MultiTypeArg ArgTypes,
978 MultiExprArg ArgExprs) {
979 unsigned NumAssocs = ArgTypes.size();
980 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000981
Richard Trieuba63ce62011-09-09 01:45:06 +0000982 ParsedType *ParsedTypes = ArgTypes.release();
983 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000984
985 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
986 for (unsigned i = 0; i < NumAssocs; ++i) {
987 if (ParsedTypes[i])
988 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
989 else
990 Types[i] = 0;
991 }
992
993 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
994 ControllingExpr, Types, Exprs,
995 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000996 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000997 return ER;
998}
999
1000ExprResult
1001Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1002 SourceLocation DefaultLoc,
1003 SourceLocation RParenLoc,
1004 Expr *ControllingExpr,
1005 TypeSourceInfo **Types,
1006 Expr **Exprs,
1007 unsigned NumAssocs) {
1008 bool TypeErrorFound = false,
1009 IsResultDependent = ControllingExpr->isTypeDependent(),
1010 ContainsUnexpandedParameterPack
1011 = ControllingExpr->containsUnexpandedParameterPack();
1012
1013 for (unsigned i = 0; i < NumAssocs; ++i) {
1014 if (Exprs[i]->containsUnexpandedParameterPack())
1015 ContainsUnexpandedParameterPack = true;
1016
1017 if (Types[i]) {
1018 if (Types[i]->getType()->containsUnexpandedParameterPack())
1019 ContainsUnexpandedParameterPack = true;
1020
1021 if (Types[i]->getType()->isDependentType()) {
1022 IsResultDependent = true;
1023 } else {
1024 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1025 // complete object type other than a variably modified type."
1026 unsigned D = 0;
1027 if (Types[i]->getType()->isIncompleteType())
1028 D = diag::err_assoc_type_incomplete;
1029 else if (!Types[i]->getType()->isObjectType())
1030 D = diag::err_assoc_type_nonobject;
1031 else if (Types[i]->getType()->isVariablyModifiedType())
1032 D = diag::err_assoc_type_variably_modified;
1033
1034 if (D != 0) {
1035 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1036 << Types[i]->getTypeLoc().getSourceRange()
1037 << Types[i]->getType();
1038 TypeErrorFound = true;
1039 }
1040
1041 // C1X 6.5.1.1p2 "No two generic associations in the same generic
1042 // selection shall specify compatible types."
1043 for (unsigned j = i+1; j < NumAssocs; ++j)
1044 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1045 Context.typesAreCompatible(Types[i]->getType(),
1046 Types[j]->getType())) {
1047 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1048 diag::err_assoc_compatible_types)
1049 << Types[j]->getTypeLoc().getSourceRange()
1050 << Types[j]->getType()
1051 << Types[i]->getType();
1052 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1053 diag::note_compat_assoc)
1054 << Types[i]->getTypeLoc().getSourceRange()
1055 << Types[i]->getType();
1056 TypeErrorFound = true;
1057 }
1058 }
1059 }
1060 }
1061 if (TypeErrorFound)
1062 return ExprError();
1063
1064 // If we determined that the generic selection is result-dependent, don't
1065 // try to compute the result expression.
1066 if (IsResultDependent)
1067 return Owned(new (Context) GenericSelectionExpr(
1068 Context, KeyLoc, ControllingExpr,
1069 Types, Exprs, NumAssocs, DefaultLoc,
1070 RParenLoc, ContainsUnexpandedParameterPack));
1071
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001073 unsigned DefaultIndex = -1U;
1074 for (unsigned i = 0; i < NumAssocs; ++i) {
1075 if (!Types[i])
1076 DefaultIndex = i;
1077 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1078 Types[i]->getType()))
1079 CompatIndices.push_back(i);
1080 }
1081
1082 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1083 // type compatible with at most one of the types named in its generic
1084 // association list."
1085 if (CompatIndices.size() > 1) {
1086 // We strip parens here because the controlling expression is typically
1087 // parenthesized in macro definitions.
1088 ControllingExpr = ControllingExpr->IgnoreParens();
1089 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1090 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1091 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001092 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001093 E = CompatIndices.end(); I != E; ++I) {
1094 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1095 diag::note_compat_assoc)
1096 << Types[*I]->getTypeLoc().getSourceRange()
1097 << Types[*I]->getType();
1098 }
1099 return ExprError();
1100 }
1101
1102 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1103 // its controlling expression shall have type compatible with exactly one of
1104 // the types named in its generic association list."
1105 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1106 // We strip parens here because the controlling expression is typically
1107 // parenthesized in macro definitions.
1108 ControllingExpr = ControllingExpr->IgnoreParens();
1109 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1110 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1111 return ExprError();
1112 }
1113
1114 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1115 // type name that is compatible with the type of the controlling expression,
1116 // then the result expression of the generic selection is the expression
1117 // in that generic association. Otherwise, the result expression of the
1118 // generic selection is the expression in the default generic association."
1119 unsigned ResultIndex =
1120 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1121
1122 return Owned(new (Context) GenericSelectionExpr(
1123 Context, KeyLoc, ControllingExpr,
1124 Types, Exprs, NumAssocs, DefaultLoc,
1125 RParenLoc, ContainsUnexpandedParameterPack,
1126 ResultIndex));
1127}
1128
Steve Naroff83895f72007-09-16 03:34:24 +00001129/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001130/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1131/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1132/// multiple tokens. However, the common case is that StringToks points to one
1133/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001134///
John McCalldadc5752010-08-24 06:29:42 +00001135ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001136Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001137 assert(NumStringToks && "Must have at least one string!");
1138
Chris Lattner8a24e582009-01-16 18:51:42 +00001139 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001140 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001141 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001142
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001143 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001144 for (unsigned i = 0; i != NumStringToks; ++i)
1145 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001146
Chris Lattner36fc8792008-02-11 00:02:17 +00001147 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001148 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001149 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001150 else if (Literal.isUTF16())
1151 StrTy = Context.Char16Ty;
1152 else if (Literal.isUTF32())
1153 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001154 else if (Literal.Pascal)
1155 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001156
Douglas Gregorfb65e592011-07-27 05:40:30 +00001157 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1158 if (Literal.isWide())
1159 Kind = StringLiteral::Wide;
1160 else if (Literal.isUTF8())
1161 Kind = StringLiteral::UTF8;
1162 else if (Literal.isUTF16())
1163 Kind = StringLiteral::UTF16;
1164 else if (Literal.isUTF32())
1165 Kind = StringLiteral::UTF32;
1166
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001167 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001168 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001169 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001170
Chris Lattner36fc8792008-02-11 00:02:17 +00001171 // Get an array type for the string, according to C99 6.4.5. This includes
1172 // the nul terminator character as well as the string length for pascal
1173 // strings.
1174 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001175 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001176 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Chris Lattner5b183d82006-11-10 05:03:26 +00001178 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001179 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001180 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001181 &StringTokLocs[0],
1182 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001183}
1184
John McCallc63de662011-02-02 13:00:07 +00001185enum CaptureResult {
1186 /// No capture is required.
1187 CR_NoCapture,
1188
1189 /// A capture is required.
1190 CR_Capture,
1191
John McCall351762c2011-02-07 10:33:21 +00001192 /// A by-ref capture is required.
1193 CR_CaptureByRef,
1194
John McCallc63de662011-02-02 13:00:07 +00001195 /// An error occurred when trying to capture the given variable.
1196 CR_Error
1197};
1198
1199/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001200///
John McCallc63de662011-02-02 13:00:07 +00001201/// \param var - the variable referenced
1202/// \param DC - the context which we couldn't capture through
1203static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001204diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001205 VarDecl *var, DeclContext *DC) {
1206 switch (S.ExprEvalContexts.back().Context) {
1207 case Sema::Unevaluated:
1208 // The argument will never be evaluated, so don't complain.
1209 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001210
John McCallc63de662011-02-02 13:00:07 +00001211 case Sema::PotentiallyEvaluated:
1212 case Sema::PotentiallyEvaluatedIfUsed:
1213 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001214
John McCallc63de662011-02-02 13:00:07 +00001215 case Sema::PotentiallyPotentiallyEvaluated:
1216 // FIXME: delay these!
1217 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219
John McCallc63de662011-02-02 13:00:07 +00001220 // Don't diagnose about capture if we're not actually in code right
1221 // now; in general, there are more appropriate places that will
1222 // diagnose this.
1223 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1224
John McCall92d627e2011-03-22 23:15:50 +00001225 // Certain madnesses can happen with parameter declarations, which
1226 // we want to ignore.
1227 if (isa<ParmVarDecl>(var)) {
1228 // - If the parameter still belongs to the translation unit, then
1229 // we're actually just using one parameter in the declaration of
1230 // the next. This is useful in e.g. VLAs.
1231 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1232 return CR_NoCapture;
1233
1234 // - This particular madness can happen in ill-formed default
1235 // arguments; claim it's okay and let downstream code handle it.
1236 if (S.CurContext == var->getDeclContext()->getParent())
1237 return CR_NoCapture;
1238 }
John McCallc63de662011-02-02 13:00:07 +00001239
1240 DeclarationName functionName;
1241 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1242 functionName = fn->getDeclName();
1243 // FIXME: variable from enclosing block that we couldn't capture from!
1244
1245 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1246 << var->getIdentifier() << functionName;
1247 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1248 << var->getIdentifier();
1249
1250 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001251}
1252
John McCall351762c2011-02-07 10:33:21 +00001253/// There is a well-formed capture at a particular scope level;
1254/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001255static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1256 const BlockDecl::Capture &Capture) {
1257 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001258
1259 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001260 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001261 i != e; ++i) {
1262 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1263 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001264 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1265 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001266 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1267 }
1268
Richard Trieuba63ce62011-09-09 01:45:06 +00001269 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001270}
1271
1272/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001273/// given value in the current context requires a variable capture.
1274///
1275/// This also keeps the captures set in the BlockScopeInfo records
1276/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001277static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001278 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001279 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001280 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001281 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001282
1283 // Fast path: variables from the current context never require capture.
1284 DeclContext *DC = S.CurContext;
1285 if (var->getDeclContext() == DC) return CR_NoCapture;
1286
1287 // Only variables with local storage require capture.
1288 // FIXME: What about 'const' variables in C++?
1289 if (!var->hasLocalStorage()) return CR_NoCapture;
1290
1291 // Otherwise, we need to capture.
1292
1293 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001294 do {
1295 // Only blocks (and eventually C++0x closures) can capture; other
1296 // scopes don't work.
1297 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001298 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001299
1300 BlockScopeInfo *blockScope =
1301 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1302 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1303
John McCall351762c2011-02-07 10:33:21 +00001304 // Check whether we've already captured it in this block. If so,
1305 // we're done.
1306 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1307 return propagateCapture(S, functionScopesIndex,
1308 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001309
1310 functionScopesIndex--;
1311 DC = cast<BlockDecl>(DC)->getDeclContext();
1312 } while (var->getDeclContext() != DC);
1313
John McCall351762c2011-02-07 10:33:21 +00001314 // Okay, we descended all the way to the block that defines the variable.
1315 // Actually try to capture it.
1316 QualType type = var->getType();
1317
1318 // Prohibit variably-modified types.
1319 if (type->isVariablyModifiedType()) {
1320 S.Diag(loc, diag::err_ref_vm_type);
1321 S.Diag(var->getLocation(), diag::note_declared_at);
1322 return CR_Error;
1323 }
1324
1325 // Prohibit arrays, even in __block variables, but not references to
1326 // them.
1327 if (type->isArrayType()) {
1328 S.Diag(loc, diag::err_ref_array_type);
1329 S.Diag(var->getLocation(), diag::note_declared_at);
1330 return CR_Error;
1331 }
1332
1333 S.MarkDeclarationReferenced(loc, var);
1334
1335 // The BlocksAttr indicates the variable is bound by-reference.
1336 bool byRef = var->hasAttr<BlocksAttr>();
1337
1338 // Build a copy expression.
1339 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001340 const RecordType *rtype;
1341 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1342 (rtype = type->getAs<RecordType>())) {
1343
1344 // The capture logic needs the destructor, so make sure we mark it.
1345 // Usually this is unnecessary because most local variables have
1346 // their destructors marked at declaration time, but parameters are
1347 // an exception because it's technically only the call site that
1348 // actually requires the destructor.
1349 if (isa<ParmVarDecl>(var))
1350 S.FinalizeVarWithDestructor(var, rtype);
1351
John McCall351762c2011-02-07 10:33:21 +00001352 // According to the blocks spec, the capture of a variable from
1353 // the stack requires a const copy constructor. This is not true
1354 // of the copy/move done to move a __block variable to the heap.
1355 type.addConst();
1356
1357 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1358 ExprResult result =
1359 S.PerformCopyInitialization(
1360 InitializedEntity::InitializeBlock(var->getLocation(),
1361 type, false),
1362 loc, S.Owned(declRef));
1363
1364 // Build a full-expression copy expression if initialization
1365 // succeeded and used a non-trivial constructor. Recover from
1366 // errors by pretending that the copy isn't necessary.
1367 if (!result.isInvalid() &&
1368 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1369 result = S.MaybeCreateExprWithCleanups(result);
1370 copyExpr = result.take();
1371 }
1372 }
1373
1374 // We're currently at the declarer; go back to the closure.
1375 functionScopesIndex++;
1376 BlockScopeInfo *blockScope =
1377 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1378
1379 // Build a valid capture in this scope.
1380 blockScope->Captures.push_back(
1381 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1382 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1383
1384 // Propagate that to inner captures if necessary.
1385 return propagateCapture(S, functionScopesIndex,
1386 blockScope->Captures.back());
1387}
1388
Richard Trieuba63ce62011-09-09 01:45:06 +00001389static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001390 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001391 bool ByRef) {
1392 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001393
Richard Trieuba63ce62011-09-09 01:45:06 +00001394 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001395 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001396 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001397
1398 QualType exprType = var->getType().getNonReferenceType();
1399
1400 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001401 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001402 // The variable will be bound by copy; make it const within the
1403 // closure, but record that this was done in the expression.
1404 bool constAdded = !exprType.isConstQualified();
1405 exprType.addConst();
1406
1407 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1408 NameInfo.getLoc(), false,
1409 constAdded);
1410 } else {
1411 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1412 NameInfo.getLoc(), true);
1413 }
1414
1415 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001416}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001417
John McCalldadc5752010-08-24 06:29:42 +00001418ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001419Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001420 SourceLocation Loc,
1421 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001422 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001423 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001424}
1425
John McCallf4cd4f92011-02-09 01:13:10 +00001426/// BuildDeclRefExpr - Build an expression that references a
1427/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001428ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001429Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001430 const DeclarationNameInfo &NameInfo,
1431 const CXXScopeSpec *SS) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001432 if (getLangOptions().CUDA)
1433 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1434 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1435 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1436 CalleeTarget = IdentifyCUDATarget(Callee);
1437 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1438 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1439 << CalleeTarget << D->getIdentifier() << CallerTarget;
1440 Diag(D->getLocation(), diag::note_previous_decl)
1441 << D->getIdentifier();
1442 return ExprError();
1443 }
1444 }
1445
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001446 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001447
John McCall086a4642010-11-24 05:12:34 +00001448 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001449 SS? SS->getWithLocInContext(Context)
1450 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001451 D, NameInfo, Ty, VK);
1452
1453 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001454 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1455 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001456 E->setObjectKind(OK_BitField);
1457
1458 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001459}
1460
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001461/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001462/// possibly a list of template arguments.
1463///
1464/// If this produces template arguments, it is permitted to call
1465/// DecomposeTemplateName.
1466///
1467/// This actually loses a lot of source location information for
1468/// non-standard name kinds; we should consider preserving that in
1469/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001470void
1471Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1472 TemplateArgumentListInfo &Buffer,
1473 DeclarationNameInfo &NameInfo,
1474 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001475 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1476 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1477 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1478
Douglas Gregor5476205b2011-06-23 00:49:38 +00001479 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001480 Id.TemplateId->getTemplateArgs(),
1481 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001482 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001483 TemplateArgsPtr.release();
1484
John McCall3e56fd42010-08-23 07:28:44 +00001485 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001486 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001487 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001488 TemplateArgs = &Buffer;
1489 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001490 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001491 TemplateArgs = 0;
1492 }
1493}
1494
John McCalld681c392009-12-16 08:11:27 +00001495/// Diagnose an empty lookup.
1496///
1497/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001498bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001499 CorrectTypoContext CTC,
1500 TemplateArgumentListInfo *ExplicitTemplateArgs,
1501 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001502 DeclarationName Name = R.getLookupName();
1503
John McCalld681c392009-12-16 08:11:27 +00001504 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001505 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001506 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1507 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001508 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001509 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001510 diagnostic_suggest = diag::err_undeclared_use_suggest;
1511 }
John McCalld681c392009-12-16 08:11:27 +00001512
Douglas Gregor598b08f2009-12-31 05:20:13 +00001513 // If the original lookup was an unqualified lookup, fake an
1514 // unqualified lookup. This is useful when (for example) the
1515 // original lookup would not have found something because it was a
1516 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001517 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001518 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001519 if (isa<CXXRecordDecl>(DC)) {
1520 LookupQualifiedName(R, DC);
1521
1522 if (!R.empty()) {
1523 // Don't give errors about ambiguities in this lookup.
1524 R.suppressDiagnostics();
1525
1526 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1527 bool isInstance = CurMethod &&
1528 CurMethod->isInstance() &&
1529 DC == CurMethod->getParent();
1530
1531 // Give a code modification hint to insert 'this->'.
1532 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1533 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001534 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001535 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1536 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001537 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001538 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001539 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001540 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001541 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001542 Diag(R.getNameLoc(), diagnostic) << Name
1543 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1544 QualType DepThisType = DepMethod->getThisType(Context);
1545 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546 R.getNameLoc(), DepThisType, false);
1547 TemplateArgumentListInfo TList;
1548 if (ULE->hasExplicitTemplateArgs())
1549 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001550
Douglas Gregore16af532011-02-28 18:50:33 +00001551 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001552 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001553 CXXDependentScopeMemberExpr *DepExpr =
1554 CXXDependentScopeMemberExpr::Create(
1555 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001556 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001557 R.getLookupNameInfo(),
1558 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001559 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001560 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001561 // FIXME: we should be able to handle this case too. It is correct
1562 // to add this-> here. This is a workaround for PR7947.
1563 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001564 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001565 } else {
John McCalld681c392009-12-16 08:11:27 +00001566 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001567 }
John McCalld681c392009-12-16 08:11:27 +00001568
1569 // Do we really want to note all of these?
1570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1572
1573 // Tell the callee to try to recover.
1574 return false;
1575 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001576
1577 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001578 }
1579 }
1580
Douglas Gregor598b08f2009-12-31 05:20:13 +00001581 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001582 TypoCorrection Corrected;
1583 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1584 S, &SS, NULL, false, CTC))) {
1585 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1586 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1587 R.setLookupName(Corrected.getCorrection());
1588
Hans Wennborg38198de2011-07-12 08:45:31 +00001589 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001590 if (Corrected.isOverloaded()) {
1591 OverloadCandidateSet OCS(R.getNameLoc());
1592 OverloadCandidateSet::iterator Best;
1593 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1594 CDEnd = Corrected.end();
1595 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001596 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001597 dyn_cast<FunctionTemplateDecl>(*CD))
1598 AddTemplateOverloadCandidate(
1599 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1600 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001601 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1602 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1603 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1604 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001605 }
1606 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1607 case OR_Success:
1608 ND = Best->Function;
1609 break;
1610 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001611 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001612 }
1613 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001614 R.addDecl(ND);
1615 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001616 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001617 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1618 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001619 else
1620 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001621 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001622 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001623 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1624 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001625 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001626 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001627
1628 // Tell the callee to try to recover.
1629 return false;
1630 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001631
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001632 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001633 // FIXME: If we ended up with a typo for a type name or
1634 // Objective-C class name, we're in trouble because the parser
1635 // is in the wrong place to recover. Suggest the typo
1636 // correction, but don't make it a fix-it since we're not going
1637 // to recover well anyway.
1638 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001639 Diag(R.getNameLoc(), diagnostic_suggest)
1640 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001641 else
1642 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001643 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001644 << SS.getRange();
1645
1646 // Don't try to recover; it won't work.
1647 return true;
1648 }
1649 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001650 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001651 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001652 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001653 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001654 else
Douglas Gregor25363982010-01-01 00:15:04 +00001655 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001656 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001657 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001658 return true;
1659 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001660 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001661 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001662
1663 // Emit a special diagnostic for failed member lookups.
1664 // FIXME: computing the declaration context might fail here (?)
1665 if (!SS.isEmpty()) {
1666 Diag(R.getNameLoc(), diag::err_no_member)
1667 << Name << computeDeclContext(SS, false)
1668 << SS.getRange();
1669 return true;
1670 }
1671
John McCalld681c392009-12-16 08:11:27 +00001672 // Give up, we can't recover.
1673 Diag(R.getNameLoc(), diagnostic) << Name;
1674 return true;
1675}
1676
John McCalldadc5752010-08-24 06:29:42 +00001677ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001678 CXXScopeSpec &SS,
1679 UnqualifiedId &Id,
1680 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001681 bool IsAddressOfOperand) {
1682 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001683 "cannot be direct & operand and have a trailing lparen");
1684
1685 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001686 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001687
John McCall10eae182009-11-30 22:42:35 +00001688 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001689
1690 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001691 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001692 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001693 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001694
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001695 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001696 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001697 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001698
John McCalle66edc12009-11-24 19:00:30 +00001699 // C++ [temp.dep.expr]p3:
1700 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001701 // -- an identifier that was declared with a dependent type,
1702 // (note: handled after lookup)
1703 // -- a template-id that is dependent,
1704 // (note: handled in BuildTemplateIdExpr)
1705 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001706 // -- a nested-name-specifier that contains a class-name that
1707 // names a dependent type.
1708 // Determine whether this is a member of an unknown specialization;
1709 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001710 bool DependentID = false;
1711 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1712 Name.getCXXNameType()->isDependentType()) {
1713 DependentID = true;
1714 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001715 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001716 if (RequireCompleteDeclContext(SS, DC))
1717 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001718 } else {
1719 DependentID = true;
1720 }
1721 }
1722
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001723 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001724 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001725 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001726
Fariborz Jahanian86151342010-07-22 23:33:21 +00001727 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001728 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001729 LookupResult R(*this, NameInfo,
1730 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1731 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001732 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001733 // Lookup the template name again to correctly establish the context in
1734 // which it was found. This is really unfortunate as we already did the
1735 // lookup to determine that it was a template name in the first place. If
1736 // this becomes a performance hit, we can work harder to preserve those
1737 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001738 bool MemberOfUnknownSpecialization;
1739 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1740 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001741
1742 if (MemberOfUnknownSpecialization ||
1743 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001744 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001745 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001746 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001747 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001748 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregora5226932011-02-04 13:35:07 +00001750 // If the result might be in a dependent base class, this is a dependent
1751 // id-expression.
1752 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001753 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001754 TemplateArgs);
1755
John McCalle66edc12009-11-24 19:00:30 +00001756 // If this reference is in an Objective-C method, then we need to do
1757 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001758 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001759 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001760 if (E.isInvalid())
1761 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001762
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001763 if (Expr *Ex = E.takeAs<Expr>())
1764 return Owned(Ex);
1765
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001766 // for further use, this must be set to false if in class method.
1767 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001768 }
Chris Lattner59a25942008-03-31 00:36:02 +00001769 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001770
John McCalle66edc12009-11-24 19:00:30 +00001771 if (R.isAmbiguous())
1772 return ExprError();
1773
Douglas Gregor171c45a2009-02-18 21:56:37 +00001774 // Determine whether this name might be a candidate for
1775 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001776 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001777
John McCalle66edc12009-11-24 19:00:30 +00001778 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001779 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001780 // in C90, extension in C99, forbidden in C++).
1781 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1782 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1783 if (D) R.addDecl(D);
1784 }
1785
1786 // If this name wasn't predeclared and if this is not a function
1787 // call, diagnose the problem.
1788 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001789
1790 // In Microsoft mode, if we are inside a template class member function
1791 // and we can't resolve an identifier then assume the identifier is type
1792 // dependent. The goal is to postpone name lookup to instantiation time
1793 // to be able to search into type dependent base classes.
1794 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1795 isa<CXXMethodDecl>(CurContext))
1796 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1797 TemplateArgs);
1798
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001799 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001800 return ExprError();
1801
1802 assert(!R.empty() &&
1803 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001804
1805 // If we found an Objective-C instance variable, let
1806 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001807 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001808 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1809 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001810 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001811 // In a hopelessly buggy code, Objective-C instance variable
1812 // lookup fails and no expression will be built to reference it.
1813 if (!E.isInvalid() && !E.get())
1814 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001815 return move(E);
1816 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001817 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
John McCalle66edc12009-11-24 19:00:30 +00001820 // This is guaranteed from this point on.
1821 assert(!R.empty() || ADL);
1822
John McCall2d74de92009-12-01 22:10:20 +00001823 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001824 // C++ [class.mfct.non-static]p3:
1825 // When an id-expression that is not part of a class member access
1826 // syntax and not used to form a pointer to member is used in the
1827 // body of a non-static member function of class X, if name lookup
1828 // resolves the name in the id-expression to a non-static non-type
1829 // member of some class C, the id-expression is transformed into a
1830 // class member access expression using (*this) as the
1831 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001832 //
1833 // But we don't actually need to do this for '&' operands if R
1834 // resolved to a function or overloaded function set, because the
1835 // expression is ill-formed if it actually works out to be a
1836 // non-static member function:
1837 //
1838 // C++ [expr.ref]p4:
1839 // Otherwise, if E1.E2 refers to a non-static member function. . .
1840 // [t]he expression can be used only as the left-hand operand of a
1841 // member function call.
1842 //
1843 // There are other safeguards against such uses, but it's important
1844 // to get this right here so that we don't end up making a
1845 // spuriously dependent expression if we're inside a dependent
1846 // instance method.
John McCall57500772009-12-16 12:17:52 +00001847 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001848 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001849 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001850 MightBeImplicitMember = true;
1851 else if (!SS.isEmpty())
1852 MightBeImplicitMember = false;
1853 else if (R.isOverloadedResult())
1854 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001855 else if (R.isUnresolvableResult())
1856 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001857 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001858 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1859 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001860
1861 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001862 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001863 }
1864
John McCalle66edc12009-11-24 19:00:30 +00001865 if (TemplateArgs)
1866 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001867
John McCalle66edc12009-11-24 19:00:30 +00001868 return BuildDeclarationNameExpr(SS, R, ADL);
1869}
1870
John McCall10eae182009-11-30 22:42:35 +00001871/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1872/// declaration name, generally during template instantiation.
1873/// There's a large number of things which don't need to be done along
1874/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001875ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001876Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001877 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001878 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001879 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001880 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001881
John McCall0b66eb32010-05-01 00:40:08 +00001882 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001883 return ExprError();
1884
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001885 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001886 LookupQualifiedName(R, DC);
1887
1888 if (R.isAmbiguous())
1889 return ExprError();
1890
1891 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001892 Diag(NameInfo.getLoc(), diag::err_no_member)
1893 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001894 return ExprError();
1895 }
1896
1897 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1898}
1899
1900/// LookupInObjCMethod - The parser has read a name in, and Sema has
1901/// detected that we're currently inside an ObjC method. Perform some
1902/// additional lookup.
1903///
1904/// Ideally, most of this would be done by lookup, but there's
1905/// actually quite a lot of extra work involved.
1906///
1907/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001908ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001909Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001910 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001911 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001912 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001913
John McCalle66edc12009-11-24 19:00:30 +00001914 // There are two cases to handle here. 1) scoped lookup could have failed,
1915 // in which case we should look for an ivar. 2) scoped lookup could have
1916 // found a decl, but that decl is outside the current instance method (i.e.
1917 // a global variable). In these two cases, we do a lookup for an ivar with
1918 // this name, if the lookup sucedes, we replace it our current decl.
1919
1920 // If we're in a class method, we don't normally want to look for
1921 // ivars. But if we don't find anything else, and there's an
1922 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001923 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001924
1925 bool LookForIvars;
1926 if (Lookup.empty())
1927 LookForIvars = true;
1928 else if (IsClassMethod)
1929 LookForIvars = false;
1930 else
1931 LookForIvars = (Lookup.isSingleResult() &&
1932 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001933 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001934 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001935 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001936 ObjCInterfaceDecl *ClassDeclared;
1937 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1938 // Diagnose using an ivar in a class method.
1939 if (IsClassMethod)
1940 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1941 << IV->getDeclName());
1942
1943 // If we're referencing an invalid decl, just return this as a silent
1944 // error node. The error diagnostic was already emitted on the decl.
1945 if (IV->isInvalidDecl())
1946 return ExprError();
1947
1948 // Check if referencing a field with __attribute__((deprecated)).
1949 if (DiagnoseUseOfDecl(IV, Loc))
1950 return ExprError();
1951
1952 // Diagnose the use of an ivar outside of the declaring class.
1953 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1954 ClassDeclared != IFace)
1955 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1956
1957 // FIXME: This should use a new expr for a direct reference, don't
1958 // turn this into Self->ivar, just return a BareIVarExpr or something.
1959 IdentifierInfo &II = Context.Idents.get("self");
1960 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001961 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001962 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001963 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001964 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001965 SelfName, false, false);
1966 if (SelfExpr.isInvalid())
1967 return ExprError();
1968
John Wiegley01296292011-04-08 18:41:53 +00001969 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1970 if (SelfExpr.isInvalid())
1971 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001972
John McCalle66edc12009-11-24 19:00:30 +00001973 MarkDeclarationReferenced(Loc, IV);
1974 return Owned(new (Context)
1975 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001976 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001977 }
Chris Lattner87313662010-04-12 05:10:17 +00001978 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001979 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001980 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001981 ObjCInterfaceDecl *ClassDeclared;
1982 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1983 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1984 IFace == ClassDeclared)
1985 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1986 }
1987 }
1988
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001989 if (Lookup.empty() && II && AllowBuiltinCreation) {
1990 // FIXME. Consolidate this with similar code in LookupName.
1991 if (unsigned BuiltinID = II->getBuiltinID()) {
1992 if (!(getLangOptions().CPlusPlus &&
1993 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1994 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1995 S, Lookup.isForRedeclaration(),
1996 Lookup.getNameLoc());
1997 if (D) Lookup.addDecl(D);
1998 }
1999 }
2000 }
John McCalle66edc12009-11-24 19:00:30 +00002001 // Sentinel value saying that we didn't do anything special.
2002 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002003}
John McCalld14a8642009-11-21 08:51:07 +00002004
John McCall16df1e52010-03-30 21:47:33 +00002005/// \brief Cast a base object to a member's actual type.
2006///
2007/// Logically this happens in three phases:
2008///
2009/// * First we cast from the base type to the naming class.
2010/// The naming class is the class into which we were looking
2011/// when we found the member; it's the qualifier type if a
2012/// qualifier was provided, and otherwise it's the base type.
2013///
2014/// * Next we cast from the naming class to the declaring class.
2015/// If the member we found was brought into a class's scope by
2016/// a using declaration, this is that class; otherwise it's
2017/// the class declaring the member.
2018///
2019/// * Finally we cast from the declaring class to the "true"
2020/// declaring class of the member. This conversion does not
2021/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002022ExprResult
2023Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002024 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002025 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002026 NamedDecl *Member) {
2027 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2028 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002029 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002030
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002031 QualType DestRecordType;
2032 QualType DestType;
2033 QualType FromRecordType;
2034 QualType FromType = From->getType();
2035 bool PointerConversions = false;
2036 if (isa<FieldDecl>(Member)) {
2037 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002038
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002039 if (FromType->getAs<PointerType>()) {
2040 DestType = Context.getPointerType(DestRecordType);
2041 FromRecordType = FromType->getPointeeType();
2042 PointerConversions = true;
2043 } else {
2044 DestType = DestRecordType;
2045 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002046 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002047 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2048 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002049 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002050
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002051 DestType = Method->getThisType(Context);
2052 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002053
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002054 if (FromType->getAs<PointerType>()) {
2055 FromRecordType = FromType->getPointeeType();
2056 PointerConversions = true;
2057 } else {
2058 FromRecordType = FromType;
2059 DestType = DestRecordType;
2060 }
2061 } else {
2062 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002063 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002065
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002066 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002067 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002068
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002069 // If the unqualified types are the same, no conversion is necessary.
2070 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002071 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002072
John McCall16df1e52010-03-30 21:47:33 +00002073 SourceRange FromRange = From->getSourceRange();
2074 SourceLocation FromLoc = FromRange.getBegin();
2075
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002076 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002077
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002078 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002079 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002080 // class name.
2081 //
2082 // If the member was a qualified name and the qualified referred to a
2083 // specific base subobject type, we'll cast to that intermediate type
2084 // first and then to the object in which the member is declared. That allows
2085 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2086 //
2087 // class Base { public: int x; };
2088 // class Derived1 : public Base { };
2089 // class Derived2 : public Base { };
2090 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2091 //
2092 // void VeryDerived::f() {
2093 // x = 17; // error: ambiguous base subobjects
2094 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2095 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002096 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002097 QualType QType = QualType(Qualifier->getAsType(), 0);
2098 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2099 assert(QType->isRecordType() && "lookup done with non-record type");
2100
2101 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2102
2103 // In C++98, the qualifier type doesn't actually have to be a base
2104 // type of the object type, in which case we just ignore it.
2105 // Otherwise build the appropriate casts.
2106 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002107 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002108 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002109 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002110 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002111
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002112 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002113 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002114 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2115 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002116
2117 FromType = QType;
2118 FromRecordType = QRecordType;
2119
2120 // If the qualifier type was the same as the destination type,
2121 // we're done.
2122 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002123 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002124 }
2125 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002126
John McCall16df1e52010-03-30 21:47:33 +00002127 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002128
John McCall16df1e52010-03-30 21:47:33 +00002129 // If we actually found the member through a using declaration, cast
2130 // down to the using declaration's type.
2131 //
2132 // Pointer equality is fine here because only one declaration of a
2133 // class ever has member declarations.
2134 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2135 assert(isa<UsingShadowDecl>(FoundDecl));
2136 QualType URecordType = Context.getTypeDeclType(
2137 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2138
2139 // We only need to do this if the naming-class to declaring-class
2140 // conversion is non-trivial.
2141 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2142 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002143 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002144 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002145 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002146 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002147
John McCall16df1e52010-03-30 21:47:33 +00002148 QualType UType = URecordType;
2149 if (PointerConversions)
2150 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002151 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2152 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002153 FromType = UType;
2154 FromRecordType = URecordType;
2155 }
2156
2157 // We don't do access control for the conversion from the
2158 // declaring class to the true declaring class.
2159 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002160 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002161
John McCallcf142162010-08-07 06:22:56 +00002162 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002163 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2164 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002165 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002166 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002167
John Wiegley01296292011-04-08 18:41:53 +00002168 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2169 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002170}
Douglas Gregor3256d042009-06-30 15:47:41 +00002171
John McCalle66edc12009-11-24 19:00:30 +00002172bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002173 const LookupResult &R,
2174 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002175 // Only when used directly as the postfix-expression of a call.
2176 if (!HasTrailingLParen)
2177 return false;
2178
2179 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002180 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002181 return false;
2182
2183 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002184 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002185 return false;
2186
2187 // Turn off ADL when we find certain kinds of declarations during
2188 // normal lookup:
2189 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2190 NamedDecl *D = *I;
2191
2192 // C++0x [basic.lookup.argdep]p3:
2193 // -- a declaration of a class member
2194 // Since using decls preserve this property, we check this on the
2195 // original decl.
John McCall57500772009-12-16 12:17:52 +00002196 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002197 return false;
2198
2199 // C++0x [basic.lookup.argdep]p3:
2200 // -- a block-scope function declaration that is not a
2201 // using-declaration
2202 // NOTE: we also trigger this for function templates (in fact, we
2203 // don't check the decl type at all, since all other decl types
2204 // turn off ADL anyway).
2205 if (isa<UsingShadowDecl>(D))
2206 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2207 else if (D->getDeclContext()->isFunctionOrMethod())
2208 return false;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a declaration that is neither a function or a function
2212 // template
2213 // And also for builtin functions.
2214 if (isa<FunctionDecl>(D)) {
2215 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2216
2217 // But also builtin functions.
2218 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2219 return false;
2220 } else if (!isa<FunctionTemplateDecl>(D))
2221 return false;
2222 }
2223
2224 return true;
2225}
2226
2227
John McCalld14a8642009-11-21 08:51:07 +00002228/// Diagnoses obvious problems with the use of the given declaration
2229/// as an expression. This is only actually called for lookups that
2230/// were not overloaded, and it doesn't promise that the declaration
2231/// will in fact be used.
2232static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002233 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002234 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2235 return true;
2236 }
2237
2238 if (isa<ObjCInterfaceDecl>(D)) {
2239 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2240 return true;
2241 }
2242
2243 if (isa<NamespaceDecl>(D)) {
2244 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2245 return true;
2246 }
2247
2248 return false;
2249}
2250
John McCalldadc5752010-08-24 06:29:42 +00002251ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002252Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002253 LookupResult &R,
2254 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002255 // If this is a single, fully-resolved result and we don't need ADL,
2256 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002257 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002258 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2259 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002260
2261 // We only need to check the declaration if there's exactly one
2262 // result, because in the overloaded case the results can only be
2263 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002264 if (R.isSingleResult() &&
2265 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002266 return ExprError();
2267
John McCall58cc69d2010-01-27 01:50:18 +00002268 // Otherwise, just build an unresolved lookup expression. Suppress
2269 // any lookup-related diagnostics; we'll hash these out later, when
2270 // we've picked a target.
2271 R.suppressDiagnostics();
2272
John McCalld14a8642009-11-21 08:51:07 +00002273 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002274 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002275 SS.getWithLocInContext(Context),
2276 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002277 NeedsADL, R.isOverloadedResult(),
2278 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002279
2280 return Owned(ULE);
2281}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002282
John McCalld14a8642009-11-21 08:51:07 +00002283/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002284ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002285Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002286 const DeclarationNameInfo &NameInfo,
2287 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002288 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002289 assert(!isa<FunctionTemplateDecl>(D) &&
2290 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002291
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002292 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002293 if (CheckDeclInExpr(*this, Loc, D))
2294 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002295
Douglas Gregore7488b92009-12-01 16:58:18 +00002296 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2297 // Specifically diagnose references to class templates that are missing
2298 // a template argument list.
2299 Diag(Loc, diag::err_template_decl_ref)
2300 << Template << SS.getRange();
2301 Diag(Template->getLocation(), diag::note_template_decl_here);
2302 return ExprError();
2303 }
2304
2305 // Make sure that we're referring to a value.
2306 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2307 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002308 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002309 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002310 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002311 return ExprError();
2312 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002313
Douglas Gregor171c45a2009-02-18 21:56:37 +00002314 // Check whether this declaration can be used. Note that we suppress
2315 // this check when we're going to perform argument-dependent lookup
2316 // on this function name, because this might not be the function
2317 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002318 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002319 return ExprError();
2320
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002321 // Only create DeclRefExpr's for valid Decl's.
2322 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002323 return ExprError();
2324
John McCallf3a88602011-02-03 08:15:49 +00002325 // Handle members of anonymous structs and unions. If we got here,
2326 // and the reference is to a class member indirect field, then this
2327 // must be the subject of a pointer-to-member expression.
2328 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2329 if (!indirectField->isCXXClassMember())
2330 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2331 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002332
Chris Lattner2a9d9892008-10-20 05:16:36 +00002333 // If the identifier reference is inside a block, and it refers to a value
2334 // that is outside the block, create a BlockDeclRefExpr instead of a
2335 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2336 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002337 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002338 // We do not do this for things like enum constants, global variables, etc,
2339 // as they do not get snapshotted.
2340 //
John McCall351762c2011-02-07 10:33:21 +00002341 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002342 case CR_Error:
2343 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002344
John McCallc63de662011-02-02 13:00:07 +00002345 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002346 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2347 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2348
2349 case CR_CaptureByRef:
2350 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2351 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002352
2353 case CR_NoCapture: {
2354 // If this reference is not in a block or if the referenced
2355 // variable is within the block, create a normal DeclRefExpr.
2356
2357 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002358 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002359
2360 switch (D->getKind()) {
2361 // Ignore all the non-ValueDecl kinds.
2362#define ABSTRACT_DECL(kind)
2363#define VALUE(type, base)
2364#define DECL(type, base) \
2365 case Decl::type:
2366#include "clang/AST/DeclNodes.inc"
2367 llvm_unreachable("invalid value decl kind");
2368 return ExprError();
2369
2370 // These shouldn't make it here.
2371 case Decl::ObjCAtDefsField:
2372 case Decl::ObjCIvar:
2373 llvm_unreachable("forming non-member reference to ivar?");
2374 return ExprError();
2375
2376 // Enum constants are always r-values and never references.
2377 // Unresolved using declarations are dependent.
2378 case Decl::EnumConstant:
2379 case Decl::UnresolvedUsingValue:
2380 valueKind = VK_RValue;
2381 break;
2382
2383 // Fields and indirect fields that got here must be for
2384 // pointer-to-member expressions; we just call them l-values for
2385 // internal consistency, because this subexpression doesn't really
2386 // exist in the high-level semantics.
2387 case Decl::Field:
2388 case Decl::IndirectField:
2389 assert(getLangOptions().CPlusPlus &&
2390 "building reference to field in C?");
2391
2392 // These can't have reference type in well-formed programs, but
2393 // for internal consistency we do this anyway.
2394 type = type.getNonReferenceType();
2395 valueKind = VK_LValue;
2396 break;
2397
2398 // Non-type template parameters are either l-values or r-values
2399 // depending on the type.
2400 case Decl::NonTypeTemplateParm: {
2401 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2402 type = reftype->getPointeeType();
2403 valueKind = VK_LValue; // even if the parameter is an r-value reference
2404 break;
2405 }
2406
2407 // For non-references, we need to strip qualifiers just in case
2408 // the template parameter was declared as 'const int' or whatever.
2409 valueKind = VK_RValue;
2410 type = type.getUnqualifiedType();
2411 break;
2412 }
2413
2414 case Decl::Var:
2415 // In C, "extern void blah;" is valid and is an r-value.
2416 if (!getLangOptions().CPlusPlus &&
2417 !type.hasQualifiers() &&
2418 type->isVoidType()) {
2419 valueKind = VK_RValue;
2420 break;
2421 }
2422 // fallthrough
2423
2424 case Decl::ImplicitParam:
2425 case Decl::ParmVar:
2426 // These are always l-values.
2427 valueKind = VK_LValue;
2428 type = type.getNonReferenceType();
2429 break;
2430
2431 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002432 const FunctionType *fty = type->castAs<FunctionType>();
2433
2434 // If we're referring to a function with an __unknown_anytype
2435 // result type, make the entire expression __unknown_anytype.
2436 if (fty->getResultType() == Context.UnknownAnyTy) {
2437 type = Context.UnknownAnyTy;
2438 valueKind = VK_RValue;
2439 break;
2440 }
2441
John McCallf4cd4f92011-02-09 01:13:10 +00002442 // Functions are l-values in C++.
2443 if (getLangOptions().CPlusPlus) {
2444 valueKind = VK_LValue;
2445 break;
2446 }
2447
2448 // C99 DR 316 says that, if a function type comes from a
2449 // function definition (without a prototype), that type is only
2450 // used for checking compatibility. Therefore, when referencing
2451 // the function, we pretend that we don't have the full function
2452 // type.
John McCall2979fe02011-04-12 00:42:48 +00002453 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2454 isa<FunctionProtoType>(fty))
2455 type = Context.getFunctionNoProtoType(fty->getResultType(),
2456 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002457
2458 // Functions are r-values in C.
2459 valueKind = VK_RValue;
2460 break;
2461 }
2462
2463 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002464 // If we're referring to a method with an __unknown_anytype
2465 // result type, make the entire expression __unknown_anytype.
2466 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002467 if (const FunctionProtoType *proto
2468 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002469 if (proto->getResultType() == Context.UnknownAnyTy) {
2470 type = Context.UnknownAnyTy;
2471 valueKind = VK_RValue;
2472 break;
2473 }
2474
John McCallf4cd4f92011-02-09 01:13:10 +00002475 // C++ methods are l-values if static, r-values if non-static.
2476 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2477 valueKind = VK_LValue;
2478 break;
2479 }
2480 // fallthrough
2481
2482 case Decl::CXXConversion:
2483 case Decl::CXXDestructor:
2484 case Decl::CXXConstructor:
2485 valueKind = VK_RValue;
2486 break;
2487 }
2488
2489 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2490 }
2491
John McCallc63de662011-02-02 13:00:07 +00002492 }
John McCall7decc9e2010-11-18 06:31:45 +00002493
John McCall351762c2011-02-07 10:33:21 +00002494 llvm_unreachable("unknown capture result");
2495 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002496}
Chris Lattnere168f762006-11-10 05:29:30 +00002497
John McCall2979fe02011-04-12 00:42:48 +00002498ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002499 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002500
Chris Lattnere168f762006-11-10 05:29:30 +00002501 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002502 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002503 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2504 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2505 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002506 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002507
Chris Lattnera81a0272008-01-12 08:14:25 +00002508 // Pre-defined identifiers are of type char[x], where x is the length of the
2509 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002510
Anders Carlsson2fb08242009-09-08 18:24:21 +00002511 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002512 if (!currentDecl && getCurBlock())
2513 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002514 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002515 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002516 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002517 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002518
Anders Carlsson0b209a82009-09-11 01:22:35 +00002519 QualType ResTy;
2520 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2521 ResTy = Context.DependentTy;
2522 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002523 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002524
Anders Carlsson0b209a82009-09-11 01:22:35 +00002525 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002526 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002527 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2528 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002529 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002530}
2531
John McCalldadc5752010-08-24 06:29:42 +00002532ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002533 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002534 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002536 if (Invalid)
2537 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002538
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002539 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002540 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002541 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002542 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002543
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002544 QualType Ty;
2545 if (!getLangOptions().CPlusPlus)
2546 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2547 else if (Literal.isWide())
2548 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002549 else if (Literal.isUTF16())
2550 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2551 else if (Literal.isUTF32())
2552 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002553 else if (Literal.isMultiChar())
2554 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002555 else
2556 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002557
Douglas Gregorfb65e592011-07-27 05:40:30 +00002558 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2559 if (Literal.isWide())
2560 Kind = CharacterLiteral::Wide;
2561 else if (Literal.isUTF16())
2562 Kind = CharacterLiteral::UTF16;
2563 else if (Literal.isUTF32())
2564 Kind = CharacterLiteral::UTF32;
2565
2566 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2567 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002568}
2569
John McCalldadc5752010-08-24 06:29:42 +00002570ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002572 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2573 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002574 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002575 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002576 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002577 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002578 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002579
Chris Lattner23b7eb62007-06-15 23:05:46 +00002580 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002581 // Add padding so that NumericLiteralParser can overread by one character.
2582 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002583 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002584
Chris Lattner67ca9252007-05-21 01:08:44 +00002585 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002586 bool Invalid = false;
2587 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2588 if (Invalid)
2589 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002590
Mike Stump11289f42009-09-09 15:08:12 +00002591 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002592 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002593 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002594 return ExprError();
2595
Chris Lattner1c20a172007-08-26 03:42:43 +00002596 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002597
Chris Lattner1c20a172007-08-26 03:42:43 +00002598 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002599 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002600 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002601 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002602 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002603 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002604 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002605 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002606
2607 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2608
John McCall53b93a02009-12-24 09:08:04 +00002609 using llvm::APFloat;
2610 APFloat Val(Format);
2611
2612 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002613
2614 // Overflow is always an error, but underflow is only an error if
2615 // we underflowed to zero (APFloat reports denormals as underflow).
2616 if ((result & APFloat::opOverflow) ||
2617 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002618 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002619 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002620 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002621 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002622 APFloat::getLargest(Format).toString(buffer);
2623 } else {
John McCall62abc942010-02-26 23:35:57 +00002624 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002625 APFloat::getSmallest(Format).toString(buffer);
2626 }
2627
2628 Diag(Tok.getLocation(), diagnostic)
2629 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002630 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002631 }
2632
2633 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002634 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002635
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002636 if (Ty == Context.DoubleTy) {
2637 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002638 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002639 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2640 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002641 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002642 }
2643 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002644 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002645 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002646 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002647 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002648
Neil Boothac582c52007-08-29 22:00:19 +00002649 // long long is a C99 feature.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002650 if (!getLangOptions().C99 && Literal.isLongLong)
2651 Diag(Tok.getLocation(),
2652 getLangOptions().CPlusPlus0x ?
2653 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002654
Chris Lattner67ca9252007-05-21 01:08:44 +00002655 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002656 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002657
Chris Lattner67ca9252007-05-21 01:08:44 +00002658 if (Literal.GetIntegerValue(ResultVal)) {
2659 // If this value didn't fit into uintmax_t, warn and force to ull.
2660 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002661 Ty = Context.UnsignedLongLongTy;
2662 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002663 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002664 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 // If this value fits into a ULL, try to figure out what else it fits into
2666 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002667
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2669 // be an unsigned int.
2670 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2671
2672 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002673 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002674 if (!Literal.isLong && !Literal.isLongLong) {
2675 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002676 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // Does it fit in a unsigned int?
2679 if (ResultVal.isIntN(IntSize)) {
2680 // Does it fit in a signed int?
2681 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002690 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002691 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 // Does it fit in a unsigned long?
2694 if (ResultVal.isIntN(LongSize)) {
2695 // Does it fit in a signed long?
2696 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002697 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002698 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002699 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702 }
2703
Chris Lattner67ca9252007-05-21 01:08:44 +00002704 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002705 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002706 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002707
Chris Lattner67ca9252007-05-21 01:08:44 +00002708 // Does it fit in a unsigned long long?
2709 if (ResultVal.isIntN(LongLongSize)) {
2710 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002711 // To be compatible with MSVC, hex integer literals ending with the
2712 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002713 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002714 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002715 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002719 }
2720 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002721
Chris Lattner67ca9252007-05-21 01:08:44 +00002722 // If we still couldn't decide a type, we probably have something that
2723 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002724 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002725 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002726 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002727 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002728 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002729
Chris Lattner55258cf2008-05-09 05:59:00 +00002730 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002731 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002732 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002733 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002734 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002735
Chris Lattner1c20a172007-08-26 03:42:43 +00002736 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2737 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002738 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002739 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002740
2741 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002742}
2743
Richard Trieuba63ce62011-09-09 01:45:06 +00002744ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002745 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002746 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002747}
2748
Chandler Carruth62da79c2011-05-26 08:53:12 +00002749static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2750 SourceLocation Loc,
2751 SourceRange ArgRange) {
2752 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2753 // scalar or vector data type argument..."
2754 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2755 // type (C99 6.2.5p18) or void.
2756 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2757 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2758 << T << ArgRange;
2759 return true;
2760 }
2761
2762 assert((T->isVoidType() || !T->isIncompleteType()) &&
2763 "Scalar types should always be complete");
2764 return false;
2765}
2766
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002767static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2768 SourceLocation Loc,
2769 SourceRange ArgRange,
2770 UnaryExprOrTypeTrait TraitKind) {
2771 // C99 6.5.3.4p1:
2772 if (T->isFunctionType()) {
2773 // alignof(function) is allowed as an extension.
2774 if (TraitKind == UETT_SizeOf)
2775 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2776 return false;
2777 }
2778
2779 // Allow sizeof(void)/alignof(void) as an extension.
2780 if (T->isVoidType()) {
2781 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2782 return false;
2783 }
2784
2785 return true;
2786}
2787
2788static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2789 SourceLocation Loc,
2790 SourceRange ArgRange,
2791 UnaryExprOrTypeTrait TraitKind) {
2792 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2793 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2794 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2795 << T << (TraitKind == UETT_SizeOf)
2796 << ArgRange;
2797 return true;
2798 }
2799
2800 return false;
2801}
2802
Chandler Carruth14502c22011-05-26 08:53:10 +00002803/// \brief Check the constrains on expression operands to unary type expression
2804/// and type traits.
2805///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002806/// Completes any types necessary and validates the constraints on the operand
2807/// expression. The logic mostly mirrors the type-based overload, but may modify
2808/// the expression as it completes the type for that expression through template
2809/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002810bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002811 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002812 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002813
2814 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2815 // the result is the size of the referenced type."
2816 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2817 // result shall be the alignment of the referenced type."
2818 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2819 ExprTy = Ref->getPointeeType();
2820
2821 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002822 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2823 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002824
2825 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002826 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2827 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002828 return false;
2829
Richard Trieuba63ce62011-09-09 01:45:06 +00002830 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002831 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002832 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002833 std::make_pair(SourceLocation(), PDiag(0))))
2834 return true;
2835
2836 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002837 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002838 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2839 ExprTy = Ref->getPointeeType();
2840
Richard Trieuba63ce62011-09-09 01:45:06 +00002841 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2842 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002843 return true;
2844
Nico Weber0870deb2011-06-15 02:47:03 +00002845 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002846 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002847 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2848 QualType OType = PVD->getOriginalType();
2849 QualType Type = PVD->getType();
2850 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002851 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002852 << Type << OType;
2853 Diag(PVD->getLocation(), diag::note_declared_at);
2854 }
2855 }
2856 }
2857 }
2858
Chandler Carruth7c430c02011-05-27 01:33:31 +00002859 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002860}
2861
2862/// \brief Check the constraints on operands to unary expression and type
2863/// traits.
2864///
2865/// This will complete any types necessary, and validate the various constraints
2866/// on those operands.
2867///
Steve Naroff71b59a92007-06-04 22:22:31 +00002868/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002869/// C99 6.3.2.1p[2-4] all state:
2870/// Except when it is the operand of the sizeof operator ...
2871///
2872/// C++ [expr.sizeof]p4
2873/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2874/// standard conversions are not applied to the operand of sizeof.
2875///
2876/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002877bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002878 SourceLocation OpLoc,
2879 SourceRange ExprRange,
2880 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002881 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002882 return false;
2883
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002884 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2885 // the result is the size of the referenced type."
2886 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2887 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002888 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2889 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002890
Chandler Carruth62da79c2011-05-26 08:53:12 +00002891 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002892 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002894 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002895 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002896 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002897 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Richard Trieuba63ce62011-09-09 01:45:06 +00002899 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002900 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002901 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002902 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002903
Richard Trieuba63ce62011-09-09 01:45:06 +00002904 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002905 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002906 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002907
Chris Lattner62975a72009-04-24 00:30:45 +00002908 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002909}
2910
Chandler Carruth14502c22011-05-26 08:53:10 +00002911static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002912 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002913
Mike Stump11289f42009-09-09 15:08:12 +00002914 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002915 if (isa<DeclRefExpr>(E))
2916 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002917
2918 // Cannot know anything else if the expression is dependent.
2919 if (E->isTypeDependent())
2920 return false;
2921
Douglas Gregor71235ec2009-05-02 02:18:30 +00002922 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002923 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2924 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002925 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002926 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002927
2928 // Alignment of a field access is always okay, so long as it isn't a
2929 // bit-field.
2930 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002931 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002932 return false;
2933
Chandler Carruth14502c22011-05-26 08:53:10 +00002934 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002935}
2936
Chandler Carruth14502c22011-05-26 08:53:10 +00002937bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002938 E = E->IgnoreParens();
2939
2940 // Cannot know anything else if the expression is dependent.
2941 if (E->isTypeDependent())
2942 return false;
2943
Chandler Carruth14502c22011-05-26 08:53:10 +00002944 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002945}
2946
Douglas Gregor0950e412009-03-13 21:01:28 +00002947/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002948ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002949Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2950 SourceLocation OpLoc,
2951 UnaryExprOrTypeTrait ExprKind,
2952 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002953 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002954 return ExprError();
2955
John McCallbcd03502009-12-07 02:54:59 +00002956 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002957
Douglas Gregor0950e412009-03-13 21:01:28 +00002958 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002959 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002960 return ExprError();
2961
2962 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002963 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2964 Context.getSizeType(),
2965 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002966}
2967
2968/// \brief Build a sizeof or alignof expression given an expression
2969/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002970ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002971Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2972 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002973 ExprResult PE = CheckPlaceholderExpr(E);
2974 if (PE.isInvalid())
2975 return ExprError();
2976
2977 E = PE.get();
2978
Douglas Gregor0950e412009-03-13 21:01:28 +00002979 // Verify that the operand is valid.
2980 bool isInvalid = false;
2981 if (E->isTypeDependent()) {
2982 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002983 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002984 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002985 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002986 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002987 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002988 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002989 isInvalid = true;
2990 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002991 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002992 }
2993
2994 if (isInvalid)
2995 return ExprError();
2996
2997 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002998 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002999 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003000 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003001}
3002
Peter Collingbournee190dee2011-03-11 19:24:49 +00003003/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3004/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003005/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003006ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003007Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003008 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003009 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003010 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003011 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003012
Richard Trieuba63ce62011-09-09 01:45:06 +00003013 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003014 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003015 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003016 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003017 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003018
Douglas Gregor0950e412009-03-13 21:01:28 +00003019 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003020 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003021 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003022}
3023
John Wiegley01296292011-04-08 18:41:53 +00003024static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003025 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003026 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003027 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003028
John McCall34376a62010-12-04 03:47:34 +00003029 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003030 if (V.get()->getObjectKind() != OK_Ordinary) {
3031 V = S.DefaultLvalueConversion(V.take());
3032 if (V.isInvalid())
3033 return QualType();
3034 }
John McCall34376a62010-12-04 03:47:34 +00003035
Chris Lattnere267f5d2007-08-26 05:39:26 +00003036 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003037 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003038 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003039
Chris Lattnere267f5d2007-08-26 05:39:26 +00003040 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003041 if (V.get()->getType()->isArithmeticType())
3042 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003043
John McCall36226622010-10-12 02:09:17 +00003044 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003045 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003046 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003047 if (PR.get() != V.get()) {
3048 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003049 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003050 }
3051
Chris Lattnere267f5d2007-08-26 05:39:26 +00003052 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003053 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003054 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003055 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003056}
3057
3058
Chris Lattnere168f762006-11-10 05:29:30 +00003059
John McCalldadc5752010-08-24 06:29:42 +00003060ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003061Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003062 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003063 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003064 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003065 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003066 case tok::plusplus: Opc = UO_PostInc; break;
3067 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003068 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003069
John McCallb268a282010-08-23 23:25:46 +00003070 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003071}
3072
John McCalldadc5752010-08-24 06:29:42 +00003073ExprResult
John McCallb268a282010-08-23 23:25:46 +00003074Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3075 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003076 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003077 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003078 if (Result.isInvalid()) return ExprError();
3079 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003080
John McCallb268a282010-08-23 23:25:46 +00003081 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003082
Douglas Gregor40412ac2008-11-19 17:17:41 +00003083 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003084 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003085 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003086 Context.DependentTy,
3087 VK_LValue, OK_Ordinary,
3088 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003089 }
3090
Mike Stump11289f42009-09-09 15:08:12 +00003091 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003092 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003093 LHSExp->getType()->isEnumeralType() ||
3094 RHSExp->getType()->isRecordType() ||
3095 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003096 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003097 }
3098
John McCallb268a282010-08-23 23:25:46 +00003099 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003100}
3101
3102
John McCalldadc5752010-08-24 06:29:42 +00003103ExprResult
John McCallb268a282010-08-23 23:25:46 +00003104Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003105 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003106 Expr *LHSExp = Base;
3107 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003108
Chris Lattner36d572b2007-07-16 00:14:47 +00003109 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003110 if (!LHSExp->getType()->getAs<VectorType>()) {
3111 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3112 if (Result.isInvalid())
3113 return ExprError();
3114 LHSExp = Result.take();
3115 }
3116 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3117 if (Result.isInvalid())
3118 return ExprError();
3119 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003120
Chris Lattner36d572b2007-07-16 00:14:47 +00003121 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003122 ExprValueKind VK = VK_LValue;
3123 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003124
Steve Naroffc1aadb12007-03-28 21:49:40 +00003125 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003126 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003127 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003128 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003129 Expr *BaseExpr, *IndexExpr;
3130 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003131 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3132 BaseExpr = LHSExp;
3133 IndexExpr = RHSExp;
3134 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003135 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003136 BaseExpr = LHSExp;
3137 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003138 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003139 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003140 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003141 BaseExpr = RHSExp;
3142 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003143 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003144 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003145 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003146 BaseExpr = LHSExp;
3147 IndexExpr = RHSExp;
3148 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003149 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003150 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003151 // Handle the uncommon case of "123[Ptr]".
3152 BaseExpr = RHSExp;
3153 IndexExpr = LHSExp;
3154 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003155 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003156 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003157 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003158 VK = LHSExp->getValueKind();
3159 if (VK != VK_RValue)
3160 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003161
Chris Lattner36d572b2007-07-16 00:14:47 +00003162 // FIXME: need to deal with const...
3163 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003164 } else if (LHSTy->isArrayType()) {
3165 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003166 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003167 // wasn't promoted because of the C90 rule that doesn't
3168 // allow promoting non-lvalue arrays. Warn, then
3169 // force the promotion here.
3170 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3171 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003172 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3173 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003174 LHSTy = LHSExp->getType();
3175
3176 BaseExpr = LHSExp;
3177 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003178 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003179 } else if (RHSTy->isArrayType()) {
3180 // Same as previous, except for 123[f().a] case
3181 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3182 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003183 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3184 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003185 RHSTy = RHSExp->getType();
3186
3187 BaseExpr = RHSExp;
3188 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003189 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003190 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003191 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3192 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003193 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003194 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003195 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003196 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3197 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003198
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003199 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003200 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3201 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003202 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3203
Douglas Gregorac1fb652009-03-24 19:52:54 +00003204 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003205 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3206 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003207 // incomplete types are not object types.
3208 if (ResultType->isFunctionType()) {
3209 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3210 << ResultType << BaseExpr->getSourceRange();
3211 return ExprError();
3212 }
Mike Stump11289f42009-09-09 15:08:12 +00003213
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003214 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3215 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003216 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3217 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003218
3219 // C forbids expressions of unqualified void type from being l-values.
3220 // See IsCForbiddenLValueType.
3221 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003222 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003223 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003224 PDiag(diag::err_subscript_incomplete_type)
3225 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003226 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003227
Chris Lattner62975a72009-04-24 00:30:45 +00003228 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003229 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003230 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3231 << ResultType << BaseExpr->getSourceRange();
3232 return ExprError();
3233 }
Mike Stump11289f42009-09-09 15:08:12 +00003234
John McCall4bc41ae2010-11-18 19:01:18 +00003235 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003236 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003237
Mike Stump4e1f26a2009-02-19 03:04:26 +00003238 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003239 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003240}
3241
John McCalldadc5752010-08-24 06:29:42 +00003242ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003243 FunctionDecl *FD,
3244 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003245 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003246 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003247 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003248 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003249 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003250 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003251 return ExprError();
3252 }
3253
3254 if (Param->hasUninstantiatedDefaultArg()) {
3255 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003256
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003257 // Instantiate the expression.
3258 MultiLevelTemplateArgumentList ArgList
3259 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003260
Nico Weber44887f62010-11-29 18:19:25 +00003261 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003262 = ArgList.getInnermost();
3263 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3264 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003265
Nico Weber44887f62010-11-29 18:19:25 +00003266 ExprResult Result;
3267 {
3268 // C++ [dcl.fct.default]p5:
3269 // The names in the [default argument] expression are bound, and
3270 // the semantic constraints are checked, at the point where the
3271 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003272 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003273 Result = SubstExpr(UninstExpr, ArgList);
3274 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003275 if (Result.isInvalid())
3276 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003278 // Check the expression as an initializer for the parameter.
3279 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003280 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003281 InitializationKind Kind
3282 = InitializationKind::CreateCopy(Param->getLocation(),
3283 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3284 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003285
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003286 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3287 Result = InitSeq.Perform(*this, Entity, Kind,
3288 MultiExprArg(*this, &ResultE, 1));
3289 if (Result.isInvalid())
3290 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003291
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003292 // Build the default argument expression.
3293 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3294 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003295 }
3296
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003297 // If the default expression creates temporaries, we need to
3298 // push them to the current stack of expression temporaries so they'll
3299 // be properly destroyed.
3300 // FIXME: We should really be rebuilding the default argument with new
3301 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003302 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3303 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3304 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3305 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3306 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003307 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003308 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003309
3310 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003311 // Just mark all of the declarations in this potentially-evaluated expression
3312 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003313 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003314 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003315}
3316
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317/// ConvertArgumentsForCall - Converts the arguments specified in
3318/// Args/NumArgs to the parameter types of the function FDecl with
3319/// function prototype Proto. Call is the call expression itself, and
3320/// Fn is the function expression. For a C++ member function, this
3321/// routine does not attempt to convert the object argument. Returns
3322/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003323bool
3324Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003325 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003326 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003327 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003328 SourceLocation RParenLoc,
3329 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003330 // Bail out early if calling a builtin with custom typechecking.
3331 // We don't need to do this in the
3332 if (FDecl)
3333 if (unsigned ID = FDecl->getBuiltinID())
3334 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3335 return false;
3336
Mike Stump4e1f26a2009-02-19 03:04:26 +00003337 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 // assignment, to the types of the corresponding parameter, ...
3339 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003340 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003341 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003342 unsigned FnKind = Fn->getType()->isBlockPointerType()
3343 ? 1 /* block */
3344 : (IsExecConfig ? 3 /* kernel function (exec config) */
3345 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003346
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003347 // If too few arguments are available (and we don't have default
3348 // arguments for the remaining parameters), don't make the call.
3349 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003350 if (NumArgs < MinArgs) {
3351 Diag(RParenLoc, MinArgs == NumArgsInProto
3352 ? diag::err_typecheck_call_too_few_args
3353 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003354 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003355 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003356
3357 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003358 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003359 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3360 << FDecl;
3361
3362 return true;
3363 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003364 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003365 }
3366
3367 // If too many are passed and not variadic, error on the extras and drop
3368 // them.
3369 if (NumArgs > NumArgsInProto) {
3370 if (!Proto->isVariadic()) {
3371 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003372 MinArgs == NumArgsInProto
3373 ? diag::err_typecheck_call_too_many_args
3374 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003375 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003376 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003377 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3378 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003379
3380 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003381 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003382 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3383 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003384
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003385 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003386 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003387 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003388 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003389 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003390 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003391 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003392 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3393 if (Fn->getType()->isBlockPointerType())
3394 CallType = VariadicBlock; // Block
3395 else if (isa<MemberExpr>(Fn))
3396 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003397 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003398 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003399 if (Invalid)
3400 return true;
3401 unsigned TotalNumArgs = AllArgs.size();
3402 for (unsigned i = 0; i < TotalNumArgs; ++i)
3403 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003404
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003405 return false;
3406}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003407
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003408bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3409 FunctionDecl *FDecl,
3410 const FunctionProtoType *Proto,
3411 unsigned FirstProtoArg,
3412 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003413 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003414 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003415 unsigned NumArgsInProto = Proto->getNumArgs();
3416 unsigned NumArgsToCheck = NumArgs;
3417 bool Invalid = false;
3418 if (NumArgs != NumArgsInProto)
3419 // Use default arguments for missing arguments
3420 NumArgsToCheck = NumArgsInProto;
3421 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003422 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003423 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003424 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003425
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003426 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003427 if (ArgIx < NumArgs) {
3428 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003429
Eli Friedman3164fb12009-03-22 22:00:50 +00003430 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3431 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003432 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003433 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003434 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003435
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003436 // Pass the argument
3437 ParmVarDecl *Param = 0;
3438 if (FDecl && i < FDecl->getNumParams())
3439 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003440
John McCall4124c492011-10-17 18:40:02 +00003441 // Strip the unbridged-cast placeholder expression off, if applicable.
3442 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3443 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3444 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3445 Arg = stripARCUnbridgedCast(Arg);
3446
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003447 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003448 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003449 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3450 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003451 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003452 SourceLocation(),
3453 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003454 if (ArgE.isInvalid())
3455 return true;
3456
3457 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003458 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003459 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003460
John McCalldadc5752010-08-24 06:29:42 +00003461 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003462 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003463 if (ArgExpr.isInvalid())
3464 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003465
Anders Carlsson355933d2009-08-25 03:49:14 +00003466 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003467 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003468
3469 // Check for array bounds violations for each argument to the call. This
3470 // check only triggers warnings when the argument isn't a more complex Expr
3471 // with its own checking, such as a BinaryOperator.
3472 CheckArrayAccess(Arg);
3473
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003474 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003475 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003476
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003477 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003478 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003479
3480 // Assume that extern "C" functions with variadic arguments that
3481 // return __unknown_anytype aren't *really* variadic.
3482 if (Proto->getResultType() == Context.UnknownAnyTy &&
3483 FDecl && FDecl->isExternC()) {
3484 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3485 ExprResult arg;
3486 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3487 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3488 else
3489 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3490 Invalid |= arg.isInvalid();
3491 AllArgs.push_back(arg.take());
3492 }
3493
3494 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3495 } else {
3496 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003497 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3498 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003499 Invalid |= Arg.isInvalid();
3500 AllArgs.push_back(Arg.take());
3501 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003502 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003503
3504 // Check for array bounds violations.
3505 for (unsigned i = ArgIx; i != NumArgs; ++i)
3506 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003507 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003508 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509}
3510
John McCall2979fe02011-04-12 00:42:48 +00003511/// Given a function expression of unknown-any type, try to rebuild it
3512/// to have a function type.
3513static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3514
Steve Naroff83895f72007-09-16 03:34:24 +00003515/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003516/// This provides the location of the left/right parens and a list of comma
3517/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003518ExprResult
John McCallb268a282010-08-23 23:25:46 +00003519Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003520 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003521 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003522 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003523
3524 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003525 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003526 if (Result.isInvalid()) return ExprError();
3527 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003528
Richard Trieuba63ce62011-09-09 01:45:06 +00003529 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003530
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003531 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003532 // If this is a pseudo-destructor expression, build the call immediately.
3533 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3534 if (NumArgs > 0) {
3535 // Pseudo-destructor calls should not have any arguments.
3536 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003537 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003538 SourceRange(Args[0]->getLocStart(),
3539 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003540
Douglas Gregorad8a3362009-09-04 17:36:40 +00003541 NumArgs = 0;
3542 }
Mike Stump11289f42009-09-09 15:08:12 +00003543
Douglas Gregorad8a3362009-09-04 17:36:40 +00003544 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003545 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003548 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003549 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003550 // FIXME: Will need to cache the results of name lookup (including ADL) in
3551 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003552 bool Dependent = false;
3553 if (Fn->isTypeDependent())
3554 Dependent = true;
3555 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3556 Dependent = true;
3557
Peter Collingbourne41f85462011-02-09 21:07:24 +00003558 if (Dependent) {
3559 if (ExecConfig) {
3560 return Owned(new (Context) CUDAKernelCallExpr(
3561 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3562 Context.DependentTy, VK_RValue, RParenLoc));
3563 } else {
3564 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3565 Context.DependentTy, VK_RValue,
3566 RParenLoc));
3567 }
3568 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003569
3570 // Determine whether this is a call to an object (C++ [over.call.object]).
3571 if (Fn->getType()->isRecordType())
3572 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003573 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003574
John McCall2979fe02011-04-12 00:42:48 +00003575 if (Fn->getType() == Context.UnknownAnyTy) {
3576 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3577 if (result.isInvalid()) return ExprError();
3578 Fn = result.take();
3579 }
3580
John McCall0009fcc2011-04-26 20:42:42 +00003581 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003582 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003583 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003584 }
John McCall0009fcc2011-04-26 20:42:42 +00003585 }
John McCall10eae182009-11-30 22:42:35 +00003586
John McCall0009fcc2011-04-26 20:42:42 +00003587 // Check for overloaded calls. This can happen even in C due to extensions.
3588 if (Fn->getType() == Context.OverloadTy) {
3589 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3590
Douglas Gregorcda22702011-10-13 18:10:35 +00003591 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003592 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003593 OverloadExpr *ovl = find.Expression;
3594 if (isa<UnresolvedLookupExpr>(ovl)) {
3595 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3596 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3597 RParenLoc, ExecConfig);
3598 } else {
John McCall2d74de92009-12-01 22:10:20 +00003599 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003600 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003601 }
3602 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003603 }
3604
Douglas Gregore254f902009-02-04 00:32:51 +00003605 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003606
Eli Friedmane14b1992009-12-26 03:35:45 +00003607 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003608
John McCall57500772009-12-16 12:17:52 +00003609 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003610 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3611 if (UnOp->getOpcode() == UO_AddrOf)
3612 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3613
John McCall57500772009-12-16 12:17:52 +00003614 if (isa<DeclRefExpr>(NakedFn))
3615 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003616 else if (isa<MemberExpr>(NakedFn))
3617 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003618
Peter Collingbourne41f85462011-02-09 21:07:24 +00003619 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003620 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003621}
3622
3623ExprResult
3624Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003625 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003626 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3627 if (!ConfigDecl)
3628 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3629 << "cudaConfigureCall");
3630 QualType ConfigQTy = ConfigDecl->getType();
3631
3632 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3633 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3634
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003635 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3636 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003637}
3638
Tanya Lattner55808c12011-06-04 00:47:47 +00003639/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3640///
3641/// __builtin_astype( value, dst type )
3642///
Richard Trieuba63ce62011-09-09 01:45:06 +00003643ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003644 SourceLocation BuiltinLoc,
3645 SourceLocation RParenLoc) {
3646 ExprValueKind VK = VK_RValue;
3647 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003648 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3649 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003650 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3651 return ExprError(Diag(BuiltinLoc,
3652 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003653 << DstTy
3654 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003655 << E->getSourceRange());
3656 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003657 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003658}
3659
John McCall57500772009-12-16 12:17:52 +00003660/// BuildResolvedCallExpr - Build a call to a resolved expression,
3661/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003662/// unary-convert to an expression of function-pointer or
3663/// block-pointer type.
3664///
3665/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003666ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003667Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3668 SourceLocation LParenLoc,
3669 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003670 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003671 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003672 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3673
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003674 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003675 ExprResult Result = UsualUnaryConversions(Fn);
3676 if (Result.isInvalid())
3677 return ExprError();
3678 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003679
Chris Lattner08464942007-12-28 05:29:59 +00003680 // Make the call expr early, before semantic checks. This guarantees cleanup
3681 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003682 CallExpr *TheCall;
3683 if (Config) {
3684 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3685 cast<CallExpr>(Config),
3686 Args, NumArgs,
3687 Context.BoolTy,
3688 VK_RValue,
3689 RParenLoc);
3690 } else {
3691 TheCall = new (Context) CallExpr(Context, Fn,
3692 Args, NumArgs,
3693 Context.BoolTy,
3694 VK_RValue,
3695 RParenLoc);
3696 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003697
John McCallbebede42011-02-26 05:39:39 +00003698 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3699
3700 // Bail out early if calling a builtin with custom typechecking.
3701 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3702 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3703
John McCall31996342011-04-07 08:22:57 +00003704 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003705 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003706 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003707 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3708 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003709 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003710 if (FuncT == 0)
3711 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3712 << Fn->getType() << Fn->getSourceRange());
3713 } else if (const BlockPointerType *BPT =
3714 Fn->getType()->getAs<BlockPointerType>()) {
3715 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3716 } else {
John McCall31996342011-04-07 08:22:57 +00003717 // Handle calls to expressions of unknown-any type.
3718 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003719 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003720 if (rewrite.isInvalid()) return ExprError();
3721 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003722 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003723 goto retry;
3724 }
3725
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003726 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3727 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003728 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003729
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003730 if (getLangOptions().CUDA) {
3731 if (Config) {
3732 // CUDA: Kernel calls must be to global functions
3733 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3734 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3735 << FDecl->getName() << Fn->getSourceRange());
3736
3737 // CUDA: Kernel function must have 'void' return type
3738 if (!FuncT->getResultType()->isVoidType())
3739 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3740 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003741 } else {
3742 // CUDA: Calls to global functions must be configured
3743 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3744 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3745 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003746 }
3747 }
3748
Eli Friedman3164fb12009-03-22 22:00:50 +00003749 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003750 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003751 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003752 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003753 return ExprError();
3754
Chris Lattner08464942007-12-28 05:29:59 +00003755 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003756 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003757 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003758
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003759 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003760 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003761 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003762 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003763 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003764 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003765
Douglas Gregord8e97de2009-04-02 15:37:10 +00003766 if (FDecl) {
3767 // Check if we have too few/too many template arguments, based
3768 // on our knowledge of the function definition.
3769 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003770 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003771 const FunctionProtoType *Proto
3772 = Def->getType()->getAs<FunctionProtoType>();
3773 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003774 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3775 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003776 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003777
3778 // If the function we're calling isn't a function prototype, but we have
3779 // a function prototype from a prior declaratiom, use that prototype.
3780 if (!FDecl->hasPrototype())
3781 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003782 }
3783
Steve Naroff0b661582007-08-28 23:30:39 +00003784 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003785 for (unsigned i = 0; i != NumArgs; i++) {
3786 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003787
3788 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003789 InitializedEntity Entity
3790 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003791 Proto->getArgType(i),
3792 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003793 ExprResult ArgE = PerformCopyInitialization(Entity,
3794 SourceLocation(),
3795 Owned(Arg));
3796 if (ArgE.isInvalid())
3797 return true;
3798
3799 Arg = ArgE.takeAs<Expr>();
3800
3801 } else {
John Wiegley01296292011-04-08 18:41:53 +00003802 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3803
3804 if (ArgE.isInvalid())
3805 return true;
3806
3807 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003808 }
3809
Douglas Gregor83025412010-10-26 05:45:40 +00003810 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3811 Arg->getType(),
3812 PDiag(diag::err_call_incomplete_argument)
3813 << Arg->getSourceRange()))
3814 return ExprError();
3815
Chris Lattner08464942007-12-28 05:29:59 +00003816 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003817 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003818 }
Chris Lattner08464942007-12-28 05:29:59 +00003819
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003820 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3821 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003822 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3823 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003824
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003825 // Check for sentinels
3826 if (NDecl)
3827 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003828
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003829 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003830 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003831 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003832 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003833
John McCallbebede42011-02-26 05:39:39 +00003834 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003835 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003836 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003837 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003838 return ExprError();
3839 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003840
John McCallb268a282010-08-23 23:25:46 +00003841 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003842}
3843
John McCalldadc5752010-08-24 06:29:42 +00003844ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003845Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003846 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003847 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003848 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003849 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003850
3851 TypeSourceInfo *TInfo;
3852 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3853 if (!TInfo)
3854 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3855
John McCallb268a282010-08-23 23:25:46 +00003856 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003857}
3858
John McCalldadc5752010-08-24 06:29:42 +00003859ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003860Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003861 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003862 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003863
Eli Friedman37a186d2008-05-20 05:22:08 +00003864 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003865 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3866 PDiag(diag::err_illegal_decl_array_incomplete_type)
3867 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003868 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003869 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003870 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003871 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003872 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003873 } else if (!literalType->isDependentType() &&
3874 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003875 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003876 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003877 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003878 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003879
Douglas Gregor85dabae2009-12-16 01:38:02 +00003880 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003881 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003882 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003883 = InitializationKind::CreateCStyleCast(LParenLoc,
3884 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003885 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003886 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003887 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003888 &literalType);
3889 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003890 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003891 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003892
Chris Lattner79413952008-12-04 23:50:19 +00003893 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003894 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003895 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003896 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003897 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003898
John McCall7decc9e2010-11-18 06:31:45 +00003899 // In C, compound literals are l-values for some reason.
3900 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3901
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003902 return MaybeBindToTemporary(
3903 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003904 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003905}
3906
John McCalldadc5752010-08-24 06:29:42 +00003907ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003908Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003909 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003910 unsigned NumInit = InitArgList.size();
3911 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003912
Steve Naroff30d242c2007-09-15 18:49:24 +00003913 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003914 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003915
Ted Kremenekac034612010-04-13 23:39:13 +00003916 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3917 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003918 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003919 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003920}
3921
John McCallcd78e802011-09-10 01:16:55 +00003922/// Do an explicit extend of the given block pointer if we're in ARC.
3923static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3924 assert(E.get()->getType()->isBlockPointerType());
3925 assert(E.get()->isRValue());
3926
3927 // Only do this in an r-value context.
3928 if (!S.getLangOptions().ObjCAutoRefCount) return;
3929
3930 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003931 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003932 /*base path*/ 0, VK_RValue);
3933 S.ExprNeedsCleanups = true;
3934}
3935
3936/// Prepare a conversion of the given expression to an ObjC object
3937/// pointer type.
3938CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3939 QualType type = E.get()->getType();
3940 if (type->isObjCObjectPointerType()) {
3941 return CK_BitCast;
3942 } else if (type->isBlockPointerType()) {
3943 maybeExtendBlockObject(*this, E);
3944 return CK_BlockPointerToObjCPointerCast;
3945 } else {
3946 assert(type->isPointerType());
3947 return CK_CPointerToObjCPointerCast;
3948 }
3949}
3950
John McCalld7646252010-11-14 08:17:51 +00003951/// Prepares for a scalar cast, performing all the necessary stages
3952/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00003953CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003954 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3955 // Also, callers should have filtered out the invalid cases with
3956 // pointers. Everything else should be possible.
3957
John Wiegley01296292011-04-08 18:41:53 +00003958 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00003959 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003960 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003961
John McCall9320b872011-09-09 05:25:32 +00003962 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003963 case Type::STK_MemberPointer:
3964 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003965
John McCall9320b872011-09-09 05:25:32 +00003966 case Type::STK_CPointer:
3967 case Type::STK_BlockPointer:
3968 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003969 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003970 case Type::STK_CPointer:
3971 return CK_BitCast;
3972 case Type::STK_BlockPointer:
3973 return (SrcKind == Type::STK_BlockPointer
3974 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3975 case Type::STK_ObjCObjectPointer:
3976 if (SrcKind == Type::STK_ObjCObjectPointer)
3977 return CK_BitCast;
3978 else if (SrcKind == Type::STK_CPointer)
3979 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003980 else {
John McCall9776e432011-10-06 23:25:11 +00003981 maybeExtendBlockObject(*this, Src);
John McCall9320b872011-09-09 05:25:32 +00003982 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003983 }
John McCall8cb679e2010-11-15 09:13:47 +00003984 case Type::STK_Bool:
3985 return CK_PointerToBoolean;
3986 case Type::STK_Integral:
3987 return CK_PointerToIntegral;
3988 case Type::STK_Floating:
3989 case Type::STK_FloatingComplex:
3990 case Type::STK_IntegralComplex:
3991 case Type::STK_MemberPointer:
3992 llvm_unreachable("illegal cast from pointer");
3993 }
3994 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003995
John McCall8cb679e2010-11-15 09:13:47 +00003996 case Type::STK_Bool: // casting from bool is like casting from an integer
3997 case Type::STK_Integral:
3998 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003999 case Type::STK_CPointer:
4000 case Type::STK_ObjCObjectPointer:
4001 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004002 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004003 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004004 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004005 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004006 case Type::STK_Bool:
4007 return CK_IntegralToBoolean;
4008 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004009 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004010 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004011 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004012 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004013 Src = ImpCastExprToType(Src.take(),
4014 DestTy->castAs<ComplexType>()->getElementType(),
4015 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004016 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004017 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004018 Src = ImpCastExprToType(Src.take(),
4019 DestTy->castAs<ComplexType>()->getElementType(),
4020 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004021 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004022 case Type::STK_MemberPointer:
4023 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004024 }
4025 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004026
John McCall8cb679e2010-11-15 09:13:47 +00004027 case Type::STK_Floating:
4028 switch (DestTy->getScalarTypeKind()) {
4029 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004030 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004031 case Type::STK_Bool:
4032 return CK_FloatingToBoolean;
4033 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004034 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004035 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004036 Src = ImpCastExprToType(Src.take(),
4037 DestTy->castAs<ComplexType>()->getElementType(),
4038 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004039 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004040 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004041 Src = ImpCastExprToType(Src.take(),
4042 DestTy->castAs<ComplexType>()->getElementType(),
4043 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004044 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004045 case Type::STK_CPointer:
4046 case Type::STK_ObjCObjectPointer:
4047 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004048 llvm_unreachable("valid float->pointer cast?");
4049 case Type::STK_MemberPointer:
4050 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004051 }
4052 break;
4053
John McCall8cb679e2010-11-15 09:13:47 +00004054 case Type::STK_FloatingComplex:
4055 switch (DestTy->getScalarTypeKind()) {
4056 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004057 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004058 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004059 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004060 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004061 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4062 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004063 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004064 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004065 return CK_FloatingCast;
4066 }
John McCall8cb679e2010-11-15 09:13:47 +00004067 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004068 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004069 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004070 Src = ImpCastExprToType(Src.take(),
4071 SrcTy->castAs<ComplexType>()->getElementType(),
4072 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004073 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004074 case Type::STK_CPointer:
4075 case Type::STK_ObjCObjectPointer:
4076 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004077 llvm_unreachable("valid complex float->pointer cast?");
4078 case Type::STK_MemberPointer:
4079 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004080 }
4081 break;
4082
John McCall8cb679e2010-11-15 09:13:47 +00004083 case Type::STK_IntegralComplex:
4084 switch (DestTy->getScalarTypeKind()) {
4085 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004086 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004087 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004088 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004089 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004090 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4091 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004092 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004093 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004094 return CK_IntegralCast;
4095 }
John McCall8cb679e2010-11-15 09:13:47 +00004096 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004097 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004098 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004099 Src = ImpCastExprToType(Src.take(),
4100 SrcTy->castAs<ComplexType>()->getElementType(),
4101 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004102 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004103 case Type::STK_CPointer:
4104 case Type::STK_ObjCObjectPointer:
4105 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004106 llvm_unreachable("valid complex int->pointer cast?");
4107 case Type::STK_MemberPointer:
4108 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004109 }
4110 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004111 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004112
John McCalld7646252010-11-14 08:17:51 +00004113 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004114}
4115
Anders Carlsson525b76b2009-10-16 02:48:28 +00004116bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004117 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004118 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004119
Anders Carlssonde71adf2007-11-27 05:51:55 +00004120 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004121 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004122 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004123 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004124 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004125 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004126 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004127 } else
4128 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004129 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004130 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004131
John McCalle3027922010-08-25 11:45:40 +00004132 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004133 return false;
4134}
4135
John Wiegley01296292011-04-08 18:41:53 +00004136ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4137 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004138 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004139
Anders Carlsson43d70f82009-10-16 05:23:41 +00004140 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004141
Nate Begemanc8961a42009-06-27 22:05:55 +00004142 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4143 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004144 // In OpenCL, casts between vectors of different types are not allowed.
4145 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004146 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004147 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4148 || (getLangOptions().OpenCL &&
4149 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004150 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004151 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004152 return ExprError();
4153 }
John McCalle3027922010-08-25 11:45:40 +00004154 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004155 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004156 }
4157
Nate Begemanbd956c42009-06-28 02:36:38 +00004158 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004159 // conversion will take place first from scalar to elt type, and then
4160 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004161 if (SrcTy->isPointerType())
4162 return Diag(R.getBegin(),
4163 diag::err_invalid_conversion_between_vector_and_scalar)
4164 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004165
4166 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004167 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004168 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004169 if (CastExprRes.isInvalid())
4170 return ExprError();
4171 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004172
John McCalle3027922010-08-25 11:45:40 +00004173 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004174 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004175}
4176
John McCalldadc5752010-08-24 06:29:42 +00004177ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004178Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4179 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004180 SourceLocation RParenLoc, Expr *CastExpr) {
4181 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004182 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004183
Richard Trieuba63ce62011-09-09 01:45:06 +00004184 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004185 if (D.isInvalidType())
4186 return ExprError();
4187
4188 if (getLangOptions().CPlusPlus) {
4189 // Check that there are no default arguments (C++ only).
4190 CheckExtraCXXDefaultArguments(D);
4191 }
4192
John McCall42856de2011-10-01 05:17:03 +00004193 checkUnusedDeclAttributes(D);
4194
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004195 QualType castType = castTInfo->getType();
4196 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004197
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004198 bool isVectorLiteral = false;
4199
4200 // Check for an altivec or OpenCL literal,
4201 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004202 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4203 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004204 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4205 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004206 if (PLE && PLE->getNumExprs() == 0) {
4207 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4208 return ExprError();
4209 }
4210 if (PE || PLE->getNumExprs() == 1) {
4211 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4212 if (!E->getType()->isVectorType())
4213 isVectorLiteral = true;
4214 }
4215 else
4216 isVectorLiteral = true;
4217 }
4218
4219 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4220 // then handle it as such.
4221 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004222 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004223
Nate Begeman5ec4b312009-08-10 23:49:36 +00004224 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004225 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4226 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004227 if (isa<ParenListExpr>(CastExpr)) {
4228 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004229 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004230 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004231 }
John McCallebe54742010-01-15 18:56:44 +00004232
Richard Trieuba63ce62011-09-09 01:45:06 +00004233 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004234}
4235
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004236ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4237 SourceLocation RParenLoc, Expr *E,
4238 TypeSourceInfo *TInfo) {
4239 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4240 "Expected paren or paren list expression");
4241
4242 Expr **exprs;
4243 unsigned numExprs;
4244 Expr *subExpr;
4245 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4246 exprs = PE->getExprs();
4247 numExprs = PE->getNumExprs();
4248 } else {
4249 subExpr = cast<ParenExpr>(E)->getSubExpr();
4250 exprs = &subExpr;
4251 numExprs = 1;
4252 }
4253
4254 QualType Ty = TInfo->getType();
4255 assert(Ty->isVectorType() && "Expected vector type");
4256
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004257 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004258 const VectorType *VTy = Ty->getAs<VectorType>();
4259 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4260
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004261 // '(...)' form of vector initialization in AltiVec: the number of
4262 // initializers must be one or must match the size of the vector.
4263 // If a single value is specified in the initializer then it will be
4264 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004265 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004266 // The number of initializers must be one or must match the size of the
4267 // vector. If a single value is specified in the initializer then it will
4268 // be replicated to all the components of the vector
4269 if (numExprs == 1) {
4270 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4271 ExprResult Literal = Owned(exprs[0]);
4272 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004273 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004274 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4275 }
4276 else if (numExprs < numElems) {
4277 Diag(E->getExprLoc(),
4278 diag::err_incorrect_number_of_vector_initializers);
4279 return ExprError();
4280 }
4281 else
4282 for (unsigned i = 0, e = numExprs; i != e; ++i)
4283 initExprs.push_back(exprs[i]);
4284 }
Tanya Lattner83559382011-07-15 23:07:01 +00004285 else {
4286 // For OpenCL, when the number of initializers is a single value,
4287 // it will be replicated to all components of the vector.
4288 if (getLangOptions().OpenCL &&
4289 VTy->getVectorKind() == VectorType::GenericVector &&
4290 numExprs == 1) {
4291 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4292 ExprResult Literal = Owned(exprs[0]);
4293 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004294 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004295 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4296 }
4297
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004298 for (unsigned i = 0, e = numExprs; i != e; ++i)
4299 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004300 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004301 // FIXME: This means that pretty-printing the final AST will produce curly
4302 // braces instead of the original commas.
4303 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4304 &initExprs[0],
4305 initExprs.size(), RParenLoc);
4306 initE->setType(Ty);
4307 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4308}
4309
Nate Begeman5ec4b312009-08-10 23:49:36 +00004310/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4311/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004312ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004313Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4314 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004315 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004316 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004317
John McCalldadc5752010-08-24 06:29:42 +00004318 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004319
Nate Begeman5ec4b312009-08-10 23:49:36 +00004320 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004321 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4322 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004323
John McCallb268a282010-08-23 23:25:46 +00004324 if (Result.isInvalid()) return ExprError();
4325
4326 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004327}
4328
John McCalldadc5752010-08-24 06:29:42 +00004329ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004330 SourceLocation R,
4331 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004332 unsigned nexprs = Val.size();
4333 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004334 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4335 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004336 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004337 expr = new (Context) ParenExpr(L, R, exprs[0]);
4338 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004339 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4340 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004341 return Owned(expr);
4342}
4343
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004344/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004345/// constant and the other is not a pointer. Returns true if a diagnostic is
4346/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004347bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004348 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004349 Expr *NullExpr = LHSExpr;
4350 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004351 Expr::NullPointerConstantKind NullKind =
4352 NullExpr->isNullPointerConstant(Context,
4353 Expr::NPC_ValueDependentIsNotNull);
4354
4355 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004356 NullExpr = RHSExpr;
4357 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004358 NullKind =
4359 NullExpr->isNullPointerConstant(Context,
4360 Expr::NPC_ValueDependentIsNotNull);
4361 }
4362
4363 if (NullKind == Expr::NPCK_NotNull)
4364 return false;
4365
4366 if (NullKind == Expr::NPCK_ZeroInteger) {
4367 // In this case, check to make sure that we got here from a "NULL"
4368 // string in the source code.
4369 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004370 SourceLocation loc = NullExpr->getExprLoc();
4371 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004372 return false;
4373 }
4374
4375 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4376 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4377 << NonPointerExpr->getType() << DiagType
4378 << NonPointerExpr->getSourceRange();
4379 return true;
4380}
4381
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004382/// \brief Return false if the condition expression is valid, true otherwise.
4383static bool checkCondition(Sema &S, Expr *Cond) {
4384 QualType CondTy = Cond->getType();
4385
4386 // C99 6.5.15p2
4387 if (CondTy->isScalarType()) return false;
4388
4389 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4390 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4391 return false;
4392
4393 // Emit the proper error message.
4394 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4395 diag::err_typecheck_cond_expect_scalar :
4396 diag::err_typecheck_cond_expect_scalar_or_vector)
4397 << CondTy;
4398 return true;
4399}
4400
4401/// \brief Return false if the two expressions can be converted to a vector,
4402/// true otherwise
4403static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4404 ExprResult &RHS,
4405 QualType CondTy) {
4406 // Both operands should be of scalar type.
4407 if (!LHS.get()->getType()->isScalarType()) {
4408 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4409 << CondTy;
4410 return true;
4411 }
4412 if (!RHS.get()->getType()->isScalarType()) {
4413 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4414 << CondTy;
4415 return true;
4416 }
4417
4418 // Implicity convert these scalars to the type of the condition.
4419 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4420 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4421 return false;
4422}
4423
4424/// \brief Handle when one or both operands are void type.
4425static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4426 ExprResult &RHS) {
4427 Expr *LHSExpr = LHS.get();
4428 Expr *RHSExpr = RHS.get();
4429
4430 if (!LHSExpr->getType()->isVoidType())
4431 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4432 << RHSExpr->getSourceRange();
4433 if (!RHSExpr->getType()->isVoidType())
4434 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4435 << LHSExpr->getSourceRange();
4436 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4437 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4438 return S.Context.VoidTy;
4439}
4440
4441/// \brief Return false if the NullExpr can be promoted to PointerTy,
4442/// true otherwise.
4443static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4444 QualType PointerTy) {
4445 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4446 !NullExpr.get()->isNullPointerConstant(S.Context,
4447 Expr::NPC_ValueDependentIsNull))
4448 return true;
4449
4450 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4451 return false;
4452}
4453
4454/// \brief Checks compatibility between two pointers and return the resulting
4455/// type.
4456static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4457 ExprResult &RHS,
4458 SourceLocation Loc) {
4459 QualType LHSTy = LHS.get()->getType();
4460 QualType RHSTy = RHS.get()->getType();
4461
4462 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4463 // Two identical pointers types are always compatible.
4464 return LHSTy;
4465 }
4466
4467 QualType lhptee, rhptee;
4468
4469 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004470 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4471 lhptee = LHSBTy->getPointeeType();
4472 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004473 } else {
John McCall9320b872011-09-09 05:25:32 +00004474 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4475 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004476 }
4477
4478 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4479 rhptee.getUnqualifiedType())) {
4480 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4481 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4482 << RHS.get()->getSourceRange();
4483 // In this situation, we assume void* type. No especially good
4484 // reason, but this is what gcc does, and we do have to pick
4485 // to get a consistent AST.
4486 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4487 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4488 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4489 return incompatTy;
4490 }
4491
4492 // The pointer types are compatible.
4493 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4494 // differently qualified versions of compatible types, the result type is
4495 // a pointer to an appropriately qualified version of the *composite*
4496 // type.
4497 // FIXME: Need to calculate the composite type.
4498 // FIXME: Need to add qualifiers
4499
4500 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4501 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4502 return LHSTy;
4503}
4504
4505/// \brief Return the resulting type when the operands are both block pointers.
4506static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4507 ExprResult &LHS,
4508 ExprResult &RHS,
4509 SourceLocation Loc) {
4510 QualType LHSTy = LHS.get()->getType();
4511 QualType RHSTy = RHS.get()->getType();
4512
4513 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4514 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4515 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4516 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4517 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4518 return destType;
4519 }
4520 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4521 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4522 << RHS.get()->getSourceRange();
4523 return QualType();
4524 }
4525
4526 // We have 2 block pointer types.
4527 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4528}
4529
4530/// \brief Return the resulting type when the operands are both pointers.
4531static QualType
4532checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4533 ExprResult &RHS,
4534 SourceLocation Loc) {
4535 // get the pointer types
4536 QualType LHSTy = LHS.get()->getType();
4537 QualType RHSTy = RHS.get()->getType();
4538
4539 // get the "pointed to" types
4540 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4541 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4542
4543 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4544 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4545 // Figure out necessary qualifiers (C99 6.5.15p6)
4546 QualType destPointee
4547 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4548 QualType destType = S.Context.getPointerType(destPointee);
4549 // Add qualifiers if necessary.
4550 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4551 // Promote to void*.
4552 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4553 return destType;
4554 }
4555 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4556 QualType destPointee
4557 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4558 QualType destType = S.Context.getPointerType(destPointee);
4559 // Add qualifiers if necessary.
4560 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4561 // Promote to void*.
4562 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4563 return destType;
4564 }
4565
4566 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4567}
4568
4569/// \brief Return false if the first expression is not an integer and the second
4570/// expression is not a pointer, true otherwise.
4571static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4572 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004573 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004574 if (!PointerExpr->getType()->isPointerType() ||
4575 !Int.get()->getType()->isIntegerType())
4576 return false;
4577
Richard Trieuba63ce62011-09-09 01:45:06 +00004578 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4579 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004580
4581 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4582 << Expr1->getType() << Expr2->getType()
4583 << Expr1->getSourceRange() << Expr2->getSourceRange();
4584 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4585 CK_IntegralToPointer);
4586 return true;
4587}
4588
Richard Trieud33e46e2011-09-06 20:06:39 +00004589/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4590/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004591/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004592QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4593 ExprResult &RHS, ExprValueKind &VK,
4594 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004595 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004596
Richard Trieud33e46e2011-09-06 20:06:39 +00004597 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4598 if (!LHSResult.isUsable()) return QualType();
4599 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004600
Richard Trieud33e46e2011-09-06 20:06:39 +00004601 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4602 if (!RHSResult.isUsable()) return QualType();
4603 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004604
Sebastian Redl1a99f442009-04-16 17:51:27 +00004605 // C++ is sufficiently different to merit its own checker.
4606 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004607 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004608
4609 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004610 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004611
John Wiegley01296292011-04-08 18:41:53 +00004612 Cond = UsualUnaryConversions(Cond.take());
4613 if (Cond.isInvalid())
4614 return QualType();
4615 LHS = UsualUnaryConversions(LHS.take());
4616 if (LHS.isInvalid())
4617 return QualType();
4618 RHS = UsualUnaryConversions(RHS.take());
4619 if (RHS.isInvalid())
4620 return QualType();
4621
4622 QualType CondTy = Cond.get()->getType();
4623 QualType LHSTy = LHS.get()->getType();
4624 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004625
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004626 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004627 if (checkCondition(*this, Cond.get()))
4628 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004629
Chris Lattnere2949f42008-01-06 22:42:25 +00004630 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004631 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004632 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004633
Nate Begemanabb5a732010-09-20 22:41:17 +00004634 // OpenCL: If the condition is a vector, and both operands are scalar,
4635 // attempt to implicity convert them to the vector type to act like the
4636 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004637 if (getLangOptions().OpenCL && CondTy->isVectorType())
4638 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004639 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004640
Chris Lattnere2949f42008-01-06 22:42:25 +00004641 // If both operands have arithmetic type, do the usual arithmetic conversions
4642 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004643 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4644 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004645 if (LHS.isInvalid() || RHS.isInvalid())
4646 return QualType();
4647 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004648 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004649
Chris Lattnere2949f42008-01-06 22:42:25 +00004650 // If both operands are the same structure or union type, the result is that
4651 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004652 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4653 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004654 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004655 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004656 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004657 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004658 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004659 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004660
Chris Lattnere2949f42008-01-06 22:42:25 +00004661 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004662 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004663 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004664 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004665 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004666
Steve Naroff039ad3c2008-01-08 01:11:38 +00004667 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4668 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004669 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4670 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004671
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004672 // All objective-c pointer type analysis is done here.
4673 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4674 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004675 if (LHS.isInvalid() || RHS.isInvalid())
4676 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004677 if (!compositeType.isNull())
4678 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004679
4680
Steve Naroff05efa972009-07-01 14:36:47 +00004681 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004682 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4683 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4684 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004685
Steve Naroff05efa972009-07-01 14:36:47 +00004686 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004687 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4688 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4689 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004690
John McCalle84af4e2010-11-13 01:35:44 +00004691 // GCC compatibility: soften pointer/integer mismatch. Note that
4692 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004693 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4694 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004695 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004696 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4697 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004698 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004699
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004700 // Emit a better diagnostic if one of the expressions is a null pointer
4701 // constant and the other is not a pointer type. In this case, the user most
4702 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004703 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004704 return QualType();
4705
Chris Lattnere2949f42008-01-06 22:42:25 +00004706 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004707 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004708 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4709 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004710 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004711}
4712
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004713/// FindCompositeObjCPointerType - Helper method to find composite type of
4714/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004715QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004716 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004717 QualType LHSTy = LHS.get()->getType();
4718 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004719
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004720 // Handle things like Class and struct objc_class*. Here we case the result
4721 // to the pseudo-builtin, because that will be implicitly cast back to the
4722 // redefinition type if an attempt is made to access its fields.
4723 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004724 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004725 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004726 return LHSTy;
4727 }
4728 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004729 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004730 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004731 return RHSTy;
4732 }
4733 // And the same for struct objc_object* / id
4734 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004735 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004736 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004737 return LHSTy;
4738 }
4739 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004740 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004741 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004742 return RHSTy;
4743 }
4744 // And the same for struct objc_selector* / SEL
4745 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004746 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004747 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004748 return LHSTy;
4749 }
4750 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004751 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004752 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004753 return RHSTy;
4754 }
4755 // Check constraints for Objective-C object pointers types.
4756 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004757
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004758 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4759 // Two identical object pointer types are always compatible.
4760 return LHSTy;
4761 }
John McCall9320b872011-09-09 05:25:32 +00004762 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4763 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004764 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004765
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004766 // If both operands are interfaces and either operand can be
4767 // assigned to the other, use that type as the composite
4768 // type. This allows
4769 // xxx ? (A*) a : (B*) b
4770 // where B is a subclass of A.
4771 //
4772 // Additionally, as for assignment, if either type is 'id'
4773 // allow silent coercion. Finally, if the types are
4774 // incompatible then make sure to use 'id' as the composite
4775 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004776
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004777 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4778 // It could return the composite type.
4779 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4780 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4781 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4782 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4783 } else if ((LHSTy->isObjCQualifiedIdType() ||
4784 RHSTy->isObjCQualifiedIdType()) &&
4785 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4786 // Need to handle "id<xx>" explicitly.
4787 // GCC allows qualified id and any Objective-C type to devolve to
4788 // id. Currently localizing to here until clear this should be
4789 // part of ObjCQualifiedIdTypesAreCompatible.
4790 compositeType = Context.getObjCIdType();
4791 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4792 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004793 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004794 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4795 ;
4796 else {
4797 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4798 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004799 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004800 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004801 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4802 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004803 return incompatTy;
4804 }
4805 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004806 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4807 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004808 return compositeType;
4809 }
4810 // Check Objective-C object pointer types and 'void *'
4811 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4812 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4813 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4814 QualType destPointee
4815 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4816 QualType destType = Context.getPointerType(destPointee);
4817 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004818 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004819 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004820 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004821 return destType;
4822 }
4823 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4824 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4825 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4826 QualType destPointee
4827 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4828 QualType destType = Context.getPointerType(destPointee);
4829 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004830 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004831 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004832 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004833 return destType;
4834 }
4835 return QualType();
4836}
4837
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004838/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004839/// ParenRange in parentheses.
4840static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004841 const PartialDiagnostic &Note,
4842 SourceRange ParenRange) {
4843 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4844 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4845 EndLoc.isValid()) {
4846 Self.Diag(Loc, Note)
4847 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4848 << FixItHint::CreateInsertion(EndLoc, ")");
4849 } else {
4850 // We can't display the parentheses, so just show the bare note.
4851 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004852 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004853}
4854
4855static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4856 return Opc >= BO_Mul && Opc <= BO_Shr;
4857}
4858
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004859/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4860/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004861/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4862/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004863static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004864 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004865 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4866 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004867 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004868 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004869
4870 // Built-in binary operator.
4871 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4872 if (IsArithmeticOp(OP->getOpcode())) {
4873 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004874 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004875 return true;
4876 }
4877 }
4878
4879 // Overloaded operator.
4880 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4881 if (Call->getNumArgs() != 2)
4882 return false;
4883
4884 // Make sure this is really a binary operator that is safe to pass into
4885 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4886 OverloadedOperatorKind OO = Call->getOperator();
4887 if (OO < OO_Plus || OO > OO_Arrow)
4888 return false;
4889
4890 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4891 if (IsArithmeticOp(OpKind)) {
4892 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004893 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004894 return true;
4895 }
4896 }
4897
4898 return false;
4899}
4900
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004901static bool IsLogicOp(BinaryOperatorKind Opc) {
4902 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4903}
4904
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004905/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4906/// or is a logical expression such as (x==y) which has int type, but is
4907/// commonly interpreted as boolean.
4908static bool ExprLooksBoolean(Expr *E) {
4909 E = E->IgnoreParenImpCasts();
4910
4911 if (E->getType()->isBooleanType())
4912 return true;
4913 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4914 return IsLogicOp(OP->getOpcode());
4915 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4916 return OP->getOpcode() == UO_LNot;
4917
4918 return false;
4919}
4920
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004921/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4922/// and binary operator are mixed in a way that suggests the programmer assumed
4923/// the conditional operator has higher precedence, for example:
4924/// "int x = a + someBinaryCondition ? 1 : 2".
4925static void DiagnoseConditionalPrecedence(Sema &Self,
4926 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004927 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00004928 Expr *LHSExpr,
4929 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004930 BinaryOperatorKind CondOpcode;
4931 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004932
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004933 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004934 return;
4935 if (!ExprLooksBoolean(CondRHS))
4936 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004937
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004938 // The condition is an arithmetic binary expression, with a right-
4939 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004940
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004941 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004942 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004943 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004944
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004945 SuggestParentheses(Self, OpLoc,
4946 Self.PDiag(diag::note_precedence_conditional_silence)
4947 << BinaryOperator::getOpcodeStr(CondOpcode),
4948 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004949
4950 SuggestParentheses(Self, OpLoc,
4951 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00004952 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004953}
4954
Steve Naroff83895f72007-09-16 03:34:24 +00004955/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004956/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004957ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004958 SourceLocation ColonLoc,
4959 Expr *CondExpr, Expr *LHSExpr,
4960 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004961 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4962 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004963 OpaqueValueExpr *opaqueValue = 0;
4964 Expr *commonExpr = 0;
4965 if (LHSExpr == 0) {
4966 commonExpr = CondExpr;
4967
4968 // We usually want to apply unary conversions *before* saving, except
4969 // in the special case of a C++ l-value conditional.
4970 if (!(getLangOptions().CPlusPlus
4971 && !commonExpr->isTypeDependent()
4972 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4973 && commonExpr->isGLValue()
4974 && commonExpr->isOrdinaryOrBitFieldObject()
4975 && RHSExpr->isOrdinaryOrBitFieldObject()
4976 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004977 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4978 if (commonRes.isInvalid())
4979 return ExprError();
4980 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004981 }
4982
4983 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4984 commonExpr->getType(),
4985 commonExpr->getValueKind(),
4986 commonExpr->getObjectKind());
4987 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004988 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004989
John McCall7decc9e2010-11-18 06:31:45 +00004990 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004991 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004992 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4993 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004994 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004995 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4996 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004997 return ExprError();
4998
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004999 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5000 RHS.get());
5001
John McCallc07a0c72011-02-17 10:25:35 +00005002 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005003 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5004 LHS.take(), ColonLoc,
5005 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005006
5007 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005008 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005009 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5010 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005011}
5012
John McCallaba90822011-01-31 23:13:11 +00005013// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005014// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005015// routine is it effectively iqnores the qualifiers on the top level pointee.
5016// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5017// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005018static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005019checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5020 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5021 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005022
Steve Naroff1f4d7272007-05-11 04:00:31 +00005023 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005024 const Type *lhptee, *rhptee;
5025 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005026 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5027 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005028
John McCallaba90822011-01-31 23:13:11 +00005029 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005030
5031 // C99 6.5.16.1p1: This following citation is common to constraints
5032 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5033 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005034 Qualifiers lq;
5035
John McCall31168b02011-06-15 23:02:42 +00005036 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5037 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5038 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5039 // Ignore lifetime for further calculation.
5040 lhq.removeObjCLifetime();
5041 rhq.removeObjCLifetime();
5042 }
5043
John McCall4fff8f62011-02-01 00:10:29 +00005044 if (!lhq.compatiblyIncludes(rhq)) {
5045 // Treat address-space mismatches as fatal. TODO: address subspaces
5046 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5047 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5048
John McCall31168b02011-06-15 23:02:42 +00005049 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005050 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005051 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5052 .compatiblyIncludes(
5053 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005054 && (lhptee->isVoidType() || rhptee->isVoidType()))
5055 ; // keep old
5056
John McCall31168b02011-06-15 23:02:42 +00005057 // Treat lifetime mismatches as fatal.
5058 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5059 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5060
John McCall4fff8f62011-02-01 00:10:29 +00005061 // For GCC compatibility, other qualifier mismatches are treated
5062 // as still compatible in C.
5063 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5064 }
Steve Naroff3f597292007-05-11 22:18:03 +00005065
Mike Stump4e1f26a2009-02-19 03:04:26 +00005066 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5067 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005068 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005069 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005070 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005071 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005072
Chris Lattner0a788432008-01-03 22:56:36 +00005073 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005074 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005075 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005076 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005077
Chris Lattner0a788432008-01-03 22:56:36 +00005078 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005079 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005080 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005081
5082 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005083 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005084 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005085 }
John McCall4fff8f62011-02-01 00:10:29 +00005086
Mike Stump4e1f26a2009-02-19 03:04:26 +00005087 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005088 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005089 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5090 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005091 // Check if the pointee types are compatible ignoring the sign.
5092 // We explicitly check for char so that we catch "char" vs
5093 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005094 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005095 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005096 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005097 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005098
Chris Lattnerec3a1562009-10-17 20:33:28 +00005099 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005100 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005101 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005102 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005103
John McCall4fff8f62011-02-01 00:10:29 +00005104 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005105 // Types are compatible ignoring the sign. Qualifier incompatibility
5106 // takes priority over sign incompatibility because the sign
5107 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005108 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005109 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005110
John McCallaba90822011-01-31 23:13:11 +00005111 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005112 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005113
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005114 // If we are a multi-level pointer, it's possible that our issue is simply
5115 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5116 // the eventual target type is the same and the pointers have the same
5117 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005118 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005119 do {
John McCall4fff8f62011-02-01 00:10:29 +00005120 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5121 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005122 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005123
John McCall4fff8f62011-02-01 00:10:29 +00005124 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005125 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005126 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005127
Eli Friedman80160bd2009-03-22 23:59:44 +00005128 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005129 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005130 }
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005131 if (!S.getLangOptions().CPlusPlus &&
5132 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5133 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005134 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005135}
5136
John McCallaba90822011-01-31 23:13:11 +00005137/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005138/// block pointer types are compatible or whether a block and normal pointer
5139/// are compatible. It is more restrict than comparing two function pointer
5140// types.
John McCallaba90822011-01-31 23:13:11 +00005141static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005142checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5143 QualType RHSType) {
5144 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5145 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005146
Steve Naroff081c7422008-09-04 15:10:53 +00005147 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005148
Steve Naroff081c7422008-09-04 15:10:53 +00005149 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005150 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5151 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
John McCallaba90822011-01-31 23:13:11 +00005153 // In C++, the types have to match exactly.
5154 if (S.getLangOptions().CPlusPlus)
5155 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005156
John McCallaba90822011-01-31 23:13:11 +00005157 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005158
Steve Naroff081c7422008-09-04 15:10:53 +00005159 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005160 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5161 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005162
Richard Trieua871b972011-09-06 20:21:22 +00005163 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005164 return Sema::IncompatibleBlockPointer;
5165
Steve Naroff081c7422008-09-04 15:10:53 +00005166 return ConvTy;
5167}
5168
John McCallaba90822011-01-31 23:13:11 +00005169/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005170/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005171static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005172checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5173 QualType RHSType) {
5174 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5175 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005176
Richard Trieua871b972011-09-06 20:21:22 +00005177 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005178 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005179 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5180 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005181 return Sema::IncompatiblePointer;
5182 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005183 }
Richard Trieua871b972011-09-06 20:21:22 +00005184 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005185 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5186 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005187 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005188 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005189 }
Richard Trieua871b972011-09-06 20:21:22 +00005190 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5191 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005192
John McCallaba90822011-01-31 23:13:11 +00005193 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5194 return Sema::CompatiblePointerDiscardsQualifiers;
5195
Richard Trieua871b972011-09-06 20:21:22 +00005196 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005197 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005198 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005199 return Sema::IncompatibleObjCQualifiedId;
5200 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005201}
5202
John McCall29600e12010-11-16 02:32:08 +00005203Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005204Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005205 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005206 // Fake up an opaque expression. We don't actually care about what
5207 // cast operations are required, so if CheckAssignmentConstraints
5208 // adds casts to this they'll be wasted, but fortunately that doesn't
5209 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005210 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5211 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005212 CastKind K = CK_Invalid;
5213
Richard Trieua871b972011-09-06 20:21:22 +00005214 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005215}
5216
Mike Stump4e1f26a2009-02-19 03:04:26 +00005217/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5218/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005219/// pointers. Here are some objectionable examples that GCC considers warnings:
5220///
5221/// int a, *pint;
5222/// short *pshort;
5223/// struct foo *pfoo;
5224///
5225/// pint = pshort; // warning: assignment from incompatible pointer type
5226/// a = pint; // warning: assignment makes integer from pointer without a cast
5227/// pint = a; // warning: assignment makes pointer from integer without a cast
5228/// pint = pfoo; // warning: assignment from incompatible pointer type
5229///
5230/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005231/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005232///
John McCall8cb679e2010-11-15 09:13:47 +00005233/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005234Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005235Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005236 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005237 QualType RHSType = RHS.get()->getType();
5238 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005239
Chris Lattnera52c2f22008-01-04 23:18:45 +00005240 // Get canonical types. We're not formatting these types, just comparing
5241 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005242 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5243 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005244
Eli Friedman0dfb8892011-10-06 23:00:33 +00005245 // We can't do assignment from/to atomics yet.
5246 if (LHSType->isAtomicType())
5247 return Incompatible;
5248
John McCalle5255932011-01-31 22:28:28 +00005249 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005250 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005251 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005252 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005253 }
5254
Douglas Gregor6b754842008-10-28 00:22:11 +00005255 // If the left-hand side is a reference type, then we are in a
5256 // (rare!) case where we've allowed the use of references in C,
5257 // e.g., as a parameter type in a built-in function. In this case,
5258 // just make sure that the type referenced is compatible with the
5259 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005260 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005261 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005262 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5263 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005264 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005265 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005266 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005267 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005268 }
John McCalle5255932011-01-31 22:28:28 +00005269
Nate Begemanbd956c42009-06-28 02:36:38 +00005270 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5271 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005272 if (LHSType->isExtVectorType()) {
5273 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005274 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005275 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005276 // CK_VectorSplat does T -> vector T, so first cast to the
5277 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005278 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5279 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005280 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005281 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005282 }
5283 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005284 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005285 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005286 }
Mike Stump11289f42009-09-09 15:08:12 +00005287
John McCalle5255932011-01-31 22:28:28 +00005288 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005289 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5290 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005291 // Allow assignments of an AltiVec vector type to an equivalent GCC
5292 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005293 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005294 Kind = CK_BitCast;
5295 return Compatible;
5296 }
5297
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005298 // If we are allowing lax vector conversions, and LHS and RHS are both
5299 // vectors, the total size only needs to be the same. This is a bitcast;
5300 // no bits are changed but the result type is different.
5301 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005302 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005303 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005304 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005305 }
Chris Lattner881a2122008-01-04 23:32:24 +00005306 }
5307 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005308 }
Eli Friedman3360d892008-05-30 18:07:22 +00005309
John McCalle5255932011-01-31 22:28:28 +00005310 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005311 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5312 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005313 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005314 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005315 }
Eli Friedman3360d892008-05-30 18:07:22 +00005316
John McCalle5255932011-01-31 22:28:28 +00005317 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005318 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005319 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005320 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005321 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005322 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005323 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005324
John McCalle5255932011-01-31 22:28:28 +00005325 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005326 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005327 Kind = CK_IntegralToPointer; // FIXME: null?
5328 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005329 }
John McCalle5255932011-01-31 22:28:28 +00005330
5331 // C pointers are not compatible with ObjC object pointers,
5332 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005333 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005334 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005335 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005336 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005337 return Compatible;
5338 }
5339
5340 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005341 if (RHSType->isObjCClassType() &&
5342 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005343 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005344 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005345 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005346 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005347
John McCalle5255932011-01-31 22:28:28 +00005348 Kind = CK_BitCast;
5349 return IncompatiblePointer;
5350 }
5351
5352 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005353 if (RHSType->getAs<BlockPointerType>()) {
5354 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005355 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005356 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005357 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005358 }
John McCalle5255932011-01-31 22:28:28 +00005359
Steve Naroff081c7422008-09-04 15:10:53 +00005360 return Incompatible;
5361 }
5362
John McCalle5255932011-01-31 22:28:28 +00005363 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005364 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005365 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005366 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005367 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005368 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005369 }
5370
5371 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005372 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005373 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005374 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005375 }
5376
John McCalle5255932011-01-31 22:28:28 +00005377 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005378 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005379 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005380 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005381 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005382
John McCalle5255932011-01-31 22:28:28 +00005383 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005384 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005385 if (RHSPT->getPointeeType()->isVoidType()) {
5386 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005387 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005388 }
John McCall8cb679e2010-11-15 09:13:47 +00005389
Chris Lattnera52c2f22008-01-04 23:18:45 +00005390 return Incompatible;
5391 }
5392
John McCalle5255932011-01-31 22:28:28 +00005393 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005394 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005395 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005396 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005397 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005398 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005399 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005400 if (getLangOptions().ObjCAutoRefCount &&
5401 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005402 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005403 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005404 return result;
John McCalle5255932011-01-31 22:28:28 +00005405 }
5406
5407 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005408 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005409 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005410 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005411 }
5412
John McCalle5255932011-01-31 22:28:28 +00005413 // In general, C pointers are not compatible with ObjC object pointers,
5414 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005415 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005416 Kind = CK_CPointerToObjCPointerCast;
5417
John McCalle5255932011-01-31 22:28:28 +00005418 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005419 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005420 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005421 }
5422
5423 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005424 if (LHSType->isObjCClassType() &&
5425 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005426 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005427 return Compatible;
5428 }
5429
Steve Naroffaccc4882009-07-20 17:56:53 +00005430 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005431 }
John McCalle5255932011-01-31 22:28:28 +00005432
5433 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005434 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005435 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005436 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005437 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005438 }
5439
Steve Naroff7cae42b2009-07-10 23:34:53 +00005440 return Incompatible;
5441 }
John McCalle5255932011-01-31 22:28:28 +00005442
5443 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005444 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005445 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005446 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005447 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005448 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005449 }
Eli Friedman3360d892008-05-30 18:07:22 +00005450
John McCalle5255932011-01-31 22:28:28 +00005451 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005452 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005453 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005454 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005455 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005456
Chris Lattnera52c2f22008-01-04 23:18:45 +00005457 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005458 }
John McCalle5255932011-01-31 22:28:28 +00005459
5460 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005461 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005462 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005463 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005464 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005465 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005466 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467
John McCalle5255932011-01-31 22:28:28 +00005468 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005469 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005470 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005471 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005472 }
5473
Steve Naroff7cae42b2009-07-10 23:34:53 +00005474 return Incompatible;
5475 }
Eli Friedman3360d892008-05-30 18:07:22 +00005476
John McCalle5255932011-01-31 22:28:28 +00005477 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005478 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5479 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005480 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005481 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005482 }
Bill Wendling216423b2007-05-30 06:30:29 +00005483 }
John McCalle5255932011-01-31 22:28:28 +00005484
Steve Naroff98cf3e92007-06-06 18:38:38 +00005485 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005486}
5487
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005488/// \brief Constructs a transparent union from an expression that is
5489/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005490static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5491 ExprResult &EResult, QualType UnionType,
5492 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005493 // Build an initializer list that designates the appropriate member
5494 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005495 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005496 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005497 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005498 SourceLocation());
5499 Initializer->setType(UnionType);
5500 Initializer->setInitializedFieldInUnion(Field);
5501
5502 // Build a compound literal constructing a value of the transparent
5503 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005504 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005505 EResult = S.Owned(
5506 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5507 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005508}
5509
5510Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005511Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005512 ExprResult &RHS) {
5513 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005514
Mike Stump11289f42009-09-09 15:08:12 +00005515 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005516 // transparent_union GCC extension.
5517 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005518 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005519 return Incompatible;
5520
5521 // The field to initialize within the transparent union.
5522 RecordDecl *UD = UT->getDecl();
5523 FieldDecl *InitField = 0;
5524 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005525 for (RecordDecl::field_iterator it = UD->field_begin(),
5526 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005527 it != itend; ++it) {
5528 if (it->getType()->isPointerType()) {
5529 // If the transparent union contains a pointer type, we allow:
5530 // 1) void pointer
5531 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005532 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005533 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005534 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005535 InitField = *it;
5536 break;
5537 }
Mike Stump11289f42009-09-09 15:08:12 +00005538
Richard Trieueb299142011-09-06 20:40:12 +00005539 if (RHS.get()->isNullPointerConstant(Context,
5540 Expr::NPC_ValueDependentIsNull)) {
5541 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5542 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005543 InitField = *it;
5544 break;
5545 }
5546 }
5547
John McCall8cb679e2010-11-15 09:13:47 +00005548 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005549 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005550 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005551 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005552 InitField = *it;
5553 break;
5554 }
5555 }
5556
5557 if (!InitField)
5558 return Incompatible;
5559
Richard Trieueb299142011-09-06 20:40:12 +00005560 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005561 return Compatible;
5562}
5563
Chris Lattner9bad62c2008-01-04 18:04:52 +00005564Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005565Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5566 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005567 if (getLangOptions().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005568 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005569 // C++ 5.17p3: If the left operand is not of class type, the
5570 // expression is implicitly converted (C++ 4) to the
5571 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005572 ExprResult Res;
5573 if (Diagnose) {
5574 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5575 AA_Assigning);
5576 } else {
5577 ImplicitConversionSequence ICS =
5578 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5579 /*SuppressUserConversions=*/false,
5580 /*AllowExplicit=*/false,
5581 /*InOverloadResolution=*/false,
5582 /*CStyle=*/false,
5583 /*AllowObjCWritebackConversion=*/false);
5584 if (ICS.isFailure())
5585 return Incompatible;
5586 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5587 ICS, AA_Assigning);
5588 }
John Wiegley01296292011-04-08 18:41:53 +00005589 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005590 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005591 Sema::AssignConvertType result = Compatible;
5592 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005593 !CheckObjCARCUnavailableWeakConversion(LHSType,
5594 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005595 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005596 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005597 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005598 }
5599
5600 // FIXME: Currently, we fall through and treat C++ classes like C
5601 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005602 // FIXME: We also fall through for atomics; not sure what should
5603 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005604 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005605
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005606 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5607 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005608 if ((LHSType->isPointerType() ||
5609 LHSType->isObjCObjectPointerType() ||
5610 LHSType->isBlockPointerType())
5611 && RHS.get()->isNullPointerConstant(Context,
5612 Expr::NPC_ValueDependentIsNull)) {
5613 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005614 return Compatible;
5615 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005616
Chris Lattnere6dcd502007-10-16 02:55:40 +00005617 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005618 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005619 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005620 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005621 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005622 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005623 if (!LHSType->isReferenceType()) {
5624 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5625 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005626 return Incompatible;
5627 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005628
John McCall8cb679e2010-11-15 09:13:47 +00005629 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005630 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005631 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005632
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005633 // C99 6.5.16.1p2: The value of the right operand is converted to the
5634 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005635 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5636 // so that we can use references in built-in functions even in C.
5637 // The getNonReferenceType() call makes sure that the resulting expression
5638 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005639 if (result != Incompatible && RHS.get()->getType() != LHSType)
5640 RHS = ImpCastExprToType(RHS.take(),
5641 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005642 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005643}
5644
Richard Trieueb299142011-09-06 20:40:12 +00005645QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5646 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005647 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005648 << LHS.get()->getType() << RHS.get()->getType()
5649 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005650 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005651}
5652
Richard Trieu859d23f2011-09-06 21:01:04 +00005653QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005654 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005655 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005656 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005657 QualType LHSType =
5658 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5659 QualType RHSType =
5660 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005661
Nate Begeman191a6b12008-07-14 18:02:46 +00005662 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005663 if (LHSType == RHSType)
5664 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005665
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005666 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005667 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5668 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5669 if (LHSType->isExtVectorType()) {
5670 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5671 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005672 }
5673
Richard Trieuba63ce62011-09-09 01:45:06 +00005674 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005675 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5676 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005677 }
5678
Eli Friedman1408bc92011-06-23 18:10:35 +00005679 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005680 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005681 // If we are allowing lax vector conversions, and LHS and RHS are both
5682 // vectors, the total size only needs to be the same. This is a
5683 // bitcast; no bits are changed but the result type is different.
5684 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005685 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5686 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005687 }
5688
Nate Begemanbd956c42009-06-28 02:36:38 +00005689 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5690 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5691 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005692 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005693 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005694 std::swap(RHS, LHS);
5695 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005696 }
Mike Stump11289f42009-09-09 15:08:12 +00005697
Nate Begeman886448d2009-06-28 19:12:57 +00005698 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005699 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005700 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005701 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5702 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005703 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005704 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005705 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005706 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5707 if (swapped) std::swap(RHS, LHS);
5708 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005709 }
5710 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005711 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5712 RHSType->isRealFloatingType()) {
5713 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005714 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005715 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005716 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005717 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5718 if (swapped) std::swap(RHS, LHS);
5719 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005720 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005721 }
5722 }
Mike Stump11289f42009-09-09 15:08:12 +00005723
Nate Begeman886448d2009-06-28 19:12:57 +00005724 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005725 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005726 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005727 << LHS.get()->getType() << RHS.get()->getType()
5728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005729 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005730}
5731
Richard Trieuf8916e12011-09-16 00:53:10 +00005732// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5733// expression. These are mainly cases where the null pointer is used as an
5734// integer instead of a pointer.
5735static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5736 SourceLocation Loc, bool IsCompare) {
5737 // The canonical way to check for a GNU null is with isNullPointerConstant,
5738 // but we use a bit of a hack here for speed; this is a relatively
5739 // hot path, and isNullPointerConstant is slow.
5740 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5741 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5742
5743 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5744
5745 // Avoid analyzing cases where the result will either be invalid (and
5746 // diagnosed as such) or entirely valid and not something to warn about.
5747 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5748 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5749 return;
5750
5751 // Comparison operations would not make sense with a null pointer no matter
5752 // what the other expression is.
5753 if (!IsCompare) {
5754 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5755 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5756 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5757 return;
5758 }
5759
5760 // The rest of the operations only make sense with a null pointer
5761 // if the other expression is a pointer.
5762 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5763 NonNullType->canDecayToPointerType())
5764 return;
5765
5766 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5767 << LHSNull /* LHS is NULL */ << NonNullType
5768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5769}
5770
Richard Trieu859d23f2011-09-06 21:01:04 +00005771QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005772 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005773 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005774 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5775
Richard Trieu859d23f2011-09-06 21:01:04 +00005776 if (LHS.get()->getType()->isVectorType() ||
5777 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005778 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005779
Richard Trieuba63ce62011-09-09 01:45:06 +00005780 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005782 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005783
Richard Trieu859d23f2011-09-06 21:01:04 +00005784 if (!LHS.get()->getType()->isArithmeticType() ||
5785 !RHS.get()->getType()->isArithmeticType())
5786 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005787
Chris Lattnerfaa54172010-01-12 21:23:57 +00005788 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005789 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005790 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005791 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005792 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5793 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005794
Chris Lattnerfaa54172010-01-12 21:23:57 +00005795 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005796}
5797
Chris Lattnerfaa54172010-01-12 21:23:57 +00005798QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005799 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005800 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5801
Richard Trieu859d23f2011-09-06 21:01:04 +00005802 if (LHS.get()->getType()->isVectorType() ||
5803 RHS.get()->getType()->isVectorType()) {
5804 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5805 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005806 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005807 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005808 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005809
Richard Trieuba63ce62011-09-09 01:45:06 +00005810 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005811 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005812 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005813
Richard Trieu859d23f2011-09-06 21:01:04 +00005814 if (!LHS.get()->getType()->isIntegerType() ||
5815 !RHS.get()->getType()->isIntegerType())
5816 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005817
Chris Lattnerfaa54172010-01-12 21:23:57 +00005818 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005819 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005820 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005821 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5822 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005823
Chris Lattnerfaa54172010-01-12 21:23:57 +00005824 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005825}
5826
Chandler Carruthc9332212011-06-27 08:02:19 +00005827/// \brief Diagnose invalid arithmetic on two void pointers.
5828static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005829 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005830 S.Diag(Loc, S.getLangOptions().CPlusPlus
5831 ? diag::err_typecheck_pointer_arith_void_type
5832 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005833 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5834 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005835}
5836
5837/// \brief Diagnose invalid arithmetic on a void pointer.
5838static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5839 Expr *Pointer) {
5840 S.Diag(Loc, S.getLangOptions().CPlusPlus
5841 ? diag::err_typecheck_pointer_arith_void_type
5842 : diag::ext_gnu_void_ptr)
5843 << 0 /* one pointer */ << Pointer->getSourceRange();
5844}
5845
5846/// \brief Diagnose invalid arithmetic on two function pointers.
5847static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5848 Expr *LHS, Expr *RHS) {
5849 assert(LHS->getType()->isAnyPointerType());
5850 assert(RHS->getType()->isAnyPointerType());
5851 S.Diag(Loc, S.getLangOptions().CPlusPlus
5852 ? diag::err_typecheck_pointer_arith_function_type
5853 : diag::ext_gnu_ptr_func_arith)
5854 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5855 // We only show the second type if it differs from the first.
5856 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5857 RHS->getType())
5858 << RHS->getType()->getPointeeType()
5859 << LHS->getSourceRange() << RHS->getSourceRange();
5860}
5861
5862/// \brief Diagnose invalid arithmetic on a function pointer.
5863static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5864 Expr *Pointer) {
5865 assert(Pointer->getType()->isAnyPointerType());
5866 S.Diag(Loc, S.getLangOptions().CPlusPlus
5867 ? diag::err_typecheck_pointer_arith_function_type
5868 : diag::ext_gnu_ptr_func_arith)
5869 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5870 << 0 /* one pointer, so only one type */
5871 << Pointer->getSourceRange();
5872}
5873
Richard Trieu993f3ab2011-09-12 18:08:02 +00005874/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005875///
5876/// \returns True if pointer has incomplete type
5877static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5878 Expr *Operand) {
5879 if ((Operand->getType()->isPointerType() &&
5880 !Operand->getType()->isDependentType()) ||
5881 Operand->getType()->isObjCObjectPointerType()) {
5882 QualType PointeeTy = Operand->getType()->getPointeeType();
5883 if (S.RequireCompleteType(
5884 Loc, PointeeTy,
5885 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5886 << PointeeTy << Operand->getSourceRange()))
5887 return true;
5888 }
5889 return false;
5890}
5891
Chandler Carruthc9332212011-06-27 08:02:19 +00005892/// \brief Check the validity of an arithmetic pointer operand.
5893///
5894/// If the operand has pointer type, this code will check for pointer types
5895/// which are invalid in arithmetic operations. These will be diagnosed
5896/// appropriately, including whether or not the use is supported as an
5897/// extension.
5898///
5899/// \returns True when the operand is valid to use (even if as an extension).
5900static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5901 Expr *Operand) {
5902 if (!Operand->getType()->isAnyPointerType()) return true;
5903
5904 QualType PointeeTy = Operand->getType()->getPointeeType();
5905 if (PointeeTy->isVoidType()) {
5906 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5907 return !S.getLangOptions().CPlusPlus;
5908 }
5909 if (PointeeTy->isFunctionType()) {
5910 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5911 return !S.getLangOptions().CPlusPlus;
5912 }
5913
Richard Trieuaba22802011-09-02 02:15:37 +00005914 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005915
5916 return true;
5917}
5918
5919/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5920/// operands.
5921///
5922/// This routine will diagnose any invalid arithmetic on pointer operands much
5923/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5924/// for emitting a single diagnostic even for operations where both LHS and RHS
5925/// are (potentially problematic) pointers.
5926///
5927/// \returns True when the operand is valid to use (even if as an extension).
5928static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005929 Expr *LHSExpr, Expr *RHSExpr) {
5930 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5931 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005932 if (!isLHSPointer && !isRHSPointer) return true;
5933
5934 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00005935 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5936 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005937
5938 // Check for arithmetic on pointers to incomplete types.
5939 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5940 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5941 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005942 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
5943 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
5944 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005945
5946 return !S.getLangOptions().CPlusPlus;
5947 }
5948
5949 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5950 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5951 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005952 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
5953 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
5954 RHSExpr);
5955 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005956
5957 return !S.getLangOptions().CPlusPlus;
5958 }
5959
Richard Trieu4ae7e972011-09-06 21:13:51 +00005960 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
5961 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00005962
Chandler Carruthc9332212011-06-27 08:02:19 +00005963 return true;
5964}
5965
Richard Trieub10c6312011-09-01 22:53:23 +00005966/// \brief Check bad cases where we step over interface counts.
5967static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5968 SourceLocation OpLoc,
5969 Expr *Op) {
5970 assert(Op->getType()->isAnyPointerType());
5971 QualType PointeeTy = Op->getType()->getPointeeType();
5972 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5973 return true;
5974
5975 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5976 << PointeeTy << Op->getSourceRange();
5977 return false;
5978}
5979
Richard Trieu993f3ab2011-09-12 18:08:02 +00005980/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00005981static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005982 Expr *LHSExpr, Expr *RHSExpr) {
5983 assert(LHSExpr->getType()->isAnyPointerType());
5984 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00005985 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005986 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
5987 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00005988}
5989
Chris Lattnerfaa54172010-01-12 21:23:57 +00005990QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00005991 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005992 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5993
Richard Trieu4ae7e972011-09-06 21:13:51 +00005994 if (LHS.get()->getType()->isVectorType() ||
5995 RHS.get()->getType()->isVectorType()) {
5996 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005997 if (CompLHSTy) *CompLHSTy = compType;
5998 return compType;
5999 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006000
Richard Trieu4ae7e972011-09-06 21:13:51 +00006001 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6002 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006003 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006004
Steve Naroffe4718892007-04-27 18:30:00 +00006005 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006006 if (LHS.get()->getType()->isArithmeticType() &&
6007 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006008 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006009 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006010 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006011
Eli Friedman8e122982008-05-18 18:08:51 +00006012 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006013 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006014 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006015 std::swap(PExp, IExp);
6016
Richard Trieub420bca2011-09-12 18:37:54 +00006017 if (!PExp->getType()->isAnyPointerType())
6018 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006019
Richard Trieub420bca2011-09-12 18:37:54 +00006020 if (!IExp->getType()->isIntegerType())
6021 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006022
Richard Trieub420bca2011-09-12 18:37:54 +00006023 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6024 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006025
Richard Trieub420bca2011-09-12 18:37:54 +00006026 // Diagnose bad cases where we step over interface counts.
6027 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6028 return QualType();
6029
6030 // Check array bounds for pointer arithemtic
6031 CheckArrayAccess(PExp, IExp);
6032
6033 if (CompLHSTy) {
6034 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6035 if (LHSTy.isNull()) {
6036 LHSTy = LHS.get()->getType();
6037 if (LHSTy->isPromotableIntegerType())
6038 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006039 }
Richard Trieub420bca2011-09-12 18:37:54 +00006040 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006041 }
6042
Richard Trieub420bca2011-09-12 18:37:54 +00006043 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006044}
6045
Chris Lattner2a3569b2008-04-07 05:30:13 +00006046// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006047QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006048 SourceLocation Loc,
6049 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006050 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6051
Richard Trieu4ae7e972011-09-06 21:13:51 +00006052 if (LHS.get()->getType()->isVectorType() ||
6053 RHS.get()->getType()->isVectorType()) {
6054 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006055 if (CompLHSTy) *CompLHSTy = compType;
6056 return compType;
6057 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006058
Richard Trieu4ae7e972011-09-06 21:13:51 +00006059 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6060 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006061 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006062
Chris Lattner4d62f422007-12-09 21:53:25 +00006063 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006064
Chris Lattner4d62f422007-12-09 21:53:25 +00006065 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006066 if (LHS.get()->getType()->isArithmeticType() &&
6067 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006068 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006069 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006070 }
Mike Stump11289f42009-09-09 15:08:12 +00006071
Chris Lattner4d62f422007-12-09 21:53:25 +00006072 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006073 if (LHS.get()->getType()->isAnyPointerType()) {
6074 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006075
Chris Lattner12bdebb2009-04-24 23:50:08 +00006076 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006077 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006078 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006079
Chris Lattner4d62f422007-12-09 21:53:25 +00006080 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006081 if (RHS.get()->getType()->isIntegerType()) {
6082 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006083 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006084
Richard Trieu4ae7e972011-09-06 21:13:51 +00006085 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006086 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6087 OK_Ordinary, IExpr->getExprLoc());
6088 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006089 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006090
Richard Trieu4ae7e972011-09-06 21:13:51 +00006091 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6092 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006093 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006094
Chris Lattner4d62f422007-12-09 21:53:25 +00006095 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006096 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006097 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006098 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006099
Eli Friedman168fe152009-05-16 13:54:38 +00006100 if (getLangOptions().CPlusPlus) {
6101 // Pointee types must be the same: C++ [expr.add]
6102 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006103 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006104 }
6105 } else {
6106 // Pointee types must be compatible C99 6.5.6p3
6107 if (!Context.typesAreCompatible(
6108 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6109 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006110 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006111 return QualType();
6112 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006113 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006114
Chandler Carruthc9332212011-06-27 08:02:19 +00006115 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006116 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006117 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006118
Richard Trieu4ae7e972011-09-06 21:13:51 +00006119 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006120 return Context.getPointerDiffType();
6121 }
6122 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006123
Richard Trieu4ae7e972011-09-06 21:13:51 +00006124 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006125}
6126
Douglas Gregor0bf31402010-10-08 23:50:27 +00006127static bool isScopedEnumerationType(QualType T) {
6128 if (const EnumType *ET = dyn_cast<EnumType>(T))
6129 return ET->getDecl()->isScoped();
6130 return false;
6131}
6132
Richard Trieue4a19fb2011-09-06 21:21:28 +00006133static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006134 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006135 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006136 llvm::APSInt Right;
6137 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006138 if (RHS.get()->isValueDependent() ||
6139 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006140 return;
6141
6142 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006143 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006144 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006145 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006146 return;
6147 }
6148 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006149 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006150 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006151 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006152 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006153 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006154 return;
6155 }
6156 if (Opc != BO_Shl)
6157 return;
6158
6159 // When left shifting an ICE which is signed, we can check for overflow which
6160 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6161 // integers have defined behavior modulo one more than the maximum value
6162 // representable in the result type, so never warn for those.
6163 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006164 if (LHS.get()->isValueDependent() ||
6165 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6166 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006167 return;
6168 llvm::APInt ResultBits =
6169 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6170 if (LeftBits.uge(ResultBits))
6171 return;
6172 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6173 Result = Result.shl(Right);
6174
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006175 // Print the bit representation of the signed integer as an unsigned
6176 // hexadecimal number.
6177 llvm::SmallString<40> HexResult;
6178 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6179
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006180 // If we are only missing a sign bit, this is less likely to result in actual
6181 // bugs -- if the result is cast back to an unsigned type, it will have the
6182 // expected value. Thus we place this behind a different warning that can be
6183 // turned off separately if needed.
6184 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006185 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006186 << HexResult.str() << LHSType
6187 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006188 return;
6189 }
6190
6191 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006192 << HexResult.str() << Result.getMinSignedBits() << LHSType
6193 << Left.getBitWidth() << LHS.get()->getSourceRange()
6194 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006195}
6196
Chris Lattner2a3569b2008-04-07 05:30:13 +00006197// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006198QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006199 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006200 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006201 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6202
Chris Lattner5c11c412007-12-12 05:47:28 +00006203 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006204 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6205 !RHS.get()->getType()->hasIntegerRepresentation())
6206 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006207
Douglas Gregor0bf31402010-10-08 23:50:27 +00006208 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6209 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006210 if (isScopedEnumerationType(LHS.get()->getType()) ||
6211 isScopedEnumerationType(RHS.get()->getType())) {
6212 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006213 }
6214
Nate Begemane46ee9a2009-10-25 02:26:48 +00006215 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006216 if (LHS.get()->getType()->isVectorType() ||
6217 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006218 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006219
Chris Lattner5c11c412007-12-12 05:47:28 +00006220 // Shifts don't perform usual arithmetic conversions, they just do integer
6221 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006222
John McCall57cdd882010-12-16 19:28:59 +00006223 // For the LHS, do usual unary conversions, but then reset them away
6224 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006225 ExprResult OldLHS = LHS;
6226 LHS = UsualUnaryConversions(LHS.take());
6227 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006228 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006229 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006230 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006231
6232 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006233 RHS = UsualUnaryConversions(RHS.take());
6234 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006235 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006236
Ryan Flynnf53fab82009-08-07 16:20:20 +00006237 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006238 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006239
Chris Lattner5c11c412007-12-12 05:47:28 +00006240 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006241 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006242}
6243
Chandler Carruth17773fc2010-07-10 12:30:03 +00006244static bool IsWithinTemplateSpecialization(Decl *D) {
6245 if (DeclContext *DC = D->getDeclContext()) {
6246 if (isa<ClassTemplateSpecializationDecl>(DC))
6247 return true;
6248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6249 return FD->isFunctionTemplateSpecialization();
6250 }
6251 return false;
6252}
6253
Richard Trieueea56f72011-09-02 03:48:46 +00006254/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006255static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6256 ExprResult &RHS) {
6257 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6258 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006259
6260 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6261 if (!LHSEnumType)
6262 return;
6263 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6264 if (!RHSEnumType)
6265 return;
6266
6267 // Ignore anonymous enums.
6268 if (!LHSEnumType->getDecl()->getIdentifier())
6269 return;
6270 if (!RHSEnumType->getDecl()->getIdentifier())
6271 return;
6272
6273 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6274 return;
6275
6276 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6277 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006279}
6280
Richard Trieudd82a5c2011-09-02 02:55:45 +00006281/// \brief Diagnose bad pointer comparisons.
6282static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006283 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006284 bool IsError) {
6285 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006286 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006287 << LHS.get()->getType() << RHS.get()->getType()
6288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006289}
6290
6291/// \brief Returns false if the pointers are converted to a composite type,
6292/// true otherwise.
6293static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006294 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006295 // C++ [expr.rel]p2:
6296 // [...] Pointer conversions (4.10) and qualification
6297 // conversions (4.4) are performed on pointer operands (or on
6298 // a pointer operand and a null pointer constant) to bring
6299 // them to their composite pointer type. [...]
6300 //
6301 // C++ [expr.eq]p1 uses the same notion for (in)equality
6302 // comparisons of pointers.
6303
6304 // C++ [expr.eq]p2:
6305 // In addition, pointers to members can be compared, or a pointer to
6306 // member and a null pointer constant. Pointer to member conversions
6307 // (4.11) and qualification conversions (4.4) are performed to bring
6308 // them to a common type. If one operand is a null pointer constant,
6309 // the common type is the type of the other operand. Otherwise, the
6310 // common type is a pointer to member type similar (4.4) to the type
6311 // of one of the operands, with a cv-qualification signature (4.4)
6312 // that is the union of the cv-qualification signatures of the operand
6313 // types.
6314
Richard Trieu1762d7c2011-09-06 21:27:33 +00006315 QualType LHSType = LHS.get()->getType();
6316 QualType RHSType = RHS.get()->getType();
6317 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6318 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006319
6320 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006321 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006322 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006323 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006324 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006325 return true;
6326 }
6327
6328 if (NonStandardCompositeType)
6329 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006330 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6331 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006332
Richard Trieu1762d7c2011-09-06 21:27:33 +00006333 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6334 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006335 return false;
6336}
6337
6338static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006339 ExprResult &LHS,
6340 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006341 bool IsError) {
6342 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6343 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006344 << LHS.get()->getType() << RHS.get()->getType()
6345 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006346}
6347
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006348// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006349QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006350 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006351 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006352 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6353
John McCalle3027922010-08-25 11:45:40 +00006354 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006355
Chris Lattner9a152e22009-12-05 05:40:13 +00006356 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006357 if (LHS.get()->getType()->isVectorType() ||
6358 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006359 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006360
Richard Trieub80728f2011-09-06 21:43:51 +00006361 QualType LHSType = LHS.get()->getType();
6362 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006363
Richard Trieub80728f2011-09-06 21:43:51 +00006364 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6365 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006366
Richard Trieub80728f2011-09-06 21:43:51 +00006367 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006368
Richard Trieub80728f2011-09-06 21:43:51 +00006369 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006370 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006371 !LHS.get()->getLocStart().isMacroID() &&
6372 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006373 // For non-floating point types, check for self-comparisons of the form
6374 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6375 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006376 //
6377 // NOTE: Don't warn about comparison expressions resulting from macro
6378 // expansion. Also don't warn about comparisons which are only self
6379 // comparisons within a template specialization. The warnings should catch
6380 // obvious cases in the definition of the template anyways. The idea is to
6381 // warn when the typed comparison operator will always evaluate to the same
6382 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006383 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006384 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006385 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006386 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006387 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006388 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006389 << (Opc == BO_EQ
6390 || Opc == BO_LE
6391 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006392 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006393 !DRL->getDecl()->getType()->isReferenceType() &&
6394 !DRR->getDecl()->getType()->isReferenceType()) {
6395 // what is it always going to eval to?
6396 char always_evals_to;
6397 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006398 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006399 always_evals_to = 0; // false
6400 break;
John McCalle3027922010-08-25 11:45:40 +00006401 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006402 always_evals_to = 1; // true
6403 break;
6404 default:
6405 // best we can say is 'a constant'
6406 always_evals_to = 2; // e.g. array1 <= array2
6407 break;
6408 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006409 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006410 << 1 // array
6411 << always_evals_to);
6412 }
6413 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006414 }
Mike Stump11289f42009-09-09 15:08:12 +00006415
Chris Lattner222b8bd2009-03-08 19:39:53 +00006416 if (isa<CastExpr>(LHSStripped))
6417 LHSStripped = LHSStripped->IgnoreParenCasts();
6418 if (isa<CastExpr>(RHSStripped))
6419 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006420
Chris Lattner222b8bd2009-03-08 19:39:53 +00006421 // Warn about comparisons against a string constant (unless the other
6422 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006423 Expr *literalString = 0;
6424 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006425 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006426 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006427 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006428 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006429 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006430 } else if ((isa<StringLiteral>(RHSStripped) ||
6431 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006432 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006433 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006434 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006435 literalStringStripped = RHSStripped;
6436 }
6437
6438 if (literalString) {
6439 std::string resultComparison;
6440 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006441 case BO_LT: resultComparison = ") < 0"; break;
6442 case BO_GT: resultComparison = ") > 0"; break;
6443 case BO_LE: resultComparison = ") <= 0"; break;
6444 case BO_GE: resultComparison = ") >= 0"; break;
6445 case BO_EQ: resultComparison = ") == 0"; break;
6446 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006447 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006448 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006449
Ted Kremenek3427fac2011-02-23 01:52:04 +00006450 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006451 PDiag(diag::warn_stringcompare)
6452 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006453 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006454 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006455 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006456
Douglas Gregorec170db2010-06-08 19:50:34 +00006457 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006458 if (LHS.get()->getType()->isArithmeticType() &&
6459 RHS.get()->getType()->isArithmeticType()) {
6460 UsualArithmeticConversions(LHS, RHS);
6461 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006462 return QualType();
6463 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006464 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006465 LHS = UsualUnaryConversions(LHS.take());
6466 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006467 return QualType();
6468
Richard Trieub80728f2011-09-06 21:43:51 +00006469 RHS = UsualUnaryConversions(RHS.take());
6470 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006471 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006472 }
6473
Richard Trieub80728f2011-09-06 21:43:51 +00006474 LHSType = LHS.get()->getType();
6475 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006476
Douglas Gregorca63811b2008-11-19 03:25:36 +00006477 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006478 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006479
Richard Trieuba63ce62011-09-09 01:45:06 +00006480 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006481 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006482 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006483 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006484 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006485 if (LHSType->hasFloatingRepresentation())
6486 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006487
Richard Trieub80728f2011-09-06 21:43:51 +00006488 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006489 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006490 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Richard Trieub80728f2011-09-06 21:43:51 +00006492 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006493 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006494 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006495 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006496
Douglas Gregorf267edd2010-06-15 21:38:40 +00006497 // All of the following pointer-related warnings are GCC extensions, except
6498 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006499 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006500 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006501 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006502 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006503 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006504
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006505 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006506 if (LCanPointeeTy == RCanPointeeTy)
6507 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006508 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006509 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6510 // Valid unless comparison between non-null pointer and function pointer
6511 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006512 // In a SFINAE context, we treat this as a hard error to maintain
6513 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006514 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6515 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006516 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006517 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006518
6519 if (isSFINAEContext())
6520 return QualType();
6521
Richard Trieub80728f2011-09-06 21:43:51 +00006522 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006523 return ResultTy;
6524 }
6525 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006526
Richard Trieub80728f2011-09-06 21:43:51 +00006527 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006528 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006529 else
6530 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006531 }
Eli Friedman16c209612009-08-23 00:27:47 +00006532 // C99 6.5.9p2 and C99 6.5.8p2
6533 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6534 RCanPointeeTy.getUnqualifiedType())) {
6535 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006536 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006537 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006538 << LHSType << RHSType << LHS.get()->getSourceRange()
6539 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006540 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006541 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006542 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6543 // Valid unless comparison between non-null pointer and function pointer
6544 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006545 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006546 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006547 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006548 } else {
6549 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006550 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006551 }
John McCall7684dde2011-03-11 04:25:25 +00006552 if (LCanPointeeTy != RCanPointeeTy) {
6553 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006554 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006555 else
Richard Trieub80728f2011-09-06 21:43:51 +00006556 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006557 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006558 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006559 }
Mike Stump11289f42009-09-09 15:08:12 +00006560
Sebastian Redl576fd422009-05-10 18:38:11 +00006561 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006562 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006563 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006564 return ResultTy;
6565
Mike Stump11289f42009-09-09 15:08:12 +00006566 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006567 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006568 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006569 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006570 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006571 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6572 RHS = ImpCastExprToType(RHS.take(), LHSType,
6573 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006574 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006575 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006576 return ResultTy;
6577 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006578 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006579 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006580 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006581 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6582 LHS = ImpCastExprToType(LHS.take(), RHSType,
6583 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006584 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006585 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006586 return ResultTy;
6587 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006588
6589 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006590 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006591 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6592 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006593 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006594 else
6595 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006596 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006597
6598 // Handle scoped enumeration types specifically, since they don't promote
6599 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006600 if (LHS.get()->getType()->isEnumeralType() &&
6601 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6602 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006603 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006604 }
Mike Stump11289f42009-09-09 15:08:12 +00006605
Steve Naroff081c7422008-09-04 15:10:53 +00006606 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006607 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006608 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006609 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6610 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006611
Steve Naroff081c7422008-09-04 15:10:53 +00006612 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006613 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006614 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006615 << LHSType << RHSType << LHS.get()->getSourceRange()
6616 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006617 }
Richard Trieub80728f2011-09-06 21:43:51 +00006618 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006619 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006620 }
John Wiegley01296292011-04-08 18:41:53 +00006621
Steve Naroffe18f94c2008-09-28 01:11:11 +00006622 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006623 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006624 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6625 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006626 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006627 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006628 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006629 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006630 ->getPointeeType()->isVoidType())))
6631 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006632 << LHSType << RHSType << LHS.get()->getSourceRange()
6633 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006634 }
John McCall7684dde2011-03-11 04:25:25 +00006635 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006636 LHS = ImpCastExprToType(LHS.take(), RHSType,
6637 RHSType->isPointerType() ? CK_BitCast
6638 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006639 else
John McCall9320b872011-09-09 05:25:32 +00006640 RHS = ImpCastExprToType(RHS.take(), LHSType,
6641 LHSType->isPointerType() ? CK_BitCast
6642 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006643 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006644 }
Steve Naroff081c7422008-09-04 15:10:53 +00006645
Richard Trieub80728f2011-09-06 21:43:51 +00006646 if (LHSType->isObjCObjectPointerType() ||
6647 RHSType->isObjCObjectPointerType()) {
6648 const PointerType *LPT = LHSType->getAs<PointerType>();
6649 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006650 if (LPT || RPT) {
6651 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6652 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006653
Steve Naroff753567f2008-11-17 19:49:16 +00006654 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006655 !Context.typesAreCompatible(LHSType, RHSType)) {
6656 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006657 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006658 }
John McCall7684dde2011-03-11 04:25:25 +00006659 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006660 LHS = ImpCastExprToType(LHS.take(), RHSType,
6661 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006662 else
John McCall9320b872011-09-09 05:25:32 +00006663 RHS = ImpCastExprToType(RHS.take(), LHSType,
6664 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006665 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006666 }
Richard Trieub80728f2011-09-06 21:43:51 +00006667 if (LHSType->isObjCObjectPointerType() &&
6668 RHSType->isObjCObjectPointerType()) {
6669 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6670 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006671 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006672 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006673 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006674 else
Richard Trieub80728f2011-09-06 21:43:51 +00006675 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006676 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006677 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006678 }
Richard Trieub80728f2011-09-06 21:43:51 +00006679 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6680 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006681 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006682 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006683 if ((LHSIsNull && LHSType->isIntegerType()) ||
6684 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006685 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006686 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006687 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006688 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006689 else if (getLangOptions().CPlusPlus) {
6690 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6691 isError = true;
6692 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006693 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006694
Chris Lattnerd99bd522009-08-23 00:03:44 +00006695 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006696 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006697 << LHSType << RHSType << LHS.get()->getSourceRange()
6698 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006699 if (isError)
6700 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006701 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006702
Richard Trieub80728f2011-09-06 21:43:51 +00006703 if (LHSType->isIntegerType())
6704 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006705 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006706 else
Richard Trieub80728f2011-09-06 21:43:51 +00006707 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006708 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006709 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006710 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006711
Steve Naroff4b191572008-09-04 16:56:14 +00006712 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006713 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006714 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6715 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006716 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006717 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006718 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006719 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6720 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006721 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006722 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006723
Richard Trieub80728f2011-09-06 21:43:51 +00006724 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006725}
6726
Nate Begeman191a6b12008-07-14 18:02:46 +00006727/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006728/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006729/// like a scalar comparison, a vector comparison produces a vector of integer
6730/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006731QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006732 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006733 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006734 // Check to make sure we're operating on vectors of the same type and width,
6735 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006736 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006737 if (vType.isNull())
6738 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006739
Richard Trieubcce2f72011-09-07 01:19:57 +00006740 QualType LHSType = LHS.get()->getType();
6741 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006742
Anton Yartsev530deb92011-03-27 15:36:07 +00006743 // If AltiVec, the comparison results in a numeric type, i.e.
6744 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006745 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006746 return Context.getLogicalOperationType();
6747
Nate Begeman191a6b12008-07-14 18:02:46 +00006748 // For non-floating point types, check for self-comparisons of the form
6749 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6750 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006751 if (!LHSType->hasFloatingRepresentation()) {
6752 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6753 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006754 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006755 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006756 PDiag(diag::warn_comparison_always)
6757 << 0 // self-
6758 << 2 // "a constant"
6759 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006760 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006761
Nate Begeman191a6b12008-07-14 18:02:46 +00006762 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006763 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006764 assert (RHSType->hasFloatingRepresentation());
6765 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006766 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006767
Tanya Lattner49b38412011-10-17 21:00:38 +00006768 // Return a signed type that is of identical size and number of elements.
6769 // For floating point vectors, return an integer type of identical size
6770 // and number of elements.
Richard Trieubcce2f72011-09-07 01:19:57 +00006771 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006772 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Tanya Lattner49b38412011-10-17 21:00:38 +00006773 if (TypeSize == Context.getTypeSize(Context.CharTy))
6774 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6775 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6776 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6777 else if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006778 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Tanya Lattner49b38412011-10-17 21:00:38 +00006779 else if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006780 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006781 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006782 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006783 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6784}
6785
Steve Naroff218bc2b2007-05-04 21:54:46 +00006786inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006787 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006788 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6789
Richard Trieubcce2f72011-09-07 01:19:57 +00006790 if (LHS.get()->getType()->isVectorType() ||
6791 RHS.get()->getType()->isVectorType()) {
6792 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6793 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006794 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006795
Richard Trieubcce2f72011-09-07 01:19:57 +00006796 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006797 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006798
Richard Trieubcce2f72011-09-07 01:19:57 +00006799 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6800 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006801 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006802 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006803 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006804 LHS = LHSResult.take();
6805 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006806
Richard Trieubcce2f72011-09-07 01:19:57 +00006807 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6808 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006809 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006810 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006811}
6812
Steve Naroff218bc2b2007-05-04 21:54:46 +00006813inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006814 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006815
6816 // Diagnose cases where the user write a logical and/or but probably meant a
6817 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6818 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006819 if (LHS.get()->getType()->isIntegerType() &&
6820 !LHS.get()->getType()->isBooleanType() &&
6821 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006822 // Don't warn in macros or template instantiations.
6823 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006824 // If the RHS can be constant folded, and if it constant folds to something
6825 // that isn't 0 or 1 (which indicate a potential logical operation that
6826 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006827 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00006828 llvm::APSInt Result;
6829 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieubcce2f72011-09-07 01:19:57 +00006830 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00006831 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006832 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006833 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006834 << (Opc == BO_LAnd ? "&&" : "||");
6835 // Suggest replacing the logical operator with the bitwise version
6836 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6837 << (Opc == BO_LAnd ? "&" : "|")
6838 << FixItHint::CreateReplacement(SourceRange(
6839 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6840 getLangOptions())),
6841 Opc == BO_LAnd ? "&" : "|");
6842 if (Opc == BO_LAnd)
6843 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6844 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6845 << FixItHint::CreateRemoval(
6846 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006847 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006848 0, getSourceManager(),
6849 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006850 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006851 }
Chris Lattner938533d2010-07-24 01:10:11 +00006852 }
Chris Lattner8406c512010-07-13 19:41:32 +00006853
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006854 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006855 LHS = UsualUnaryConversions(LHS.take());
6856 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006857 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006858
Richard Trieubcce2f72011-09-07 01:19:57 +00006859 RHS = UsualUnaryConversions(RHS.take());
6860 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006861 return QualType();
6862
Richard Trieubcce2f72011-09-07 01:19:57 +00006863 if (!LHS.get()->getType()->isScalarType() ||
6864 !RHS.get()->getType()->isScalarType())
6865 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006866
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006867 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006868 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006869
John McCall4a2429a2010-06-04 00:29:51 +00006870 // The following is safe because we only use this method for
6871 // non-overloadable operands.
6872
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006873 // C++ [expr.log.and]p1
6874 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006875 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006876 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6877 if (LHSRes.isInvalid())
6878 return InvalidOperands(Loc, LHS, RHS);
6879 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006880
Richard Trieubcce2f72011-09-07 01:19:57 +00006881 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6882 if (RHSRes.isInvalid())
6883 return InvalidOperands(Loc, LHS, RHS);
6884 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006885
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006886 // C++ [expr.log.and]p2
6887 // C++ [expr.log.or]p2
6888 // The result is a bool.
6889 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006890}
6891
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006892/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6893/// is a read-only property; return true if so. A readonly property expression
6894/// depends on various declarations and thus must be treated specially.
6895///
Mike Stump11289f42009-09-09 15:08:12 +00006896static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006897 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6898 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006899 if (PropExpr->isImplicitProperty()) return false;
6900
6901 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6902 QualType BaseType = PropExpr->isSuperReceiver() ?
6903 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006904 PropExpr->getBase()->getType();
6905
John McCallb7bd14f2010-12-02 01:19:52 +00006906 if (const ObjCObjectPointerType *OPT =
6907 BaseType->getAsObjCInterfacePointerType())
6908 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6909 if (S.isPropertyReadonly(PDecl, IFace))
6910 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006911 }
6912 return false;
6913}
6914
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006915static bool IsConstProperty(Expr *E, Sema &S) {
6916 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6917 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6918 if (PropExpr->isImplicitProperty()) return false;
6919
6920 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6921 QualType T = PDecl->getType();
6922 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006923 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006924 CanQualType CT = S.Context.getCanonicalType(T);
6925 return CT.isConstQualified();
6926 }
6927 return false;
6928}
6929
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006930static bool IsReadonlyMessage(Expr *E, Sema &S) {
6931 if (E->getStmtClass() != Expr::MemberExprClass)
6932 return false;
6933 const MemberExpr *ME = cast<MemberExpr>(E);
6934 NamedDecl *Member = ME->getMemberDecl();
6935 if (isa<FieldDecl>(Member)) {
6936 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6937 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6938 return false;
6939 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6940 }
6941 return false;
6942}
6943
Chris Lattner30bd3272008-11-18 01:22:49 +00006944/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6945/// emit an error and return true. If so, return false.
6946static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006947 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006948 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006949 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006950 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6951 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006952 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6953 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006954 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6955 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006956 if (IsLV == Expr::MLV_Valid)
6957 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006958
Chris Lattner30bd3272008-11-18 01:22:49 +00006959 unsigned Diag = 0;
6960 bool NeedType = false;
6961 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006962 case Expr::MLV_ConstQualified:
6963 Diag = diag::err_typecheck_assign_const;
6964
John McCalld4631322011-06-17 06:42:21 +00006965 // In ARC, use some specialized diagnostics for occasions where we
6966 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006967 if (S.getLangOptions().ObjCAutoRefCount) {
6968 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6969 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6970 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6971
John McCalld4631322011-06-17 06:42:21 +00006972 // Use the normal diagnostic if it's pseudo-__strong but the
6973 // user actually wrote 'const'.
6974 if (var->isARCPseudoStrong() &&
6975 (!var->getTypeSourceInfo() ||
6976 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6977 // There are two pseudo-strong cases:
6978 // - self
John McCall31168b02011-06-15 23:02:42 +00006979 ObjCMethodDecl *method = S.getCurMethodDecl();
6980 if (method && var == method->getSelfDecl())
6981 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006982
6983 // - fast enumeration variables
6984 else
John McCall31168b02011-06-15 23:02:42 +00006985 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006986
John McCall31168b02011-06-15 23:02:42 +00006987 SourceRange Assign;
6988 if (Loc != OrigLoc)
6989 Assign = SourceRange(OrigLoc, OrigLoc);
6990 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6991 // We need to preserve the AST regardless, so migration tool
6992 // can do its job.
6993 return false;
6994 }
6995 }
6996 }
6997
6998 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006999 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007000 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7001 NeedType = true;
7002 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007003 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007004 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7005 NeedType = true;
7006 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007007 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007008 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7009 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007010 case Expr::MLV_Valid:
7011 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007012 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007013 case Expr::MLV_MemberFunction:
7014 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007015 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7016 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007017 case Expr::MLV_IncompleteType:
7018 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007019 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007020 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007021 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007022 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007023 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7024 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007025 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007026 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7027 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007028 case Expr::MLV_ReadonlyProperty:
7029 Diag = diag::error_readonly_property_assignment;
7030 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007031 case Expr::MLV_NoSetterProperty:
7032 Diag = diag::error_nosetter_property_assignment;
7033 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007034 case Expr::MLV_InvalidMessageExpression:
7035 Diag = diag::error_readonly_message_assignment;
7036 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007037 case Expr::MLV_SubObjCPropertySetting:
7038 Diag = diag::error_no_subobject_property_setting;
7039 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007040 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007041
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007042 SourceRange Assign;
7043 if (Loc != OrigLoc)
7044 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007045 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007046 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007047 else
Mike Stump11289f42009-09-09 15:08:12 +00007048 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007049 return true;
7050}
7051
7052
7053
7054// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007055QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007056 SourceLocation Loc,
7057 QualType CompoundType) {
7058 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007059 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007060 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007061
Richard Trieuda4f43a62011-09-07 01:33:52 +00007062 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007063 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7064 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007065 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007066 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007067 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007068 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007069 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7070 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007071 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7072 if (LHSResult.isInvalid())
7073 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007074 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007075 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007076 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007077 if (RHS.isInvalid())
7078 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007079 // Special case of NSObject attributes on c-style pointer types.
7080 if (ConvTy == IncompatiblePointer &&
7081 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007082 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007083 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007084 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007085 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007086
John McCall7decc9e2010-11-18 06:31:45 +00007087 if (ConvTy == Compatible &&
7088 getLangOptions().ObjCNonFragileABI &&
7089 LHSType->isObjCObjectType())
7090 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7091 << LHSType;
7092
Chris Lattnerea714382008-08-21 18:04:13 +00007093 // If the RHS is a unary plus or minus, check to see if they = and + are
7094 // right next to each other. If so, the user may have typo'd "x =+ 4"
7095 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007096 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007097 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7098 RHSCheck = ICE->getSubExpr();
7099 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007100 if ((UO->getOpcode() == UO_Plus ||
7101 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007102 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007103 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007104 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007105 // And there is a space or other character before the subexpr of the
7106 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007107 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007108 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007109 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007110 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007111 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007112 }
Chris Lattnerea714382008-08-21 18:04:13 +00007113 }
John McCall31168b02011-06-15 23:02:42 +00007114
7115 if (ConvTy == Compatible) {
7116 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007117 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007118 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007119 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007120 }
Chris Lattnerea714382008-08-21 18:04:13 +00007121 } else {
7122 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007123 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007124 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007125
Chris Lattner326f7572008-11-18 01:30:42 +00007126 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007127 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007128 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007129
Richard Trieuda4f43a62011-09-07 01:33:52 +00007130 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007131
Steve Naroff98cf3e92007-06-06 18:38:38 +00007132 // C99 6.5.16p3: The type of an assignment expression is the type of the
7133 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007134 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007135 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7136 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007137 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007138 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007139 return (getLangOptions().CPlusPlus
7140 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007141}
7142
Chris Lattner326f7572008-11-18 01:30:42 +00007143// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007144static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007145 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007146 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007147
John McCall3aef3d82011-04-10 19:13:55 +00007148 LHS = S.CheckPlaceholderExpr(LHS.take());
7149 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007150 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007151 return QualType();
7152
John McCall73d36182010-10-12 07:14:40 +00007153 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7154 // operands, but not unary promotions.
7155 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007156
John McCall34376a62010-12-04 03:47:34 +00007157 // So we treat the LHS as a ignored value, and in C++ we allow the
7158 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007159 LHS = S.IgnoredValueConversions(LHS.take());
7160 if (LHS.isInvalid())
7161 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007162
7163 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007164 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7165 if (RHS.isInvalid())
7166 return QualType();
7167 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007168 S.RequireCompleteType(Loc, RHS.get()->getType(),
7169 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007170 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007171
John Wiegley01296292011-04-08 18:41:53 +00007172 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007173}
7174
Steve Naroff7a5af782007-07-13 16:58:59 +00007175/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7176/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007177static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7178 ExprValueKind &VK,
7179 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007180 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007181 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007182 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007183
Chris Lattner6b0cf142008-11-21 07:05:48 +00007184 QualType ResType = Op->getType();
7185 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007186
John McCall4bc41ae2010-11-18 19:01:18 +00007187 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007188 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007189 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007190 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007191 return QualType();
7192 }
7193 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007194 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007195 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007196 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007197 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007198 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007199 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007200 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007201
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007202 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007203 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007204 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007205 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007206 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007207 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007208 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007209 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007210 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007211 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007212 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007213 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007214 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7215 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007216 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007217 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007218 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007219 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007220 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007221 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007222 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007223 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007224 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007225 // In C++, a prefix increment is the same type as the operand. Otherwise
7226 // (in C or with postfix), the increment is the unqualified type of the
7227 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007228 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007229 VK = VK_LValue;
7230 return ResType;
7231 } else {
7232 VK = VK_RValue;
7233 return ResType.getUnqualifiedType();
7234 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007235}
7236
John Wiegley01296292011-04-08 18:41:53 +00007237ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007238 assert(E->getValueKind() == VK_LValue &&
7239 E->getObjectKind() == OK_ObjCProperty);
7240 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7241
Douglas Gregor33823722011-06-11 01:09:30 +00007242 QualType T = E->getType();
7243 QualType ReceiverType;
7244 if (PRE->isObjectReceiver())
7245 ReceiverType = PRE->getBase()->getType();
7246 else if (PRE->isSuperReceiver())
7247 ReceiverType = PRE->getSuperReceiverType();
7248 else
7249 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7250
John McCall34376a62010-12-04 03:47:34 +00007251 ExprValueKind VK = VK_RValue;
7252 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007253 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007254 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007255 T = getMessageSendResultType(ReceiverType, GetterMethod,
7256 PRE->isClassReceiver(),
7257 PRE->isSuperReceiver());
7258 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007259 }
7260 else {
7261 Diag(PRE->getLocation(), diag::err_getter_not_found)
7262 << PRE->getBase()->getType();
7263 }
John McCall34376a62010-12-04 03:47:34 +00007264 }
Fariborz Jahanian082a6a12011-10-03 17:58:21 +00007265 else {
Fariborz Jahaniane1e17cd2011-10-14 18:35:31 +00007266 // lvalue-ness of an explicit property is determined by
7267 // getter type.
Fariborz Jahanian03df2b22011-10-14 18:31:36 +00007268 QualType ResT = PRE->getGetterResultType();
Fariborz Jahaniane1e17cd2011-10-14 18:35:31 +00007269 VK = Expr::getValueKindForType(ResT);
Fariborz Jahanian082a6a12011-10-03 17:58:21 +00007270 }
7271
Douglas Gregor33823722011-06-11 01:09:30 +00007272 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007273 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007274
7275 ExprResult Result = MaybeBindToTemporary(E);
7276 if (!Result.isInvalid())
7277 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007278
7279 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007280}
7281
Richard Trieucfc491d2011-08-02 04:35:43 +00007282void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7283 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007284 assert(LHS.get()->getValueKind() == VK_LValue &&
7285 LHS.get()->getObjectKind() == OK_ObjCProperty);
7286 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007287
John McCall31168b02011-06-15 23:02:42 +00007288 bool Consumed = false;
7289
John Wiegley01296292011-04-08 18:41:53 +00007290 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007291 // If using property-dot syntax notation for assignment, and there is a
7292 // setter, RHS expression is being passed to the setter argument. So,
7293 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007294 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00007295 ObjCMethodDecl::param_const_iterator P = SetterMD->param_begin();
John McCall34376a62010-12-04 03:47:34 +00007296 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007297 Consumed = (getLangOptions().ObjCAutoRefCount &&
7298 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007299
7300 // Otherwise, if the getter returns an l-value, just call that.
7301 } else {
John Wiegley01296292011-04-08 18:41:53 +00007302 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007303 ExprValueKind VK = Expr::getValueKindForType(Result);
7304 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007305 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7306 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007307 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007308 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007309 }
Fariborz Jahanian7c386f82011-10-15 17:36:49 +00007310 } else {
John McCall31168b02011-06-15 23:02:42 +00007311 const ObjCMethodDecl *setter
7312 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7313 if (setter) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00007314 ObjCMethodDecl::param_const_iterator P = setter->param_begin();
John McCall31168b02011-06-15 23:02:42 +00007315 LHSTy = (*P)->getType();
Fariborz Jahanian7c386f82011-10-15 17:36:49 +00007316 if (getLangOptions().ObjCAutoRefCount)
7317 Consumed = (*P)->hasAttr<NSConsumedAttr>();
John McCall31168b02011-06-15 23:02:42 +00007318 }
John McCall34376a62010-12-04 03:47:34 +00007319 }
7320
John McCall31168b02011-06-15 23:02:42 +00007321 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7322 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007323 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007324 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007325 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007326 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007327 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007328 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7329 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7330 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007331 }
Fariborz Jahanian7c386f82011-10-15 17:36:49 +00007332 LHSTy = LHSTy.getNonReferenceType();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007333}
7334
7335
Anders Carlsson806700f2008-02-01 07:15:58 +00007336/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007337/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007338/// where the declaration is needed for type checking. We only need to
7339/// handle cases when the expression references a function designator
7340/// or is an lvalue. Here are some examples:
7341/// - &(x) => x
7342/// - &*****f => f for f a function designator.
7343/// - &s.xx => s
7344/// - &s.zz[1].yy -> s, if zz is an array
7345/// - *(x + 1) -> x, if x is an array
7346/// - &"123"[2] -> 0
7347/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007348static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007349 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007350 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007351 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007352 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007353 // If this is an arrow operator, the address is an offset from
7354 // the base's value, so the object the base refers to is
7355 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007356 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007357 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007358 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007359 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007360 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007361 // FIXME: This code shouldn't be necessary! We should catch the implicit
7362 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007363 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7364 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7365 if (ICE->getSubExpr()->getType()->isArrayType())
7366 return getPrimaryDecl(ICE->getSubExpr());
7367 }
7368 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007369 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007370 case Stmt::UnaryOperatorClass: {
7371 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007372
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007373 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007374 case UO_Real:
7375 case UO_Imag:
7376 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007377 return getPrimaryDecl(UO->getSubExpr());
7378 default:
7379 return 0;
7380 }
7381 }
Steve Naroff47500512007-04-19 23:00:49 +00007382 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007383 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007384 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007385 // If the result of an implicit cast is an l-value, we care about
7386 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007387 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007388 default:
7389 return 0;
7390 }
7391}
7392
Richard Trieu5f376f62011-09-07 21:46:33 +00007393namespace {
7394 enum {
7395 AO_Bit_Field = 0,
7396 AO_Vector_Element = 1,
7397 AO_Property_Expansion = 2,
7398 AO_Register_Variable = 3,
7399 AO_No_Error = 4
7400 };
7401}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007402/// \brief Diagnose invalid operand for address of operations.
7403///
7404/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007405static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7406 Expr *E, unsigned Type) {
7407 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7408}
7409
Steve Naroff47500512007-04-19 23:00:49 +00007410/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007411/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007412/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007413/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007414/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007415/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007416/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007417static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7418 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007419 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007420 return S.Context.DependentTy;
Douglas Gregor668d3622011-10-09 19:10:41 +00007421 if (OrigOp->getType() == S.Context.OverloadTy) {
7422 if (!isa<OverloadExpr>(OrigOp->IgnoreParens())) {
7423 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7424 << OrigOp->getSourceRange();
7425 return QualType();
7426 }
7427
John McCall4bc41ae2010-11-18 19:01:18 +00007428 return S.Context.OverloadTy;
Douglas Gregor668d3622011-10-09 19:10:41 +00007429 }
John McCall2979fe02011-04-12 00:42:48 +00007430 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7431 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007432 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7433 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7434 << OrigOp->getSourceRange();
7435 return QualType();
7436 }
John McCall8d08b9b2010-08-27 09:08:28 +00007437
John McCall2979fe02011-04-12 00:42:48 +00007438 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007439
John McCall8d08b9b2010-08-27 09:08:28 +00007440 // Make sure to ignore parentheses in subsequent checks
7441 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007442
John McCall4bc41ae2010-11-18 19:01:18 +00007443 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007444 // Implement C99-only parts of addressof rules.
7445 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007446 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007447 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7448 // (assuming the deref expression is valid).
7449 return uOp->getSubExpr()->getType();
7450 }
7451 // Technically, there should be a check for array subscript
7452 // expressions here, but the result of one is always an lvalue anyway.
7453 }
John McCallf3a88602011-02-03 08:15:49 +00007454 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007455 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007456 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007457
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007458 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007459 bool sfinae = S.isSFINAEContext();
7460 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7461 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007462 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007463 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007464 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007465 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007466 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007467 } else if (lval == Expr::LV_MemberFunction) {
7468 // If it's an instance method, make a member pointer.
7469 // The expression must have exactly the form &A::foo.
7470
7471 // If the underlying expression isn't a decl ref, give up.
7472 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007473 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007474 << OrigOp->getSourceRange();
7475 return QualType();
7476 }
7477 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7478 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7479
7480 // The id-expression was parenthesized.
7481 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007482 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007483 << OrigOp->getSourceRange();
7484
7485 // The method was named without a qualifier.
7486 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007487 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007488 << op->getSourceRange();
7489 }
7490
John McCall4bc41ae2010-11-18 19:01:18 +00007491 return S.Context.getMemberPointerType(op->getType(),
7492 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007493 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007494 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007495 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007496 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007497 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007498 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007499 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007500 return QualType();
7501 }
John McCall086a4642010-11-24 05:12:34 +00007502 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007503 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007504 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007505 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007506 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007507 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007508 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007509 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007510 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007511 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007512 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007513 // with the register storage-class specifier.
7514 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007515 // in C++ it is not error to take address of a register
7516 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007517 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007518 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007519 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007520 }
John McCalld14a8642009-11-21 08:51:07 +00007521 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007522 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007523 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007524 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007525 // Could be a pointer to member, though, if there is an explicit
7526 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007527 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007528 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007529 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007530 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007531 S.Diag(OpLoc,
7532 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007533 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007534 return QualType();
7535 }
Mike Stump11289f42009-09-09 15:08:12 +00007536
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007537 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7538 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007539 return S.Context.getMemberPointerType(op->getType(),
7540 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007541 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007542 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007543 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007544 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007545 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007546
Richard Trieu5f376f62011-09-07 21:46:33 +00007547 if (AddressOfError != AO_No_Error) {
7548 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7549 return QualType();
7550 }
7551
Eli Friedmance7f9002009-05-16 23:27:50 +00007552 if (lval == Expr::LV_IncompleteVoidType) {
7553 // Taking the address of a void variable is technically illegal, but we
7554 // allow it in cases which are otherwise valid.
7555 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007556 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007557 }
7558
Steve Naroff47500512007-04-19 23:00:49 +00007559 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007560 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007561 return S.Context.getObjCObjectPointerType(op->getType());
7562 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007563}
7564
Chris Lattner9156f1b2010-07-05 19:17:26 +00007565/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007566static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7567 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007568 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007569 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007570
John Wiegley01296292011-04-08 18:41:53 +00007571 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7572 if (ConvResult.isInvalid())
7573 return QualType();
7574 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007575 QualType OpTy = Op->getType();
7576 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007577
7578 if (isa<CXXReinterpretCastExpr>(Op)) {
7579 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7580 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7581 Op->getSourceRange());
7582 }
7583
Chris Lattner9156f1b2010-07-05 19:17:26 +00007584 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7585 // is an incomplete type or void. It would be possible to warn about
7586 // dereferencing a void pointer, but it's completely well-defined, and such a
7587 // warning is unlikely to catch any mistakes.
7588 if (const PointerType *PT = OpTy->getAs<PointerType>())
7589 Result = PT->getPointeeType();
7590 else if (const ObjCObjectPointerType *OPT =
7591 OpTy->getAs<ObjCObjectPointerType>())
7592 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007593 else {
John McCall3aef3d82011-04-10 19:13:55 +00007594 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007595 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007596 if (PR.take() != Op)
7597 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007598 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007599
Chris Lattner9156f1b2010-07-05 19:17:26 +00007600 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007601 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007602 << OpTy << Op->getSourceRange();
7603 return QualType();
7604 }
John McCall4bc41ae2010-11-18 19:01:18 +00007605
7606 // Dereferences are usually l-values...
7607 VK = VK_LValue;
7608
7609 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007610 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007611 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007612
7613 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007614}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007615
John McCalle3027922010-08-25 11:45:40 +00007616static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007617 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007618 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007619 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007620 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007621 case tok::periodstar: Opc = BO_PtrMemD; break;
7622 case tok::arrowstar: Opc = BO_PtrMemI; break;
7623 case tok::star: Opc = BO_Mul; break;
7624 case tok::slash: Opc = BO_Div; break;
7625 case tok::percent: Opc = BO_Rem; break;
7626 case tok::plus: Opc = BO_Add; break;
7627 case tok::minus: Opc = BO_Sub; break;
7628 case tok::lessless: Opc = BO_Shl; break;
7629 case tok::greatergreater: Opc = BO_Shr; break;
7630 case tok::lessequal: Opc = BO_LE; break;
7631 case tok::less: Opc = BO_LT; break;
7632 case tok::greaterequal: Opc = BO_GE; break;
7633 case tok::greater: Opc = BO_GT; break;
7634 case tok::exclaimequal: Opc = BO_NE; break;
7635 case tok::equalequal: Opc = BO_EQ; break;
7636 case tok::amp: Opc = BO_And; break;
7637 case tok::caret: Opc = BO_Xor; break;
7638 case tok::pipe: Opc = BO_Or; break;
7639 case tok::ampamp: Opc = BO_LAnd; break;
7640 case tok::pipepipe: Opc = BO_LOr; break;
7641 case tok::equal: Opc = BO_Assign; break;
7642 case tok::starequal: Opc = BO_MulAssign; break;
7643 case tok::slashequal: Opc = BO_DivAssign; break;
7644 case tok::percentequal: Opc = BO_RemAssign; break;
7645 case tok::plusequal: Opc = BO_AddAssign; break;
7646 case tok::minusequal: Opc = BO_SubAssign; break;
7647 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7648 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7649 case tok::ampequal: Opc = BO_AndAssign; break;
7650 case tok::caretequal: Opc = BO_XorAssign; break;
7651 case tok::pipeequal: Opc = BO_OrAssign; break;
7652 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007653 }
7654 return Opc;
7655}
7656
John McCalle3027922010-08-25 11:45:40 +00007657static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007658 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007659 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007660 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007661 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007662 case tok::plusplus: Opc = UO_PreInc; break;
7663 case tok::minusminus: Opc = UO_PreDec; break;
7664 case tok::amp: Opc = UO_AddrOf; break;
7665 case tok::star: Opc = UO_Deref; break;
7666 case tok::plus: Opc = UO_Plus; break;
7667 case tok::minus: Opc = UO_Minus; break;
7668 case tok::tilde: Opc = UO_Not; break;
7669 case tok::exclaim: Opc = UO_LNot; break;
7670 case tok::kw___real: Opc = UO_Real; break;
7671 case tok::kw___imag: Opc = UO_Imag; break;
7672 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007673 }
7674 return Opc;
7675}
7676
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007677/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7678/// This warning is only emitted for builtin assignment operations. It is also
7679/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007680static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007681 SourceLocation OpLoc) {
7682 if (!S.ActiveTemplateInstantiations.empty())
7683 return;
7684 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7685 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007686 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7687 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7688 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7689 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7690 if (!LHSDeclRef || !RHSDeclRef ||
7691 LHSDeclRef->getLocation().isMacroID() ||
7692 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007693 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007694 const ValueDecl *LHSDecl =
7695 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7696 const ValueDecl *RHSDecl =
7697 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7698 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007699 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007700 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007701 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007702 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007703 if (RefTy->getPointeeType().isVolatileQualified())
7704 return;
7705
7706 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007707 << LHSDeclRef->getType()
7708 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007709}
7710
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007711/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7712/// operator @p Opc at location @c TokLoc. This routine only supports
7713/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007714ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007715 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007716 Expr *LHSExpr, Expr *RHSExpr) {
7717 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007718 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007719 // The following two variables are used for compound assignment operators
7720 QualType CompLHSTy; // Type of LHS after promotions for computation
7721 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007722 ExprValueKind VK = VK_RValue;
7723 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007724
Douglas Gregor1beec452011-03-12 01:48:56 +00007725 // Check if a 'foo<int>' involved in a binary op, identifies a single
7726 // function unambiguously (i.e. an lvalue ala 13.4)
7727 // But since an assignment can trigger target based overload, exclude it in
7728 // our blind search. i.e:
7729 // template<class T> void f(); template<class T, class U> void f(U);
7730 // f<int> == 0; // resolve f<int> blindly
7731 // void (*p)(int); p = f<int>; // resolve f<int> using target
7732 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007733 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007734 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007735 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007736
Richard Trieu4a287fb2011-09-07 01:49:20 +00007737 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007738 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007739 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007740 }
7741
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007742 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007743 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007744 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007745 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007746 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7747 VK = LHS.get()->getValueKind();
7748 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007749 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007750 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007751 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007752 break;
John McCalle3027922010-08-25 11:45:40 +00007753 case BO_PtrMemD:
7754 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007755 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007756 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007757 break;
John McCalle3027922010-08-25 11:45:40 +00007758 case BO_Mul:
7759 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007760 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007761 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007762 break;
John McCalle3027922010-08-25 11:45:40 +00007763 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007764 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007765 break;
John McCalle3027922010-08-25 11:45:40 +00007766 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007767 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007768 break;
John McCalle3027922010-08-25 11:45:40 +00007769 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007770 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007771 break;
John McCalle3027922010-08-25 11:45:40 +00007772 case BO_Shl:
7773 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007774 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007775 break;
John McCalle3027922010-08-25 11:45:40 +00007776 case BO_LE:
7777 case BO_LT:
7778 case BO_GE:
7779 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007780 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007781 break;
John McCalle3027922010-08-25 11:45:40 +00007782 case BO_EQ:
7783 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007784 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007785 break;
John McCalle3027922010-08-25 11:45:40 +00007786 case BO_And:
7787 case BO_Xor:
7788 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007789 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007790 break;
John McCalle3027922010-08-25 11:45:40 +00007791 case BO_LAnd:
7792 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007793 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007794 break;
John McCalle3027922010-08-25 11:45:40 +00007795 case BO_MulAssign:
7796 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007797 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007798 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007799 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007800 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7801 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007802 break;
John McCalle3027922010-08-25 11:45:40 +00007803 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007804 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007805 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007806 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7807 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007808 break;
John McCalle3027922010-08-25 11:45:40 +00007809 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007810 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7811 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7812 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007813 break;
John McCalle3027922010-08-25 11:45:40 +00007814 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007815 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7816 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7817 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007818 break;
John McCalle3027922010-08-25 11:45:40 +00007819 case BO_ShlAssign:
7820 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007821 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007822 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007823 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7824 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007825 break;
John McCalle3027922010-08-25 11:45:40 +00007826 case BO_AndAssign:
7827 case BO_XorAssign:
7828 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007829 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007830 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007831 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7832 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007833 break;
John McCalle3027922010-08-25 11:45:40 +00007834 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007835 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7836 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7837 VK = RHS.get()->getValueKind();
7838 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007839 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007840 break;
7841 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007842 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007843 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007844
7845 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007846 CheckArrayAccess(LHS.get());
7847 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007848
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007849 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007850 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007851 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007852 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007853 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007854 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007855 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007856 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007857 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007858 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007859 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007860}
7861
Sebastian Redl44615072009-10-27 12:10:02 +00007862/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7863/// operators are mixed in a way that suggests that the programmer forgot that
7864/// comparison operators have higher precedence. The most typical example of
7865/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007866static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007867 SourceLocation OpLoc, Expr *LHSExpr,
7868 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007869 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007870 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7871 RHSopc = static_cast<BinOp::Opcode>(-1);
7872 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7873 LHSopc = BO->getOpcode();
7874 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7875 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007876
7877 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007878 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007879 return;
7880
7881 // Bitwise operations are sometimes used as eager logical ops.
7882 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007883 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7884 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007885 return;
7886
Richard Trieu4a287fb2011-09-07 01:49:20 +00007887 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7888 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007889 if (!isLeftComp && !isRightComp) return;
7890
Richard Trieu4a287fb2011-09-07 01:49:20 +00007891 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7892 OpLoc)
7893 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7894 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7895 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007896 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007897 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7898 RHSExpr->getLocEnd())
7899 : SourceRange(LHSExpr->getLocStart(),
7900 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007901
7902 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7903 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7904 SuggestParentheses(Self, OpLoc,
7905 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007906 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007907 SuggestParentheses(Self, OpLoc,
7908 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7909 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007910}
7911
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007912/// \brief It accepts a '&' expr that is inside a '|' one.
7913/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7914/// in parentheses.
7915static void
7916EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7917 BinaryOperator *Bop) {
7918 assert(Bop->getOpcode() == BO_And);
7919 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7920 << Bop->getSourceRange() << OpLoc;
7921 SuggestParentheses(Self, Bop->getOperatorLoc(),
7922 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7923 Bop->getSourceRange());
7924}
7925
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007926/// \brief It accepts a '&&' expr that is inside a '||' one.
7927/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7928/// in parentheses.
7929static void
7930EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007931 BinaryOperator *Bop) {
7932 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007933 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7934 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007935 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007936 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007937 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007938}
7939
7940/// \brief Returns true if the given expression can be evaluated as a constant
7941/// 'true'.
7942static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7943 bool Res;
7944 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7945}
7946
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007947/// \brief Returns true if the given expression can be evaluated as a constant
7948/// 'false'.
7949static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7950 bool Res;
7951 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7952}
7953
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007954/// \brief Look for '&&' in the left hand of a '||' expr.
7955static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007956 Expr *LHSExpr, Expr *RHSExpr) {
7957 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007958 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007959 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007960 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007961 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007962 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7963 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7964 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7965 } else if (Bop->getOpcode() == BO_LOr) {
7966 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7967 // If it's "a || b && 1 || c" we didn't warn earlier for
7968 // "a || b && 1", but warn now.
7969 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7970 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7971 }
7972 }
7973 }
7974}
7975
7976/// \brief Look for '&&' in the right hand of a '||' expr.
7977static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007978 Expr *LHSExpr, Expr *RHSExpr) {
7979 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007980 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007981 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007982 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007983 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007984 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7985 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7986 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007987 }
7988 }
7989}
7990
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007991/// \brief Look for '&' in the left or right hand of a '|' expr.
7992static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7993 Expr *OrArg) {
7994 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7995 if (Bop->getOpcode() == BO_And)
7996 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7997 }
7998}
7999
Sebastian Redl43028242009-10-26 15:24:15 +00008000/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008001/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008002static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008003 SourceLocation OpLoc, Expr *LHSExpr,
8004 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008005 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008006 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008007 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008008
8009 // Diagnose "arg1 & arg2 | arg3"
8010 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008011 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8012 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008013 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008014
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008015 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8016 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008017 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008018 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8019 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008020 }
Sebastian Redl43028242009-10-26 15:24:15 +00008021}
8022
Steve Naroff218bc2b2007-05-04 21:54:46 +00008023// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008024ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008025 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008026 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008027 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008028 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8029 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008030
Sebastian Redl43028242009-10-26 15:24:15 +00008031 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008032 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008033
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008034 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008035}
8036
John McCalldadc5752010-08-24 06:29:42 +00008037ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008038 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008039 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008040 if (getLangOptions().CPlusPlus) {
8041 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008042
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008043 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008044 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008045 } else if (Opc == BO_Assign &&
8046 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008047 UseBuiltinOperator = true;
8048 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008049 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8050 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008051 }
8052
8053 if (!UseBuiltinOperator) {
8054 // Find all of the overloaded operators visible from this
8055 // point. We perform both an operator-name lookup from the local
8056 // scope and an argument-dependent lookup based on the types of
8057 // the arguments.
8058 UnresolvedSet<16> Functions;
8059 OverloadedOperatorKind OverOp
8060 = BinaryOperator::getOverloadedOperator(Opc);
8061 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008062 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8063 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008064
8065 // Build the (potentially-overloaded, potentially-dependent)
8066 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008067 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008068 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008070
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008071 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008072 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008073}
8074
John McCalldadc5752010-08-24 06:29:42 +00008075ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008076 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008077 Expr *InputExpr) {
8078 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008079 ExprValueKind VK = VK_RValue;
8080 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008081 QualType resultType;
8082 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008083 case UO_PreInc:
8084 case UO_PreDec:
8085 case UO_PostInc:
8086 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008087 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008088 Opc == UO_PreInc ||
8089 Opc == UO_PostInc,
8090 Opc == UO_PreInc ||
8091 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008092 break;
John McCalle3027922010-08-25 11:45:40 +00008093 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008094 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008095 break;
John McCall31996342011-04-07 08:22:57 +00008096 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008097 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008098 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008099 Input = move(resolved);
8100 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8101 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008102 break;
John McCall31996342011-04-07 08:22:57 +00008103 }
John McCalle3027922010-08-25 11:45:40 +00008104 case UO_Plus:
8105 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008106 Input = UsualUnaryConversions(Input.take());
8107 if (Input.isInvalid()) return ExprError();
8108 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008109 if (resultType->isDependentType())
8110 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008111 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8112 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008113 break;
8114 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8115 resultType->isEnumeralType())
8116 break;
8117 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008118 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008119 resultType->isPointerType())
8120 break;
John McCall36226622010-10-12 02:09:17 +00008121 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008122 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008123 if (Input.isInvalid()) return ExprError();
8124 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008125 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008126
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008127 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008128 << resultType << Input.get()->getSourceRange());
8129
John McCalle3027922010-08-25 11:45:40 +00008130 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008131 Input = UsualUnaryConversions(Input.take());
8132 if (Input.isInvalid()) return ExprError();
8133 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008134 if (resultType->isDependentType())
8135 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008136 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8137 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8138 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008139 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008140 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008141 else if (resultType->hasIntegerRepresentation())
8142 break;
8143 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008144 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008145 if (Input.isInvalid()) return ExprError();
8146 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008147 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008148 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008149 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008150 }
Steve Naroff35d85152007-05-07 00:24:15 +00008151 break;
John Wiegley01296292011-04-08 18:41:53 +00008152
John McCalle3027922010-08-25 11:45:40 +00008153 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008154 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008155 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8156 if (Input.isInvalid()) return ExprError();
8157 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008158
8159 // Though we still have to promote half FP to float...
8160 if (resultType->isHalfType()) {
8161 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8162 resultType = Context.FloatTy;
8163 }
8164
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008165 if (resultType->isDependentType())
8166 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008167 if (resultType->isScalarType()) {
8168 // C99 6.5.3.3p1: ok, fallthrough;
8169 if (Context.getLangOptions().CPlusPlus) {
8170 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8171 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008172 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8173 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008174 }
John McCall36226622010-10-12 02:09:17 +00008175 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008176 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008177 if (Input.isInvalid()) return ExprError();
8178 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008179 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008180 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008181 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008182 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008183
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008184 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008185 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008186 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008187 break;
John McCalle3027922010-08-25 11:45:40 +00008188 case UO_Real:
8189 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008190 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008191 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008192 if (Input.isInvalid()) return ExprError();
8193 if (Input.get()->getValueKind() != VK_RValue &&
8194 Input.get()->getObjectKind() == OK_Ordinary)
8195 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008196 break;
John McCalle3027922010-08-25 11:45:40 +00008197 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008198 resultType = Input.get()->getType();
8199 VK = Input.get()->getValueKind();
8200 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008201 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008202 }
John Wiegley01296292011-04-08 18:41:53 +00008203 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008204 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008205
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008206 // Check for array bounds violations in the operand of the UnaryOperator,
8207 // except for the '*' and '&' operators that have to be handled specially
8208 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8209 // that are explicitly defined as valid by the standard).
8210 if (Opc != UO_AddrOf && Opc != UO_Deref)
8211 CheckArrayAccess(Input.get());
8212
John Wiegley01296292011-04-08 18:41:53 +00008213 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008214 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008215}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008216
John McCalldadc5752010-08-24 06:29:42 +00008217ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008218 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008219 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008220 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008221 // Find all of the overloaded operators visible from this
8222 // point. We perform both an operator-name lookup from the local
8223 // scope and an argument-dependent lookup based on the types of
8224 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008225 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008226 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008227 if (S && OverOp != OO_None)
8228 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8229 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008230
John McCallb268a282010-08-23 23:25:46 +00008231 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008232 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008233
John McCallb268a282010-08-23 23:25:46 +00008234 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008235}
8236
Douglas Gregor5287f092009-11-05 00:51:44 +00008237// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008238ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008239 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008240 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008241}
8242
Steve Naroff66356bd2007-09-16 14:56:35 +00008243/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008244ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008245 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008246 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008247 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008248 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008249 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008250}
8251
John McCall31168b02011-06-15 23:02:42 +00008252/// Given the last statement in a statement-expression, check whether
8253/// the result is a producing expression (like a call to an
8254/// ns_returns_retained function) and, if so, rebuild it to hoist the
8255/// release out of the full-expression. Otherwise, return null.
8256/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008257static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008258 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008259 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008260 if (!cleanups) return 0;
8261
8262 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008263 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008264 return 0;
8265
8266 // Splice out the cast. This shouldn't modify any interesting
8267 // features of the statement.
8268 Expr *producer = cast->getSubExpr();
8269 assert(producer->getType() == cast->getType());
8270 assert(producer->getValueKind() == cast->getValueKind());
8271 cleanups->setSubExpr(producer);
8272 return cleanups;
8273}
8274
John McCalldadc5752010-08-24 06:29:42 +00008275ExprResult
John McCallb268a282010-08-23 23:25:46 +00008276Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008277 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008278 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8279 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8280
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008281 bool isFileScope
8282 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008283 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008284 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008285
Chris Lattner366727f2007-07-24 16:58:17 +00008286 // FIXME: there are a variety of strange constraints to enforce here, for
8287 // example, it is not possible to goto into a stmt expression apparently.
8288 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008289
Chris Lattner366727f2007-07-24 16:58:17 +00008290 // If there are sub stmts in the compound stmt, take the type of the last one
8291 // as the type of the stmtexpr.
8292 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008293 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008294 if (!Compound->body_empty()) {
8295 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008296 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008297 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008298 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8299 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008300 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008301 }
John McCall31168b02011-06-15 23:02:42 +00008302
John Wiegley01296292011-04-08 18:41:53 +00008303 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008304 // Do function/array conversion on the last expression, but not
8305 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008306 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8307 if (LastExpr.isInvalid())
8308 return ExprError();
8309 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008310
John Wiegley01296292011-04-08 18:41:53 +00008311 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008312 // In ARC, if the final expression ends in a consume, splice
8313 // the consume out and bind it later. In the alternate case
8314 // (when dealing with a retainable type), the result
8315 // initialization will create a produce. In both cases the
8316 // result will be +1, and we'll need to balance that out with
8317 // a bind.
8318 if (Expr *rebuiltLastStmt
8319 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8320 LastExpr = rebuiltLastStmt;
8321 } else {
8322 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008323 InitializedEntity::InitializeResult(LPLoc,
8324 Ty,
8325 false),
8326 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008327 LastExpr);
8328 }
8329
John Wiegley01296292011-04-08 18:41:53 +00008330 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008331 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008332 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008333 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008334 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008335 else
John Wiegley01296292011-04-08 18:41:53 +00008336 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008337 StmtExprMayBindToTemp = true;
8338 }
8339 }
8340 }
Chris Lattner944d3062008-07-26 19:51:01 +00008341 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008342
Eli Friedmanba961a92009-03-23 00:24:07 +00008343 // FIXME: Check that expression type is complete/non-abstract; statement
8344 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008345 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8346 if (StmtExprMayBindToTemp)
8347 return MaybeBindToTemporary(ResStmtExpr);
8348 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008349}
Steve Naroff78864672007-08-01 22:05:33 +00008350
John McCalldadc5752010-08-24 06:29:42 +00008351ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008352 TypeSourceInfo *TInfo,
8353 OffsetOfComponent *CompPtr,
8354 unsigned NumComponents,
8355 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008356 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008357 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008358 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008359
Chris Lattnerf17bd422007-08-30 17:45:32 +00008360 // We must have at least one component that refers to the type, and the first
8361 // one is known to be a field designator. Verify that the ArgTy represents
8362 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008363 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008364 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8365 << ArgTy << TypeRange);
8366
8367 // Type must be complete per C99 7.17p3 because a declaring a variable
8368 // with an incomplete type would be ill-formed.
8369 if (!Dependent
8370 && RequireCompleteType(BuiltinLoc, ArgTy,
8371 PDiag(diag::err_offsetof_incomplete_type)
8372 << TypeRange))
8373 return ExprError();
8374
Chris Lattner78502cf2007-08-31 21:49:13 +00008375 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8376 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008377 // FIXME: This diagnostic isn't actually visible because the location is in
8378 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008379 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008380 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8381 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008382
8383 bool DidWarnAboutNonPOD = false;
8384 QualType CurrentType = ArgTy;
8385 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008386 SmallVector<OffsetOfNode, 4> Comps;
8387 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008388 for (unsigned i = 0; i != NumComponents; ++i) {
8389 const OffsetOfComponent &OC = CompPtr[i];
8390 if (OC.isBrackets) {
8391 // Offset of an array sub-field. TODO: Should we allow vector elements?
8392 if (!CurrentType->isDependentType()) {
8393 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8394 if(!AT)
8395 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8396 << CurrentType);
8397 CurrentType = AT->getElementType();
8398 } else
8399 CurrentType = Context.DependentTy;
8400
Richard Smith9fcc5c32011-10-17 23:29:39 +00008401 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8402 if (IdxRval.isInvalid())
8403 return ExprError();
8404 Expr *Idx = IdxRval.take();
8405
Douglas Gregor882211c2010-04-28 22:16:22 +00008406 // The expression must be an integral expression.
8407 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008408 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8409 !Idx->getType()->isIntegerType())
8410 return ExprError(Diag(Idx->getLocStart(),
8411 diag::err_typecheck_subscript_not_integer)
8412 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008413
Douglas Gregor882211c2010-04-28 22:16:22 +00008414 // Record this array index.
8415 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008416 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008417 continue;
8418 }
8419
8420 // Offset of a field.
8421 if (CurrentType->isDependentType()) {
8422 // We have the offset of a field, but we can't look into the dependent
8423 // type. Just record the identifier of the field.
8424 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8425 CurrentType = Context.DependentTy;
8426 continue;
8427 }
8428
8429 // We need to have a complete type to look into.
8430 if (RequireCompleteType(OC.LocStart, CurrentType,
8431 diag::err_offsetof_incomplete_type))
8432 return ExprError();
8433
8434 // Look for the designated field.
8435 const RecordType *RC = CurrentType->getAs<RecordType>();
8436 if (!RC)
8437 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8438 << CurrentType);
8439 RecordDecl *RD = RC->getDecl();
8440
8441 // C++ [lib.support.types]p5:
8442 // The macro offsetof accepts a restricted set of type arguments in this
8443 // International Standard. type shall be a POD structure or a POD union
8444 // (clause 9).
8445 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8446 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008447 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008448 PDiag(diag::warn_offsetof_non_pod_type)
8449 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8450 << CurrentType))
8451 DidWarnAboutNonPOD = true;
8452 }
8453
8454 // Look for the field.
8455 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8456 LookupQualifiedName(R, RD);
8457 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008458 IndirectFieldDecl *IndirectMemberDecl = 0;
8459 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008460 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008461 MemberDecl = IndirectMemberDecl->getAnonField();
8462 }
8463
Douglas Gregor882211c2010-04-28 22:16:22 +00008464 if (!MemberDecl)
8465 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8466 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8467 OC.LocEnd));
8468
Douglas Gregor10982ea2010-04-28 22:36:06 +00008469 // C99 7.17p3:
8470 // (If the specified member is a bit-field, the behavior is undefined.)
8471 //
8472 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008473 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008474 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8475 << MemberDecl->getDeclName()
8476 << SourceRange(BuiltinLoc, RParenLoc);
8477 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8478 return ExprError();
8479 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008480
8481 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008482 if (IndirectMemberDecl)
8483 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008484
Douglas Gregord1702062010-04-29 00:18:15 +00008485 // If the member was found in a base class, introduce OffsetOfNodes for
8486 // the base class indirections.
8487 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8488 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008489 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008490 CXXBasePath &Path = Paths.front();
8491 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8492 B != BEnd; ++B)
8493 Comps.push_back(OffsetOfNode(B->Base));
8494 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008495
Francois Pichet783dd6e2010-11-21 06:08:52 +00008496 if (IndirectMemberDecl) {
8497 for (IndirectFieldDecl::chain_iterator FI =
8498 IndirectMemberDecl->chain_begin(),
8499 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8500 assert(isa<FieldDecl>(*FI));
8501 Comps.push_back(OffsetOfNode(OC.LocStart,
8502 cast<FieldDecl>(*FI), OC.LocEnd));
8503 }
8504 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008505 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008506
Douglas Gregor882211c2010-04-28 22:16:22 +00008507 CurrentType = MemberDecl->getType().getNonReferenceType();
8508 }
8509
8510 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8511 TInfo, Comps.data(), Comps.size(),
8512 Exprs.data(), Exprs.size(), RParenLoc));
8513}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008514
John McCalldadc5752010-08-24 06:29:42 +00008515ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008516 SourceLocation BuiltinLoc,
8517 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008518 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008519 OffsetOfComponent *CompPtr,
8520 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008521 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008522
Douglas Gregor882211c2010-04-28 22:16:22 +00008523 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008524 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008525 if (ArgTy.isNull())
8526 return ExprError();
8527
Eli Friedman06dcfd92010-08-05 10:15:45 +00008528 if (!ArgTInfo)
8529 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8530
8531 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008532 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008533}
8534
8535
John McCalldadc5752010-08-24 06:29:42 +00008536ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008537 Expr *CondExpr,
8538 Expr *LHSExpr, Expr *RHSExpr,
8539 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008540 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8541
John McCall7decc9e2010-11-18 06:31:45 +00008542 ExprValueKind VK = VK_RValue;
8543 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008544 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008545 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008546 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008547 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008548 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008549 } else {
8550 // The conditional expression is required to be a constant expression.
8551 llvm::APSInt condEval(32);
8552 SourceLocation ExpLoc;
8553 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008554 return ExprError(Diag(ExpLoc,
8555 diag::err_typecheck_choose_expr_requires_constant)
8556 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008557
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008558 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008559 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8560
8561 resType = ActiveExpr->getType();
8562 ValueDependent = ActiveExpr->isValueDependent();
8563 VK = ActiveExpr->getValueKind();
8564 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008565 }
8566
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008567 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008568 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008569 resType->isDependentType(),
8570 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008571}
8572
Steve Naroffc540d662008-09-03 18:15:37 +00008573//===----------------------------------------------------------------------===//
8574// Clang Extensions.
8575//===----------------------------------------------------------------------===//
8576
8577/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008578void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008579 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008580 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008581 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008582 if (CurScope)
8583 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008584 else
8585 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008586}
8587
Mike Stump82f071f2009-02-04 22:31:32 +00008588void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008589 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008590 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008591 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008592
John McCall8cb7bdf2010-06-04 23:28:52 +00008593 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008594 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008595
John McCall3882ace2011-01-05 12:14:39 +00008596 // GetTypeForDeclarator always produces a function type for a block
8597 // literal signature. Furthermore, it is always a FunctionProtoType
8598 // unless the function was written with a typedef.
8599 assert(T->isFunctionType() &&
8600 "GetTypeForDeclarator made a non-function block signature");
8601
8602 // Look for an explicit signature in that function type.
8603 FunctionProtoTypeLoc ExplicitSignature;
8604
8605 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8606 if (isa<FunctionProtoTypeLoc>(tmp)) {
8607 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8608
8609 // Check whether that explicit signature was synthesized by
8610 // GetTypeForDeclarator. If so, don't save that as part of the
8611 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008612 if (ExplicitSignature.getLocalRangeBegin() ==
8613 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008614 // This would be much cheaper if we stored TypeLocs instead of
8615 // TypeSourceInfos.
8616 TypeLoc Result = ExplicitSignature.getResultLoc();
8617 unsigned Size = Result.getFullDataSize();
8618 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8619 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8620
8621 ExplicitSignature = FunctionProtoTypeLoc();
8622 }
John McCalla3ccba02010-06-04 11:21:44 +00008623 }
Mike Stump11289f42009-09-09 15:08:12 +00008624
John McCall3882ace2011-01-05 12:14:39 +00008625 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8626 CurBlock->FunctionType = T;
8627
8628 const FunctionType *Fn = T->getAs<FunctionType>();
8629 QualType RetTy = Fn->getResultType();
8630 bool isVariadic =
8631 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8632
John McCall8e346702010-06-04 19:02:56 +00008633 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008634
John McCalla3ccba02010-06-04 11:21:44 +00008635 // Don't allow returning a objc interface by value.
8636 if (RetTy->isObjCObjectType()) {
8637 Diag(ParamInfo.getSourceRange().getBegin(),
8638 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8639 return;
8640 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008641
John McCalla3ccba02010-06-04 11:21:44 +00008642 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008643 // return type. TODO: what should we do with declarators like:
8644 // ^ * { ... }
8645 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008646 if (RetTy != Context.DependentTy)
8647 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008648
John McCalla3ccba02010-06-04 11:21:44 +00008649 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008650 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008651 if (ExplicitSignature) {
8652 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8653 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008654 if (Param->getIdentifier() == 0 &&
8655 !Param->isImplicit() &&
8656 !Param->isInvalidDecl() &&
8657 !getLangOptions().CPlusPlus)
8658 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008659 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008660 }
John McCalla3ccba02010-06-04 11:21:44 +00008661
8662 // Fake up parameter variables if we have a typedef, like
8663 // ^ fntype { ... }
8664 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8665 for (FunctionProtoType::arg_type_iterator
8666 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8667 ParmVarDecl *Param =
8668 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8669 ParamInfo.getSourceRange().getBegin(),
8670 *I);
John McCall8e346702010-06-04 19:02:56 +00008671 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008672 }
Steve Naroffc540d662008-09-03 18:15:37 +00008673 }
John McCalla3ccba02010-06-04 11:21:44 +00008674
John McCall8e346702010-06-04 19:02:56 +00008675 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008676 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008677 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008678 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8679 CurBlock->TheDecl->param_end(),
8680 /*CheckParameterNames=*/false);
8681 }
8682
John McCalla3ccba02010-06-04 11:21:44 +00008683 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008684 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008685
John McCall8e346702010-06-04 19:02:56 +00008686 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008687 Diag(ParamInfo.getAttributes()->getLoc(),
8688 diag::warn_attribute_sentinel_not_variadic) << 1;
8689 // FIXME: remove the attribute.
8690 }
8691
8692 // Put the parameter variables in scope. We can bail out immediately
8693 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008694 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008695 return;
8696
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008697 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008698 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8699 (*AI)->setOwningFunction(CurBlock->TheDecl);
8700
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008701 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008702 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008703 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008704
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008705 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008706 }
John McCallf7b2fb52010-01-22 00:28:27 +00008707 }
Steve Naroffc540d662008-09-03 18:15:37 +00008708}
8709
8710/// ActOnBlockError - If there is an error parsing a block, this callback
8711/// is invoked to pop the information about the block from the action impl.
8712void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008713 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008714 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008715 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008716}
8717
8718/// ActOnBlockStmtExpr - This is called when the body of a block statement
8719/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008720ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008721 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008722 // If blocks are disabled, emit an error.
8723 if (!LangOpts.Blocks)
8724 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008725
Douglas Gregor9a28e842010-03-01 23:15:13 +00008726 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008727
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008728 PopDeclContext();
8729
Steve Naroffc540d662008-09-03 18:15:37 +00008730 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008731 if (!BSI->ReturnType.isNull())
8732 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008733
Mike Stump3bf1ab42009-07-28 22:04:01 +00008734 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008735 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008736
John McCallc63de662011-02-02 13:00:07 +00008737 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008738 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8739 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008740
John McCall8e346702010-06-04 19:02:56 +00008741 // If the user wrote a function type in some form, try to use that.
8742 if (!BSI->FunctionType.isNull()) {
8743 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8744
8745 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8746 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8747
8748 // Turn protoless block types into nullary block types.
8749 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008750 FunctionProtoType::ExtProtoInfo EPI;
8751 EPI.ExtInfo = Ext;
8752 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008753
8754 // Otherwise, if we don't need to change anything about the function type,
8755 // preserve its sugar structure.
8756 } else if (FTy->getResultType() == RetTy &&
8757 (!NoReturn || FTy->getNoReturnAttr())) {
8758 BlockTy = BSI->FunctionType;
8759
8760 // Otherwise, make the minimal modifications to the function type.
8761 } else {
8762 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008763 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8764 EPI.TypeQuals = 0; // FIXME: silently?
8765 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008766 BlockTy = Context.getFunctionType(RetTy,
8767 FPT->arg_type_begin(),
8768 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008769 EPI);
John McCall8e346702010-06-04 19:02:56 +00008770 }
8771
8772 // If we don't have a function type, just build one from nothing.
8773 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008774 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008775 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008776 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008777 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008778
John McCall8e346702010-06-04 19:02:56 +00008779 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8780 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008781 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008782
Chris Lattner45542ea2009-04-19 05:28:12 +00008783 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008784 if (getCurFunction()->NeedsScopeChecking() &&
8785 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008786 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008787
Chris Lattner60f84492011-02-17 23:58:47 +00008788 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008789
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008790 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8791 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8792 const VarDecl *variable = ci->getVariable();
8793 QualType T = variable->getType();
8794 QualType::DestructionKind destructKind = T.isDestructedType();
8795 if (destructKind != QualType::DK_none)
8796 getCurFunction()->setHasBranchProtectedScope();
8797 }
8798
Douglas Gregor49695f02011-09-06 20:46:03 +00008799 computeNRVO(Body, getCurBlock());
8800
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008801 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8802 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8803 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8804
Douglas Gregor9a28e842010-03-01 23:15:13 +00008805 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008806}
8807
John McCalldadc5752010-08-24 06:29:42 +00008808ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008809 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008810 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008811 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008812 GetTypeFromParser(Ty, &TInfo);
8813 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008814}
8815
John McCalldadc5752010-08-24 06:29:42 +00008816ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008817 Expr *E, TypeSourceInfo *TInfo,
8818 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008819 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008820
Eli Friedman121ba0c2008-08-09 23:32:40 +00008821 // Get the va_list type
8822 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008823 if (VaListType->isArrayType()) {
8824 // Deal with implicit array decay; for example, on x86-64,
8825 // va_list is an array, but it's supposed to decay to
8826 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008827 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008828 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008829 ExprResult Result = UsualUnaryConversions(E);
8830 if (Result.isInvalid())
8831 return ExprError();
8832 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008833 } else {
8834 // Otherwise, the va_list argument must be an l-value because
8835 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008836 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008837 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008838 return ExprError();
8839 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008840
Douglas Gregorad3150c2009-05-19 23:10:31 +00008841 if (!E->isTypeDependent() &&
8842 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008843 return ExprError(Diag(E->getLocStart(),
8844 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008845 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008846 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008847
David Majnemerc75d1a12011-06-14 05:17:32 +00008848 if (!TInfo->getType()->isDependentType()) {
8849 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8850 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8851 << TInfo->getTypeLoc().getSourceRange()))
8852 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008853
David Majnemerc75d1a12011-06-14 05:17:32 +00008854 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8855 TInfo->getType(),
8856 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8857 << TInfo->getTypeLoc().getSourceRange()))
8858 return ExprError();
8859
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008860 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008861 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008862 TInfo->getType()->isObjCLifetimeType()
8863 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8864 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008865 << TInfo->getType()
8866 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008867 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008868
8869 // Check for va_arg where arguments of the given type will be promoted
8870 // (i.e. this va_arg is guaranteed to have undefined behavior).
8871 QualType PromoteType;
8872 if (TInfo->getType()->isPromotableIntegerType()) {
8873 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8874 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8875 PromoteType = QualType();
8876 }
8877 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8878 PromoteType = Context.DoubleTy;
8879 if (!PromoteType.isNull())
8880 Diag(TInfo->getTypeLoc().getBeginLoc(),
8881 diag::warn_second_parameter_to_va_arg_never_compatible)
8882 << TInfo->getType()
8883 << PromoteType
8884 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008885 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008886
Abramo Bagnara27db2392010-08-10 10:06:15 +00008887 QualType T = TInfo->getType().getNonLValueExprType(Context);
8888 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008889}
8890
John McCalldadc5752010-08-24 06:29:42 +00008891ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008892 // The type of __null will be int or long, depending on the size of
8893 // pointers on the target.
8894 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008895 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8896 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008897 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008898 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008899 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008900 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008901 Ty = Context.LongLongTy;
8902 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008903 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008904 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008905
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008906 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008907}
8908
Alexis Huntc46382e2010-04-28 23:02:27 +00008909static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008910 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008911 if (!SemaRef.getLangOptions().ObjC1)
8912 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008913
Anders Carlssonace5d072009-11-10 04:46:30 +00008914 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8915 if (!PT)
8916 return;
8917
8918 // Check if the destination is of type 'id'.
8919 if (!PT->isObjCIdType()) {
8920 // Check if the destination is the 'NSString' interface.
8921 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8922 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8923 return;
8924 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008925
Anders Carlssonace5d072009-11-10 04:46:30 +00008926 // Strip off any parens and casts.
8927 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008928 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008929 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008930
Douglas Gregora771f462010-03-31 17:46:05 +00008931 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008932}
8933
Chris Lattner9bad62c2008-01-04 18:04:52 +00008934bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8935 SourceLocation Loc,
8936 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008937 Expr *SrcExpr, AssignmentAction Action,
8938 bool *Complained) {
8939 if (Complained)
8940 *Complained = false;
8941
Chris Lattner9bad62c2008-01-04 18:04:52 +00008942 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008943 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008944 bool isInvalid = false;
8945 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008946 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008947 ConversionFixItGenerator ConvHints;
8948 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008949
Chris Lattner9bad62c2008-01-04 18:04:52 +00008950 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00008951 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008952 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008953 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008954 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008955 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8956 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008957 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008958 case IntToPointer:
8959 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008960 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8961 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008962 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008963 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008964 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008965 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008966 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8967 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008968 if (Hint.isNull() && !CheckInferredResultType) {
8969 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8970 }
8971 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008972 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008973 case IncompatiblePointerSign:
8974 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8975 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008976 case FunctionVoidPointer:
8977 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8978 break;
John McCall4fff8f62011-02-01 00:10:29 +00008979 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008980 // Perform array-to-pointer decay if necessary.
8981 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8982
John McCall4fff8f62011-02-01 00:10:29 +00008983 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8984 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8985 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8986 DiagKind = diag::err_typecheck_incompatible_address_space;
8987 break;
John McCall31168b02011-06-15 23:02:42 +00008988
8989
8990 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008991 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008992 break;
John McCall4fff8f62011-02-01 00:10:29 +00008993 }
8994
8995 llvm_unreachable("unknown error case for discarding qualifiers!");
8996 // fallthrough
8997 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008998 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008999 // If the qualifiers lost were because we were applying the
9000 // (deprecated) C++ conversion from a string literal to a char*
9001 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9002 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009003 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009004 // bit of refactoring (so that the second argument is an
9005 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009006 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009007 // C++ semantics.
9008 if (getLangOptions().CPlusPlus &&
9009 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9010 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009011 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9012 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009013 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009014 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009015 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009016 case IntToBlockPointer:
9017 DiagKind = diag::err_int_to_block_pointer;
9018 break;
9019 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009020 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009021 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009022 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009023 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009024 // it can give a more specific diagnostic.
9025 DiagKind = diag::warn_incompatible_qualified_id;
9026 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009027 case IncompatibleVectors:
9028 DiagKind = diag::warn_incompatible_vectors;
9029 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009030 case IncompatibleObjCWeakRef:
9031 DiagKind = diag::err_arc_weak_unavailable_assign;
9032 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009033 case Incompatible:
9034 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009035 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9036 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009037 isInvalid = true;
9038 break;
9039 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009040
Douglas Gregorc68e1402010-04-09 00:35:39 +00009041 QualType FirstType, SecondType;
9042 switch (Action) {
9043 case AA_Assigning:
9044 case AA_Initializing:
9045 // The destination type comes first.
9046 FirstType = DstType;
9047 SecondType = SrcType;
9048 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009049
Douglas Gregorc68e1402010-04-09 00:35:39 +00009050 case AA_Returning:
9051 case AA_Passing:
9052 case AA_Converting:
9053 case AA_Sending:
9054 case AA_Casting:
9055 // The source type comes first.
9056 FirstType = SrcType;
9057 SecondType = DstType;
9058 break;
9059 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009060
Anna Zaks3b402712011-07-28 19:51:27 +00009061 PartialDiagnostic FDiag = PDiag(DiagKind);
9062 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9063
9064 // If we can fix the conversion, suggest the FixIts.
9065 assert(ConvHints.isNull() || Hint.isNull());
9066 if (!ConvHints.isNull()) {
9067 for (llvm::SmallVector<FixItHint, 1>::iterator
9068 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9069 HI != HE; ++HI)
9070 FDiag << *HI;
9071 } else {
9072 FDiag << Hint;
9073 }
9074 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9075
9076 Diag(Loc, FDiag);
9077
Douglas Gregor33823722011-06-11 01:09:30 +00009078 if (CheckInferredResultType)
9079 EmitRelatedResultTypeNote(SrcExpr);
9080
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009081 if (Complained)
9082 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009083 return isInvalid;
9084}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009085
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009086bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009087 llvm::APSInt ICEResult;
9088 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9089 if (Result)
9090 *Result = ICEResult;
9091 return false;
9092 }
9093
Anders Carlssone54e8a12008-11-30 19:50:32 +00009094 Expr::EvalResult EvalResult;
9095
Mike Stump4e1f26a2009-02-19 03:04:26 +00009096 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009097 EvalResult.HasSideEffects) {
9098 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9099
9100 if (EvalResult.Diag) {
9101 // We only show the note if it's not the usual "invalid subexpression"
9102 // or if it's actually in a subexpression.
9103 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9104 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9105 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9106 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009107
Anders Carlssone54e8a12008-11-30 19:50:32 +00009108 return true;
9109 }
9110
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009111 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9112 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009113
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009114 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009115 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009116 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009117 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009118
Anders Carlssone54e8a12008-11-30 19:50:32 +00009119 if (Result)
9120 *Result = EvalResult.Val.getInt();
9121 return false;
9122}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009123
Douglas Gregorff790f12009-11-26 00:44:06 +00009124void
Mike Stump11289f42009-09-09 15:08:12 +00009125Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009126 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009127 ExpressionEvaluationContextRecord(NewContext,
9128 ExprTemporaries.size(),
9129 ExprNeedsCleanups));
9130 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009131}
9132
Richard Trieucfc491d2011-08-02 04:35:43 +00009133void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009134 // Pop the current expression evaluation context off the stack.
9135 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9136 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009137
Douglas Gregorfab31f42009-12-12 07:57:52 +00009138 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9139 if (Rec.PotentiallyReferenced) {
9140 // Mark any remaining declarations in the current position of the stack
9141 // as "referenced". If they were not meant to be referenced, semantic
9142 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009143 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009144 I = Rec.PotentiallyReferenced->begin(),
9145 IEnd = Rec.PotentiallyReferenced->end();
9146 I != IEnd; ++I)
9147 MarkDeclarationReferenced(I->first, I->second);
9148 }
9149
9150 if (Rec.PotentiallyDiagnosed) {
9151 // Emit any pending diagnostics.
9152 for (PotentiallyEmittedDiagnostics::iterator
9153 I = Rec.PotentiallyDiagnosed->begin(),
9154 IEnd = Rec.PotentiallyDiagnosed->end();
9155 I != IEnd; ++I)
9156 Diag(I->first, I->second);
9157 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009158 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009159
9160 // When are coming out of an unevaluated context, clear out any
9161 // temporaries that we may have created as part of the evaluation of
9162 // the expression in that context: they aren't relevant because they
9163 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009164 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009165 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9166 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009167 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9168
9169 // Otherwise, merge the contexts together.
9170 } else {
9171 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9172 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009173
9174 // Destroy the popped expression evaluation record.
9175 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009176}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009177
John McCall31168b02011-06-15 23:02:42 +00009178void Sema::DiscardCleanupsInEvaluationContext() {
9179 ExprTemporaries.erase(
9180 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9181 ExprTemporaries.end());
9182 ExprNeedsCleanups = false;
9183}
9184
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009185/// \brief Note that the given declaration was referenced in the source code.
9186///
9187/// This routine should be invoke whenever a given declaration is referenced
9188/// in the source code, and where that reference occurred. If this declaration
9189/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9190/// C99 6.9p3), then the declaration will be marked as used.
9191///
9192/// \param Loc the location where the declaration was referenced.
9193///
9194/// \param D the declaration that has been referenced by the source code.
9195void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9196 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009197
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009198 D->setReferenced();
9199
Douglas Gregorebada0772010-06-17 23:14:26 +00009200 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009201 return;
Mike Stump11289f42009-09-09 15:08:12 +00009202
Richard Trieucfc491d2011-08-02 04:35:43 +00009203 // Mark a parameter or variable declaration "used", regardless of whether
9204 // we're in a template or not. The reason for this is that unevaluated
9205 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9206 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009207 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009208 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009209 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009210 return;
9211 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009212
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009213 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9214 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009215
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009216 // Do not mark anything as "used" within a dependent context; wait for
9217 // an instantiation.
9218 if (CurContext->isDependentContext())
9219 return;
Mike Stump11289f42009-09-09 15:08:12 +00009220
Douglas Gregorff790f12009-11-26 00:44:06 +00009221 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009222 case Unevaluated:
9223 // We are in an expression that is not potentially evaluated; do nothing.
9224 return;
Mike Stump11289f42009-09-09 15:08:12 +00009225
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009226 case PotentiallyEvaluated:
9227 // We are in a potentially-evaluated expression, so this declaration is
9228 // "used"; handle this below.
9229 break;
Mike Stump11289f42009-09-09 15:08:12 +00009230
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009231 case PotentiallyPotentiallyEvaluated:
9232 // We are in an expression that may be potentially evaluated; queue this
9233 // declaration reference until we know whether the expression is
9234 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009235 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009236 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009237
9238 case PotentiallyEvaluatedIfUsed:
9239 // Referenced declarations will only be used if the construct in the
9240 // containing expression is used.
9241 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009242 }
Mike Stump11289f42009-09-09 15:08:12 +00009243
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009244 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009245 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009246 if (Constructor->isDefaulted()) {
9247 if (Constructor->isDefaultConstructor()) {
9248 if (Constructor->isTrivial())
9249 return;
9250 if (!Constructor->isUsed(false))
9251 DefineImplicitDefaultConstructor(Loc, Constructor);
9252 } else if (Constructor->isCopyConstructor()) {
9253 if (!Constructor->isUsed(false))
9254 DefineImplicitCopyConstructor(Loc, Constructor);
9255 } else if (Constructor->isMoveConstructor()) {
9256 if (!Constructor->isUsed(false))
9257 DefineImplicitMoveConstructor(Loc, Constructor);
9258 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009259 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009260
Douglas Gregor88d292c2010-05-13 16:44:06 +00009261 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009262 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009263 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009264 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009265 if (Destructor->isVirtual())
9266 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009267 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009268 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009269 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009270 if (!MethodDecl->isUsed(false)) {
9271 if (MethodDecl->isCopyAssignmentOperator())
9272 DefineImplicitCopyAssignment(Loc, MethodDecl);
9273 else
9274 DefineImplicitMoveAssignment(Loc, MethodDecl);
9275 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009276 } else if (MethodDecl->isVirtual())
9277 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009278 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009279 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009280 // Recursive functions should be marked when used from another function.
9281 if (CurContext == Function) return;
9282
Mike Stump11289f42009-09-09 15:08:12 +00009283 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009284 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009285 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009286 bool AlreadyInstantiated = false;
9287 if (FunctionTemplateSpecializationInfo *SpecInfo
9288 = Function->getTemplateSpecializationInfo()) {
9289 if (SpecInfo->getPointOfInstantiation().isInvalid())
9290 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009291 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009292 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009293 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009294 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009295 = Function->getMemberSpecializationInfo()) {
9296 if (MSInfo->getPointOfInstantiation().isInvalid())
9297 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009298 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009299 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009300 AlreadyInstantiated = true;
9301 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009302
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009303 if (!AlreadyInstantiated) {
9304 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9305 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9306 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9307 Loc));
9308 else
Chandler Carruth54080172010-08-25 08:44:16 +00009309 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009310 }
John McCall83779672011-02-19 02:53:41 +00009311 } else {
9312 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009313 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9314 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009315 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009316 MarkDeclarationReferenced(Loc, *i);
9317 }
John McCall83779672011-02-19 02:53:41 +00009318 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009319
John McCall83779672011-02-19 02:53:41 +00009320 // Keep track of used but undefined functions.
9321 if (!Function->isPure() && !Function->hasBody() &&
9322 Function->getLinkage() != ExternalLinkage) {
9323 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9324 if (old.isInvalid()) old = Loc;
9325 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009326
John McCall83779672011-02-19 02:53:41 +00009327 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009328 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009329 }
Mike Stump11289f42009-09-09 15:08:12 +00009330
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009331 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009332 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009333 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009334 Var->getInstantiatedFromStaticDataMember()) {
9335 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9336 assert(MSInfo && "Missing member specialization information?");
9337 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9338 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9339 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009340 // This is a modification of an existing AST node. Notify listeners.
9341 if (ASTMutationListener *L = getASTMutationListener())
9342 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009343 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009344 }
9345 }
Mike Stump11289f42009-09-09 15:08:12 +00009346
John McCall15dd4042011-02-21 19:25:48 +00009347 // Keep track of used but undefined variables. We make a hole in
9348 // the warning for static const data members with in-line
9349 // initializers.
John McCall83779672011-02-19 02:53:41 +00009350 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009351 && Var->getLinkage() != ExternalLinkage
9352 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009353 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9354 if (old.isInvalid()) old = Loc;
9355 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009356
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009357 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009358 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009359 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009360}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009361
Douglas Gregor5597ab42010-05-07 23:12:07 +00009362namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009363 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009364 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009365 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009366 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9367 Sema &S;
9368 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009369
Douglas Gregor5597ab42010-05-07 23:12:07 +00009370 public:
9371 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009372
Douglas Gregor5597ab42010-05-07 23:12:07 +00009373 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009374
9375 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9376 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009377 };
9378}
9379
Chandler Carruthaf80f662010-06-09 08:17:30 +00009380bool MarkReferencedDecls::TraverseTemplateArgument(
9381 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009382 if (Arg.getKind() == TemplateArgument::Declaration) {
9383 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9384 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009385
9386 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009387}
9388
Chandler Carruthaf80f662010-06-09 08:17:30 +00009389bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009390 if (ClassTemplateSpecializationDecl *Spec
9391 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9392 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009393 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009394 }
9395
Chandler Carruthc65667c2010-06-10 10:31:57 +00009396 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009397}
9398
9399void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9400 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009401 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009402}
9403
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009404namespace {
9405 /// \brief Helper class that marks all of the declarations referenced by
9406 /// potentially-evaluated subexpressions as "referenced".
9407 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9408 Sema &S;
9409
9410 public:
9411 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9412
9413 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9414
9415 void VisitDeclRefExpr(DeclRefExpr *E) {
9416 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9417 }
9418
9419 void VisitMemberExpr(MemberExpr *E) {
9420 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009421 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009422 }
9423
9424 void VisitCXXNewExpr(CXXNewExpr *E) {
9425 if (E->getConstructor())
9426 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9427 if (E->getOperatorNew())
9428 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9429 if (E->getOperatorDelete())
9430 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009431 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009432 }
9433
9434 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9435 if (E->getOperatorDelete())
9436 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009437 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9438 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9439 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9440 S.MarkDeclarationReferenced(E->getLocStart(),
9441 S.LookupDestructor(Record));
9442 }
9443
Douglas Gregor32b3de52010-09-11 23:32:50 +00009444 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009445 }
9446
9447 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9448 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009449 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009450 }
9451
9452 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9453 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9454 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009455
9456 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9457 Visit(E->getExpr());
9458 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009459 };
9460}
9461
9462/// \brief Mark any declarations that appear within this expression or any
9463/// potentially-evaluated subexpressions as "referenced".
9464void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9465 EvaluatedExprMarker(*this).Visit(E);
9466}
9467
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009468/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9469/// of the program being compiled.
9470///
9471/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009472/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009473/// possibility that the code will actually be executable. Code in sizeof()
9474/// expressions, code used only during overload resolution, etc., are not
9475/// potentially evaluated. This routine will suppress such diagnostics or,
9476/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009477/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009478/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009479///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009480/// This routine should be used for all diagnostics that describe the run-time
9481/// behavior of a program, such as passing a non-POD value through an ellipsis.
9482/// Failure to do so will likely result in spurious diagnostics or failures
9483/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009484bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009485 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009486 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009487 case Unevaluated:
9488 // The argument will never be evaluated, so don't complain.
9489 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009490
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009491 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009492 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009493 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009494 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009495 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009496 }
9497 else
9498 Diag(Loc, PD);
9499
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009500 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009501
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009502 case PotentiallyPotentiallyEvaluated:
9503 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9504 break;
9505 }
9506
9507 return false;
9508}
9509
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009510bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9511 CallExpr *CE, FunctionDecl *FD) {
9512 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9513 return false;
9514
9515 PartialDiagnostic Note =
9516 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9517 << FD->getDeclName() : PDiag();
9518 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009519
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009520 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009521 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009522 PDiag(diag::err_call_function_incomplete_return)
9523 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009524 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009525 << CE->getSourceRange(),
9526 std::make_pair(NoteLoc, Note)))
9527 return true;
9528
9529 return false;
9530}
9531
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009532// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009533// will prevent this condition from triggering, which is what we want.
9534void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9535 SourceLocation Loc;
9536
John McCall0506e4a2009-11-11 02:41:58 +00009537 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009538 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009539
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009540 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009541 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009542 return;
9543
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009544 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9545
John McCallb0e419e2009-11-12 00:06:05 +00009546 // Greylist some idioms by putting them into a warning subcategory.
9547 if (ObjCMessageExpr *ME
9548 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9549 Selector Sel = ME->getSelector();
9550
John McCallb0e419e2009-11-12 00:06:05 +00009551 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009552 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009553 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9554
9555 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009556 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009557 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9558 }
John McCall0506e4a2009-11-11 02:41:58 +00009559
John McCalld5707ab2009-10-12 21:59:07 +00009560 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009561 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009562 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009563 return;
9564
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009565 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009566 Loc = Op->getOperatorLoc();
9567 } else {
9568 // Not an assignment.
9569 return;
9570 }
9571
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009572 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009573
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009574 SourceLocation Open = E->getSourceRange().getBegin();
9575 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9576 Diag(Loc, diag::note_condition_assign_silence)
9577 << FixItHint::CreateInsertion(Open, "(")
9578 << FixItHint::CreateInsertion(Close, ")");
9579
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009580 if (IsOrAssign)
9581 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9582 << FixItHint::CreateReplacement(Loc, "!=");
9583 else
9584 Diag(Loc, diag::note_condition_assign_to_comparison)
9585 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009586}
9587
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009588/// \brief Redundant parentheses over an equality comparison can indicate
9589/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009590void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009591 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009592 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009593 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9594 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009595 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009596 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009597 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009598
Richard Trieuba63ce62011-09-09 01:45:06 +00009599 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009600
9601 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009602 if (opE->getOpcode() == BO_EQ &&
9603 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9604 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009605 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009606
Ted Kremenekae022092011-02-02 02:20:30 +00009607 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009608 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009609 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9610 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009611 Diag(Loc, diag::note_equality_comparison_to_assign)
9612 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009613 }
9614}
9615
John Wiegley01296292011-04-08 18:41:53 +00009616ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009617 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009618 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9619 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009620
John McCall0009fcc2011-04-26 20:42:42 +00009621 ExprResult result = CheckPlaceholderExpr(E);
9622 if (result.isInvalid()) return ExprError();
9623 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009624
John McCall0009fcc2011-04-26 20:42:42 +00009625 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009626 if (getLangOptions().CPlusPlus)
9627 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9628
John Wiegley01296292011-04-08 18:41:53 +00009629 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9630 if (ERes.isInvalid())
9631 return ExprError();
9632 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009633
9634 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009635 if (!T->isScalarType()) { // C99 6.8.4.1p1
9636 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9637 << T << E->getSourceRange();
9638 return ExprError();
9639 }
John McCalld5707ab2009-10-12 21:59:07 +00009640 }
9641
John Wiegley01296292011-04-08 18:41:53 +00009642 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009643}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009644
John McCalldadc5752010-08-24 06:29:42 +00009645ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009646 Expr *SubExpr) {
9647 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009648 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009649
Richard Trieuba63ce62011-09-09 01:45:06 +00009650 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009651}
John McCall36e7fe32010-10-12 00:20:44 +00009652
John McCall31996342011-04-07 08:22:57 +00009653namespace {
John McCall2979fe02011-04-12 00:42:48 +00009654 /// A visitor for rebuilding a call to an __unknown_any expression
9655 /// to have an appropriate type.
9656 struct RebuildUnknownAnyFunction
9657 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9658
9659 Sema &S;
9660
9661 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9662
9663 ExprResult VisitStmt(Stmt *S) {
9664 llvm_unreachable("unexpected statement!");
9665 return ExprError();
9666 }
9667
Richard Trieu10162ab2011-09-09 03:59:41 +00009668 ExprResult VisitExpr(Expr *E) {
9669 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9670 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009671 return ExprError();
9672 }
9673
9674 /// Rebuild an expression which simply semantically wraps another
9675 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009676 template <class T> ExprResult rebuildSugarExpr(T *E) {
9677 ExprResult SubResult = Visit(E->getSubExpr());
9678 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009679
Richard Trieu10162ab2011-09-09 03:59:41 +00009680 Expr *SubExpr = SubResult.take();
9681 E->setSubExpr(SubExpr);
9682 E->setType(SubExpr->getType());
9683 E->setValueKind(SubExpr->getValueKind());
9684 assert(E->getObjectKind() == OK_Ordinary);
9685 return E;
John McCall2979fe02011-04-12 00:42:48 +00009686 }
9687
Richard Trieu10162ab2011-09-09 03:59:41 +00009688 ExprResult VisitParenExpr(ParenExpr *E) {
9689 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009690 }
9691
Richard Trieu10162ab2011-09-09 03:59:41 +00009692 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9693 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009694 }
9695
Richard Trieu10162ab2011-09-09 03:59:41 +00009696 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9697 ExprResult SubResult = Visit(E->getSubExpr());
9698 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009699
Richard Trieu10162ab2011-09-09 03:59:41 +00009700 Expr *SubExpr = SubResult.take();
9701 E->setSubExpr(SubExpr);
9702 E->setType(S.Context.getPointerType(SubExpr->getType()));
9703 assert(E->getValueKind() == VK_RValue);
9704 assert(E->getObjectKind() == OK_Ordinary);
9705 return E;
John McCall2979fe02011-04-12 00:42:48 +00009706 }
9707
Richard Trieu10162ab2011-09-09 03:59:41 +00009708 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9709 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009710
Richard Trieu10162ab2011-09-09 03:59:41 +00009711 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009712
Richard Trieu10162ab2011-09-09 03:59:41 +00009713 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009714 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009715 !(isa<CXXMethodDecl>(VD) &&
9716 cast<CXXMethodDecl>(VD)->isInstance()))
9717 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009718
Richard Trieu10162ab2011-09-09 03:59:41 +00009719 return E;
John McCall2979fe02011-04-12 00:42:48 +00009720 }
9721
Richard Trieu10162ab2011-09-09 03:59:41 +00009722 ExprResult VisitMemberExpr(MemberExpr *E) {
9723 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009724 }
9725
Richard Trieu10162ab2011-09-09 03:59:41 +00009726 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9727 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009728 }
9729 };
9730}
9731
9732/// Given a function expression of unknown-any type, try to rebuild it
9733/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009734static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9735 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9736 if (Result.isInvalid()) return ExprError();
9737 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009738}
9739
9740namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009741 /// A visitor for rebuilding an expression of type __unknown_anytype
9742 /// into one which resolves the type directly on the referring
9743 /// expression. Strict preservation of the original source
9744 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009745 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009746 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009747
9748 Sema &S;
9749
9750 /// The current destination type.
9751 QualType DestType;
9752
Richard Trieu10162ab2011-09-09 03:59:41 +00009753 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9754 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009755
John McCall39439732011-04-09 22:50:59 +00009756 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009757 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009758 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009759 }
9760
Richard Trieu10162ab2011-09-09 03:59:41 +00009761 ExprResult VisitExpr(Expr *E) {
9762 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9763 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009764 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009765 }
9766
Richard Trieu10162ab2011-09-09 03:59:41 +00009767 ExprResult VisitCallExpr(CallExpr *E);
9768 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009769
John McCall39439732011-04-09 22:50:59 +00009770 /// Rebuild an expression which simply semantically wraps another
9771 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009772 template <class T> ExprResult rebuildSugarExpr(T *E) {
9773 ExprResult SubResult = Visit(E->getSubExpr());
9774 if (SubResult.isInvalid()) return ExprError();
9775 Expr *SubExpr = SubResult.take();
9776 E->setSubExpr(SubExpr);
9777 E->setType(SubExpr->getType());
9778 E->setValueKind(SubExpr->getValueKind());
9779 assert(E->getObjectKind() == OK_Ordinary);
9780 return E;
John McCall39439732011-04-09 22:50:59 +00009781 }
John McCall31996342011-04-07 08:22:57 +00009782
Richard Trieu10162ab2011-09-09 03:59:41 +00009783 ExprResult VisitParenExpr(ParenExpr *E) {
9784 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009785 }
9786
Richard Trieu10162ab2011-09-09 03:59:41 +00009787 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9788 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009789 }
9790
Richard Trieu10162ab2011-09-09 03:59:41 +00009791 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9792 const PointerType *Ptr = DestType->getAs<PointerType>();
9793 if (!Ptr) {
9794 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9795 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009796 return ExprError();
9797 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009798 assert(E->getValueKind() == VK_RValue);
9799 assert(E->getObjectKind() == OK_Ordinary);
9800 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009801
9802 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009803 DestType = Ptr->getPointeeType();
9804 ExprResult SubResult = Visit(E->getSubExpr());
9805 if (SubResult.isInvalid()) return ExprError();
9806 E->setSubExpr(SubResult.take());
9807 return E;
John McCall2979fe02011-04-12 00:42:48 +00009808 }
9809
Richard Trieu10162ab2011-09-09 03:59:41 +00009810 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009811
Richard Trieu10162ab2011-09-09 03:59:41 +00009812 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009813
Richard Trieu10162ab2011-09-09 03:59:41 +00009814 ExprResult VisitMemberExpr(MemberExpr *E) {
9815 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009816 }
John McCall39439732011-04-09 22:50:59 +00009817
Richard Trieu10162ab2011-09-09 03:59:41 +00009818 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9819 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009820 }
9821 };
9822}
9823
John McCall2d2e8702011-04-11 07:02:50 +00009824/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009825ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9826 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009827
9828 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009829 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009830 FK_FunctionPointer,
9831 FK_BlockPointer
9832 };
9833
Richard Trieu10162ab2011-09-09 03:59:41 +00009834 FnKind Kind;
9835 QualType CalleeType = CalleeExpr->getType();
9836 if (CalleeType == S.Context.BoundMemberTy) {
9837 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9838 Kind = FK_MemberFunction;
9839 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9840 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9841 CalleeType = Ptr->getPointeeType();
9842 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009843 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009844 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9845 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009846 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009848
9849 // Verify that this is a legal result type of a function.
9850 if (DestType->isArrayType() || DestType->isFunctionType()) {
9851 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009852 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009853 diagID = diag::err_block_returning_array_function;
9854
Richard Trieu10162ab2011-09-09 03:59:41 +00009855 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009856 << DestType->isFunctionType() << DestType;
9857 return ExprError();
9858 }
9859
9860 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009861 E->setType(DestType.getNonLValueExprType(S.Context));
9862 E->setValueKind(Expr::getValueKindForType(DestType));
9863 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009864
9865 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009866 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009867 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009868 Proto->arg_type_begin(),
9869 Proto->getNumArgs(),
9870 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009871 else
9872 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009873 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009874
9875 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009876 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009877 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009878 // Nothing to do.
9879 break;
9880
9881 case FK_FunctionPointer:
9882 DestType = S.Context.getPointerType(DestType);
9883 break;
9884
9885 case FK_BlockPointer:
9886 DestType = S.Context.getBlockPointerType(DestType);
9887 break;
9888 }
9889
9890 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009891 ExprResult CalleeResult = Visit(CalleeExpr);
9892 if (!CalleeResult.isUsable()) return ExprError();
9893 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009894
9895 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009896 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009897}
9898
Richard Trieu10162ab2011-09-09 03:59:41 +00009899ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009900 // Verify that this is a legal result type of a call.
9901 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009902 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009903 << DestType->isFunctionType() << DestType;
9904 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009905 }
9906
John McCall3f4138c2011-07-13 17:56:40 +00009907 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009908 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9909 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9910 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009911 }
John McCall2979fe02011-04-12 00:42:48 +00009912
John McCall2d2e8702011-04-11 07:02:50 +00009913 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009914 E->setType(DestType.getNonReferenceType());
9915 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009916
Richard Trieu10162ab2011-09-09 03:59:41 +00009917 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009918}
9919
Richard Trieu10162ab2011-09-09 03:59:41 +00009920ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009921 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +00009922 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9923 assert(E->getValueKind() == VK_RValue);
9924 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009925
Richard Trieu10162ab2011-09-09 03:59:41 +00009926 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009927
John McCall2d2e8702011-04-11 07:02:50 +00009928 // Rebuild the sub-expression as the pointee (function) type.
9929 DestType = DestType->castAs<PointerType>()->getPointeeType();
9930
Richard Trieu10162ab2011-09-09 03:59:41 +00009931 ExprResult Result = Visit(E->getSubExpr());
9932 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009933
Richard Trieu10162ab2011-09-09 03:59:41 +00009934 E->setSubExpr(Result.take());
9935 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +00009936}
9937
Richard Trieu10162ab2011-09-09 03:59:41 +00009938ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9939 ExprValueKind ValueKind = VK_LValue;
9940 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +00009941
9942 // We know how to make this work for certain kinds of decls:
9943
9944 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +00009945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9946 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9947 DestType = Ptr->getPointeeType();
9948 ExprResult Result = resolveDecl(E, VD);
9949 if (Result.isInvalid()) return ExprError();
9950 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +00009951 CK_FunctionToPointerDecay, VK_RValue);
9952 }
9953
Richard Trieu10162ab2011-09-09 03:59:41 +00009954 if (!Type->isFunctionType()) {
9955 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
9956 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +00009957 return ExprError();
9958 }
John McCall2d2e8702011-04-11 07:02:50 +00009959
Richard Trieu10162ab2011-09-09 03:59:41 +00009960 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
9961 if (MD->isInstance()) {
9962 ValueKind = VK_RValue;
9963 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +00009964 }
9965
John McCall2d2e8702011-04-11 07:02:50 +00009966 // Function references aren't l-values in C.
9967 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +00009968 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +00009969
9970 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +00009971 } else if (isa<VarDecl>(VD)) {
9972 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
9973 Type = RefTy->getPointeeType();
9974 } else if (Type->isFunctionType()) {
9975 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
9976 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009977 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009978 }
9979
9980 // - nothing else
9981 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9983 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009984 return ExprError();
9985 }
9986
Richard Trieu10162ab2011-09-09 03:59:41 +00009987 VD->setType(DestType);
9988 E->setType(Type);
9989 E->setValueKind(ValueKind);
9990 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +00009991}
9992
John McCall31996342011-04-07 08:22:57 +00009993/// Check a cast of an unknown-any type. We intentionally only
9994/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +00009995ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9996 Expr *CastExpr, CastKind &CastKind,
9997 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +00009998 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +00009999 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010000 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010001
Richard Trieuba63ce62011-09-09 01:45:06 +000010002 CastExpr = result.take();
10003 VK = CastExpr->getValueKind();
10004 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010005
Richard Trieuba63ce62011-09-09 01:45:06 +000010006 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010007}
10008
Richard Trieuba63ce62011-09-09 01:45:06 +000010009static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10010 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010011 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010012 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010013 E = E->IgnoreParenImpCasts();
10014 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10015 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010016 diagID = diag::err_uncasted_call_of_unknown_any;
10017 } else {
John McCall31996342011-04-07 08:22:57 +000010018 break;
John McCall2d2e8702011-04-11 07:02:50 +000010019 }
John McCall31996342011-04-07 08:22:57 +000010020 }
10021
John McCall2d2e8702011-04-11 07:02:50 +000010022 SourceLocation loc;
10023 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010024 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010025 loc = ref->getLocation();
10026 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010027 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010028 loc = mem->getMemberLoc();
10029 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010030 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010031 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000010032 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000010033 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010034 if (!d) {
10035 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10036 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10037 << orig->getSourceRange();
10038 return ExprError();
10039 }
John McCall2d2e8702011-04-11 07:02:50 +000010040 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010041 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10042 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010043 return ExprError();
10044 }
10045
10046 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010047
10048 // Never recoverable.
10049 return ExprError();
10050}
10051
John McCall36e7fe32010-10-12 00:20:44 +000010052/// Check for operands with placeholder types and complain if found.
10053/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010054ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000010055 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
10056 if (!placeholderType) return Owned(E);
10057
10058 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000010059
John McCall31996342011-04-07 08:22:57 +000010060 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000010061 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000010062 // Try to resolve a single function template specialization.
10063 // This is obligatory.
10064 ExprResult result = Owned(E);
10065 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10066 return result;
10067
10068 // If that failed, try to recover with a call.
10069 } else {
10070 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10071 /*complain*/ true);
10072 return result;
10073 }
10074 }
John McCall31996342011-04-07 08:22:57 +000010075
John McCall0009fcc2011-04-26 20:42:42 +000010076 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000010077 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000010078 ExprResult result = Owned(E);
10079 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10080 /*complain*/ true);
10081 return result;
John McCall4124c492011-10-17 18:40:02 +000010082 }
10083
10084 // ARC unbridged casts.
10085 case BuiltinType::ARCUnbridgedCast: {
10086 Expr *realCast = stripARCUnbridgedCast(E);
10087 diagnoseARCUnbridgedCast(realCast);
10088 return Owned(realCast);
10089 }
John McCall0009fcc2011-04-26 20:42:42 +000010090
John McCall31996342011-04-07 08:22:57 +000010091 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000010092 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000010093 return diagnoseUnknownAnyExpr(*this, E);
10094
John McCalle314e272011-10-18 21:02:43 +000010095 // Everything else should be impossible.
10096#define BUILTIN_TYPE(Id, SingletonId) \
10097 case BuiltinType::Id:
10098#define PLACEHOLDER_TYPE(Id, SingletonId)
10099#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000010100 break;
10101 }
10102
10103 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000010104}
Richard Trieu2c850c02011-04-21 21:44:26 +000010105
Richard Trieuba63ce62011-09-09 01:45:06 +000010106bool Sema::CheckCaseExpression(Expr *E) {
10107 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010108 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010109 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10110 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010111 return false;
10112}