blob: 46d9fe64e0f35522e498eb50e8a20014d8dbc6f4 [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 }
56 return true;
57}
David Chisnall9f57c292009-08-17 16:35:33 +000058
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000059static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
60 NamedDecl *D, SourceLocation Loc,
61 const ObjCInterfaceDecl *UnknownObjCClass) {
62 // See if this declaration is unavailable or deprecated.
63 std::string Message;
64 AvailabilityResult Result = D->getAvailability(&Message);
65 switch (Result) {
66 case AR_Available:
67 case AR_NotYetIntroduced:
68 break;
69
70 case AR_Deprecated:
71 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
72 break;
73
74 case AR_Unavailable:
75 if (cast<Decl>(S.CurContext)->getAvailability() != AR_Unavailable) {
76 if (Message.empty()) {
77 if (!UnknownObjCClass)
78 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
79 else
80 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
81 << D->getDeclName();
82 }
83 else
84 S.Diag(Loc, diag::err_unavailable_message)
85 << D->getDeclName() << Message;
86 S.Diag(D->getLocation(), diag::note_unavailable_here)
87 << isa<FunctionDecl>(D) << false;
88 }
89 break;
90 }
91 return Result;
92}
93
Douglas Gregor171c45a2009-02-18 21:56:37 +000094/// \brief Determine whether the use of this declaration is valid, and
95/// emit any corresponding diagnostics.
96///
97/// This routine diagnoses various problems with referencing
98/// declarations that can occur when using a declaration. For example,
99/// it might warn if a deprecated or unavailable declaration is being
100/// used, or produce an error (and return true) if a C++0x deleted
101/// function is being used.
102///
103/// \returns true if there was an error (this declaration cannot be
104/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000105///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000106bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000107 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000108 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
109 // If there were any diagnostics suppressed by template argument deduction,
110 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000112 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
113 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000115 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
116 Diag(Suppressed[I].first, Suppressed[I].second);
117
118 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000119 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000120 // entry from the table, because we want to avoid ever emitting these
121 // diagnostics again.
122 Suppressed.clear();
123 }
124 }
125
Richard Smith30482bc2011-02-20 03:19:35 +0000126 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000127 if (ParsingInitForAutoVars.count(D)) {
128 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
129 << D->getDeclName();
130 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000131 }
132
Douglas Gregor171c45a2009-02-18 21:56:37 +0000133 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000135 if (FD->isDeleted()) {
136 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000137 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000138 return true;
139 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000140 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000141 AvailabilityResult Result =
142 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000143
Anders Carlsson73067a02010-10-22 23:37:08 +0000144 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000145 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000146 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000147 // For available enumerator, it will become unavailable/deprecated
148 // if its enum declaration is as such.
149 if (Result == AR_Available)
150 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
151 const DeclContext *DC = ECD->getDeclContext();
152 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000153 DiagnoseAvailabilityOfDecl(*this,
154 const_cast< EnumDecl *>(TheEnumDecl),
155 Loc, UnknownObjCClass);
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000156 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000157 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000158}
159
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000160/// \brief Retrieve the message suffix that should be added to a
161/// diagnostic complaining about the given function being deleted or
162/// unavailable.
163std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
164 // FIXME: C++0x implicitly-deleted special member functions could be
165 // detected here so that we could improve diagnostics to say, e.g.,
166 // "base class 'A' had a deleted copy constructor".
167 if (FD->isDeleted())
168 return std::string();
169
170 std::string Message;
171 if (FD->getAvailability(&Message))
172 return ": " + Message;
173
174 return std::string();
175}
176
John McCallb46f2872011-09-09 07:56:05 +0000177/// DiagnoseSentinelCalls - This routine checks whether a call or
178/// message-send is to a declaration with the sentinel attribute, and
179/// if so, it checks that the requirements of the sentinel are
180/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000181void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000182 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000183 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000184 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000185 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000186
John McCallb46f2872011-09-09 07:56:05 +0000187 // The number of formal parameters of the declaration.
188 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000189
John McCallb46f2872011-09-09 07:56:05 +0000190 // The kind of declaration. This is also an index into a %select in
191 // the diagnostic.
192 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
193
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000194 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000195 numFormalParams = MD->param_size();
196 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000197 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000198 numFormalParams = FD->param_size();
199 calleeType = CT_Function;
200 } else if (isa<VarDecl>(D)) {
201 QualType type = cast<ValueDecl>(D)->getType();
202 const FunctionType *fn = 0;
203 if (const PointerType *ptr = type->getAs<PointerType>()) {
204 fn = ptr->getPointeeType()->getAs<FunctionType>();
205 if (!fn) return;
206 calleeType = CT_Function;
207 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
208 fn = ptr->getPointeeType()->castAs<FunctionType>();
209 calleeType = CT_Block;
210 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000211 return;
John McCallb46f2872011-09-09 07:56:05 +0000212 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213
John McCallb46f2872011-09-09 07:56:05 +0000214 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
215 numFormalParams = proto->getNumArgs();
216 } else {
217 numFormalParams = 0;
218 }
219 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000220 return;
221 }
John McCallb46f2872011-09-09 07:56:05 +0000222
223 // "nullPos" is the number of formal parameters at the end which
224 // effectively count as part of the variadic arguments. This is
225 // useful if you would prefer to not have *any* formal parameters,
226 // but the language forces you to have at least one.
227 unsigned nullPos = attr->getNullPos();
228 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
229 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
230
231 // The number of arguments which should follow the sentinel.
232 unsigned numArgsAfterSentinel = attr->getSentinel();
233
234 // If there aren't enough arguments for all the formal parameters,
235 // the sentinel, and the args after the sentinel, complain.
236 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000237 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000238 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000239 return;
240 }
John McCallb46f2872011-09-09 07:56:05 +0000241
242 // Otherwise, find the sentinel expression.
243 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000244 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000245 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000246
247 // nullptr_t is always treated as null.
248 if (sentinelExpr->getType()->isNullPtrType()) return;
249
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000250 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000251 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
252 Expr::NPC_ValueDependentIsNull))
253 return;
254
255 // Unfortunately, __null has type 'int'.
256 if (isa<GNUNullExpr>(sentinelExpr)) return;
257
John McCallb46f2872011-09-09 07:56:05 +0000258 // Pick a reasonable string to insert. Optimistically use 'nil' or
259 // 'NULL' if those are actually defined in the context. Only use
260 // 'nil' for ObjC methods, where it's much more likely that the
261 // variadic arguments form a list of object pointers.
262 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000263 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
264 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000265 if (calleeType == CT_Method &&
266 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000267 NullValue = "nil";
268 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
269 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000270 else
John McCallb46f2872011-09-09 07:56:05 +0000271 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000272
273 if (MissingNilLoc.isInvalid())
274 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
275 else
276 Diag(MissingNilLoc, diag::warn_missing_sentinel)
277 << calleeType
278 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000279 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000280}
281
Richard Trieuba63ce62011-09-09 01:45:06 +0000282SourceRange Sema::getExprRange(Expr *E) const {
283 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000284}
285
Chris Lattner513165e2008-07-25 21:10:04 +0000286//===----------------------------------------------------------------------===//
287// Standard Promotions and Conversions
288//===----------------------------------------------------------------------===//
289
Chris Lattner513165e2008-07-25 21:10:04 +0000290/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000291ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000292 QualType Ty = E->getType();
293 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
294
Chris Lattner513165e2008-07-25 21:10:04 +0000295 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000296 E = ImpCastExprToType(E, Context.getPointerType(Ty),
297 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000298 else if (Ty->isArrayType()) {
299 // In C90 mode, arrays only promote to pointers if the array expression is
300 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
301 // type 'array of type' is converted to an expression that has type 'pointer
302 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
303 // that has type 'array of type' ...". The relevant change is "an lvalue"
304 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000305 //
306 // C++ 4.2p1:
307 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
308 // T" can be converted to an rvalue of type "pointer to T".
309 //
John McCall086a4642010-11-24 05:12:34 +0000310 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000311 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
312 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000313 }
John Wiegley01296292011-04-08 18:41:53 +0000314 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000315}
316
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000317static void CheckForNullPointerDereference(Sema &S, Expr *E) {
318 // Check to see if we are dereferencing a null pointer. If so,
319 // and if not volatile-qualified, this is undefined behavior that the
320 // optimizer will delete, so warn about it. People sometimes try to use this
321 // to get a deterministic trap and are surprised by clang's behavior. This
322 // only handles the pattern "*null", which is a very syntactic check.
323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
324 if (UO->getOpcode() == UO_Deref &&
325 UO->getSubExpr()->IgnoreParenCasts()->
326 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
327 !UO->getType().isVolatileQualified()) {
328 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
329 S.PDiag(diag::warn_indirection_through_null)
330 << UO->getSubExpr()->getSourceRange());
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::note_indirection_through_null));
333 }
334}
335
John Wiegley01296292011-04-08 18:41:53 +0000336ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000337 // C++ [conv.lval]p1:
338 // A glvalue of a non-function, non-array type T can be
339 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000340 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000341
John McCall27584242010-12-06 20:48:59 +0000342 QualType T = E->getType();
343 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000344
John McCall27584242010-12-06 20:48:59 +0000345 // Create a load out of an ObjCProperty l-value, if necessary.
346 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000347 ExprResult Res = ConvertPropertyForRValue(E);
348 if (Res.isInvalid())
349 return Owned(E);
350 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000351 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000352 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000353 }
John McCall27584242010-12-06 20:48:59 +0000354
355 // We don't want to throw lvalue-to-rvalue casts on top of
356 // expressions of certain types in C++.
357 if (getLangOptions().CPlusPlus &&
358 (E->getType() == Context.OverloadTy ||
359 T->isDependentType() ||
360 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000361 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000362
363 // The C standard is actually really unclear on this point, and
364 // DR106 tells us what the result should be but not why. It's
365 // generally best to say that void types just doesn't undergo
366 // lvalue-to-rvalue at all. Note that expressions of unqualified
367 // 'void' type are never l-values, but qualified void can be.
368 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000370
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000371 CheckForNullPointerDereference(*this, E);
372
John McCall27584242010-12-06 20:48:59 +0000373 // C++ [conv.lval]p1:
374 // [...] If T is a non-class type, the type of the prvalue is the
375 // cv-unqualified version of T. Otherwise, the type of the
376 // rvalue is T.
377 //
378 // C99 6.3.2.1p2:
379 // If the lvalue has qualified type, the value has the unqualified
380 // version of the type of the lvalue; otherwise, the value has the
381 // type of the lvalue.
382 if (T.hasQualifiers())
383 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000384
John Wiegley01296292011-04-08 18:41:53 +0000385 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
386 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000387}
388
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
390 ExprResult Res = DefaultFunctionArrayConversion(E);
391 if (Res.isInvalid())
392 return ExprError();
393 Res = DefaultLvalueConversion(Res.take());
394 if (Res.isInvalid())
395 return ExprError();
396 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000397}
398
399
Chris Lattner513165e2008-07-25 21:10:04 +0000400/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000401/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000402/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// apply if the array is an argument to the sizeof or address (&) operators.
404/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000405ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000406 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000407 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
408 if (Res.isInvalid())
409 return Owned(E);
410 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000411
412 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000413 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000414
415 // Try to perform integral promotions if the object has a theoretically
416 // promotable type.
417 if (Ty->isIntegralOrUnscopedEnumerationType()) {
418 // C99 6.3.1.1p2:
419 //
420 // The following may be used in an expression wherever an int or
421 // unsigned int may be used:
422 // - an object or expression with an integer type whose integer
423 // conversion rank is less than or equal to the rank of int
424 // and unsigned int.
425 // - A bit-field of type _Bool, int, signed int, or unsigned int.
426 //
427 // If an int can represent all values of the original type, the
428 // value is converted to an int; otherwise, it is converted to an
429 // unsigned int. These are called the integer promotions. All
430 // other types are unchanged by the integer promotions.
431
432 QualType PTy = Context.isPromotableBitField(E);
433 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
435 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000436 }
437 if (Ty->isPromotableIntegerType()) {
438 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000439 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
440 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000441 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000442 }
John Wiegley01296292011-04-08 18:41:53 +0000443 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000444}
445
Chris Lattner2ce500f2008-07-25 22:25:12 +0000446/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000447/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000448/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000449ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
450 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000451 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000452
John Wiegley01296292011-04-08 18:41:53 +0000453 ExprResult Res = UsualUnaryConversions(E);
454 if (Res.isInvalid())
455 return Owned(E);
456 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000457
Chris Lattner2ce500f2008-07-25 22:25:12 +0000458 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000459 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000460 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
461
John McCall4bb057d2011-08-27 22:06:17 +0000462 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000463 // promotion, even on class types, but note:
464 // C++11 [conv.lval]p2:
465 // When an lvalue-to-rvalue conversion occurs in an unevaluated
466 // operand or a subexpression thereof the value contained in the
467 // referenced object is not accessed. Otherwise, if the glvalue
468 // has a class type, the conversion copy-initializes a temporary
469 // of type T from the glvalue and the result of the conversion
470 // is a prvalue for the temporary.
471 // FIXME: add some way to gate this entire thing for correctness in
472 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000473 if (getLangOptions().CPlusPlus && E->isGLValue() &&
474 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000475 ExprResult Temp = PerformCopyInitialization(
476 InitializedEntity::InitializeTemporary(E->getType()),
477 E->getExprLoc(),
478 Owned(E));
479 if (Temp.isInvalid())
480 return ExprError();
481 E = Temp.get();
482 }
483
John Wiegley01296292011-04-08 18:41:53 +0000484 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000485}
486
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000487/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
488/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000489/// interfaces passed by value.
490ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000491 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000492 ExprResult ExprRes = CheckPlaceholderExpr(E);
493 if (ExprRes.isInvalid())
494 return ExprError();
495
496 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000497 if (ExprRes.isInvalid())
498 return ExprError();
499 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregor347e0f22011-05-21 19:26:31 +0000501 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000502 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000503 DiagRuntimeBehavior(E->getLocStart(), 0,
504 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
505 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000506 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000507
John McCall31168b02011-06-15 23:02:42 +0000508 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000509 // C++0x [expr.call]p7:
510 // Passing a potentially-evaluated argument of class type (Clause 9)
511 // having a non-trivial copy constructor, a non-trivial move constructor,
512 // or a non-trivial destructor, with no corresponding parameter,
513 // is conditionally-supported with implementation-defined semantics.
514 bool TrivialEnough = false;
515 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
516 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
517 if (Record->hasTrivialCopyConstructor() &&
518 Record->hasTrivialMoveConstructor() &&
519 Record->hasTrivialDestructor())
520 TrivialEnough = true;
521 }
522 }
John McCall31168b02011-06-15 23:02:42 +0000523
524 if (!TrivialEnough &&
525 getLangOptions().ObjCAutoRefCount &&
526 E->getType()->isObjCLifetimeType())
527 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000528
529 if (TrivialEnough) {
530 // Nothing to diagnose. This is okay.
531 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000532 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000533 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000534 << CT)) {
535 // Turn this into a trap.
536 CXXScopeSpec SS;
537 UnqualifiedId Name;
538 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
539 E->getLocStart());
540 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
541 if (TrapFn.isInvalid())
542 return ExprError();
543
544 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
545 MultiExprArg(), E->getLocEnd());
546 if (Call.isInvalid())
547 return ExprError();
548
549 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
550 Call.get(), E);
551 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000552 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000553 E = Comma.get();
554 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000555 }
556
John Wiegley01296292011-04-08 18:41:53 +0000557 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000558}
559
Richard Trieu7aa58f12011-09-02 20:58:51 +0000560/// \brief Converts an integer to complex float type. Helper function of
561/// UsualArithmeticConversions()
562///
563/// \return false if the integer expression is an integer type and is
564/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000565static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
566 ExprResult &ComplexExpr,
567 QualType IntTy,
568 QualType ComplexTy,
569 bool SkipCast) {
570 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
571 if (SkipCast) return false;
572 if (IntTy->isIntegerType()) {
573 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
574 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
575 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000576 CK_FloatingRealToComplex);
577 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000578 assert(IntTy->isComplexIntegerType());
579 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000580 CK_IntegralComplexToFloatingComplex);
581 }
582 return false;
583}
584
585/// \brief Takes two complex float types and converts them to the same type.
586/// Helper function of UsualArithmeticConversions()
587static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000588handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
589 ExprResult &RHS, QualType LHSType,
590 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000591 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000592 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000593
594 if (order < 0) {
595 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000596 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000597 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
598 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000599 }
600 if (order > 0)
601 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000602 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
603 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000604}
605
606/// \brief Converts otherExpr to complex float and promotes complexExpr if
607/// necessary. Helper function of UsualArithmeticConversions()
608static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000609 ExprResult &ComplexExpr,
610 ExprResult &OtherExpr,
611 QualType ComplexTy,
612 QualType OtherTy,
613 bool ConvertComplexExpr,
614 bool ConvertOtherExpr) {
615 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000616
617 // If just the complexExpr is complex, the otherExpr needs to be converted,
618 // and the complexExpr might need to be promoted.
619 if (order > 0) { // complexExpr is wider
620 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000621 if (ConvertOtherExpr) {
622 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
623 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
624 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000625 CK_FloatingRealToComplex);
626 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000627 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000628 }
629
630 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000631 QualType result = (order == 0 ? ComplexTy :
632 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000633
634 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 if (ConvertOtherExpr)
636 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000637 CK_FloatingRealToComplex);
638
639 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000640 if (ConvertComplexExpr && order < 0)
641 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000642 CK_FloatingComplexCast);
643
644 return result;
645}
646
647/// \brief Handle arithmetic conversion with complex types. Helper function of
648/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000649static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
650 ExprResult &RHS, QualType LHSType,
651 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000652 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000653 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000654 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000655 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000656 return LHSType;
657 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000658 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000659 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000660
661 // This handles complex/complex, complex/float, or float/complex.
662 // When both operands are complex, the shorter operand is converted to the
663 // type of the longer, and that is the type of the result. This corresponds
664 // to what is done when combining two real floating-point operands.
665 // The fun begins when size promotion occur across type domains.
666 // From H&S 6.3.4: When one operand is complex and the other is a real
667 // floating-point type, the less precise type is converted, within it's
668 // real or complex domain, to the precision of the other type. For example,
669 // when combining a "long double" with a "double _Complex", the
670 // "double _Complex" is promoted to "long double _Complex".
671
Richard Trieu5065cdd2011-09-06 18:25:09 +0000672 bool LHSComplexFloat = LHSType->isComplexType();
673 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000674
675 // If both are complex, just cast to the more precise type.
676 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000677 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
678 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000679 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000680
681 // If only one operand is complex, promote it if necessary and convert the
682 // other operand to complex.
683 if (LHSComplexFloat)
684 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000685 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000686 /*convertOtherExpr*/ true);
687
688 assert(RHSComplexFloat);
689 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000690 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000691 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692}
693
694/// \brief Hande arithmetic conversion from integer to float. Helper function
695/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000696static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
697 ExprResult &IntExpr,
698 QualType FloatTy, QualType IntTy,
699 bool ConvertFloat, bool ConvertInt) {
700 if (IntTy->isIntegerType()) {
701 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000702 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000703 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000704 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000705 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000706 }
707
708 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000709 assert(IntTy->isComplexIntegerType());
710 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000711
712 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000713 if (ConvertInt)
714 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715 CK_IntegralComplexToFloatingComplex);
716
717 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000718 if (ConvertFloat)
719 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 CK_FloatingRealToComplex);
721
722 return result;
723}
724
725/// \brief Handle arithmethic conversion with floating point types. Helper
726/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000727static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
728 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000729 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000730 bool LHSFloat = LHSType->isRealFloatingType();
731 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000732
733 // If we have two real floating types, convert the smaller operand
734 // to the bigger result.
735 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000736 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000737 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000738 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
739 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000740 }
741
742 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000743 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000744 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
745 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000746 }
747
748 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000749 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000750 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000751 /*convertInt=*/ true);
752 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000755 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000756}
757
758/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000759/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760// FIXME: if the operands are (int, _Complex long), we currently
761// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000762static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
763 ExprResult &RHS, QualType LHSType,
764 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000765 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000766 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
767 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000768
Richard Trieucfe3f212011-09-06 18:38:41 +0000769 if (LHSComplexInt && RHSComplexInt) {
770 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
771 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772 assert(order && "inequal types with equal element ordering");
773 if (order > 0) {
774 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000775 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
776 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000777 }
778
Richard Trieuba63ce62011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
781 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782 }
783
Richard Trieucfe3f212011-09-06 18:38:41 +0000784 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000786 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
787 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000788 }
789
Richard Trieucfe3f212011-09-06 18:38:41 +0000790 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000792 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000793 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
794 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795}
796
797/// \brief Handle integer arithmetic conversions. Helper function of
798/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000799static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
800 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000801 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000802 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000803 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
804 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
805 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
806 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 // Same signedness; use the higher-ranked type
808 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000809 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
810 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000811 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000812 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
813 return RHSType;
814 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000815 // The unsigned type has greater than or equal rank to the
816 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000817 if (RHSSigned) {
818 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
819 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000820 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000821 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
822 return RHSType;
823 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000824 // The two types are different widths; if we are here, that
825 // means the signed type is larger than the unsigned type, so
826 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000827 if (LHSSigned) {
828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
829 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000830 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000831 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
832 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000833 } else {
834 // The signed type is higher-ranked than the unsigned type,
835 // but isn't actually any bigger (like unsigned int and long
836 // on most 32-bit systems). Use the unsigned type corresponding
837 // to the signed type.
838 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000839 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
840 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000841 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000842 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000843 return result;
844 }
845}
846
Chris Lattner513165e2008-07-25 21:10:04 +0000847/// UsualArithmeticConversions - Performs various conversions that are common to
848/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000849/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000850/// responsible for emitting appropriate error diagnostics.
851/// FIXME: verify the conversion rules for "complex int" are consistent with
852/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000853QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000854 bool IsCompAssign) {
855 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000856 LHS = UsualUnaryConversions(LHS.take());
857 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000858 return QualType();
859 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000860
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000861 RHS = UsualUnaryConversions(RHS.take());
862 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000863 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000864
Mike Stump11289f42009-09-09 15:08:12 +0000865 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000866 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 QualType LHSType =
868 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
869 QualType RHSType =
870 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000871
872 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873 if (LHSType == RHSType)
874 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000875
876 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
877 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000878 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
879 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000880
John McCalld005ac92010-11-13 08:17:45 +0000881 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000882 QualType LHSUnpromotedType = LHSType;
883 if (LHSType->isPromotableIntegerType())
884 LHSType = Context.getPromotedIntegerType(LHSType);
885 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000886 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000887 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000889 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000890
John McCalld005ac92010-11-13 08:17:45 +0000891 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000892 if (LHSType == RHSType)
893 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000894
895 // At this point, we have two different arithmetic types.
896
897 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000898 if (LHSType->isComplexType() || RHSType->isComplexType())
899 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000900 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000901
902 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000903 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
904 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000905 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000906
907 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000908 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000909 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000910 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000911
912 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000914 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000915}
916
Chris Lattner513165e2008-07-25 21:10:04 +0000917//===----------------------------------------------------------------------===//
918// Semantic Analysis for various Expression Types
919//===----------------------------------------------------------------------===//
920
921
Peter Collingbourne91147592011-04-15 00:35:48 +0000922ExprResult
923Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
924 SourceLocation DefaultLoc,
925 SourceLocation RParenLoc,
926 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000927 MultiTypeArg ArgTypes,
928 MultiExprArg ArgExprs) {
929 unsigned NumAssocs = ArgTypes.size();
930 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000931
Richard Trieuba63ce62011-09-09 01:45:06 +0000932 ParsedType *ParsedTypes = ArgTypes.release();
933 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000934
935 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
936 for (unsigned i = 0; i < NumAssocs; ++i) {
937 if (ParsedTypes[i])
938 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
939 else
940 Types[i] = 0;
941 }
942
943 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
944 ControllingExpr, Types, Exprs,
945 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000946 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000947 return ER;
948}
949
950ExprResult
951Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
952 SourceLocation DefaultLoc,
953 SourceLocation RParenLoc,
954 Expr *ControllingExpr,
955 TypeSourceInfo **Types,
956 Expr **Exprs,
957 unsigned NumAssocs) {
958 bool TypeErrorFound = false,
959 IsResultDependent = ControllingExpr->isTypeDependent(),
960 ContainsUnexpandedParameterPack
961 = ControllingExpr->containsUnexpandedParameterPack();
962
963 for (unsigned i = 0; i < NumAssocs; ++i) {
964 if (Exprs[i]->containsUnexpandedParameterPack())
965 ContainsUnexpandedParameterPack = true;
966
967 if (Types[i]) {
968 if (Types[i]->getType()->containsUnexpandedParameterPack())
969 ContainsUnexpandedParameterPack = true;
970
971 if (Types[i]->getType()->isDependentType()) {
972 IsResultDependent = true;
973 } else {
974 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
975 // complete object type other than a variably modified type."
976 unsigned D = 0;
977 if (Types[i]->getType()->isIncompleteType())
978 D = diag::err_assoc_type_incomplete;
979 else if (!Types[i]->getType()->isObjectType())
980 D = diag::err_assoc_type_nonobject;
981 else if (Types[i]->getType()->isVariablyModifiedType())
982 D = diag::err_assoc_type_variably_modified;
983
984 if (D != 0) {
985 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
986 << Types[i]->getTypeLoc().getSourceRange()
987 << Types[i]->getType();
988 TypeErrorFound = true;
989 }
990
991 // C1X 6.5.1.1p2 "No two generic associations in the same generic
992 // selection shall specify compatible types."
993 for (unsigned j = i+1; j < NumAssocs; ++j)
994 if (Types[j] && !Types[j]->getType()->isDependentType() &&
995 Context.typesAreCompatible(Types[i]->getType(),
996 Types[j]->getType())) {
997 Diag(Types[j]->getTypeLoc().getBeginLoc(),
998 diag::err_assoc_compatible_types)
999 << Types[j]->getTypeLoc().getSourceRange()
1000 << Types[j]->getType()
1001 << Types[i]->getType();
1002 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1003 diag::note_compat_assoc)
1004 << Types[i]->getTypeLoc().getSourceRange()
1005 << Types[i]->getType();
1006 TypeErrorFound = true;
1007 }
1008 }
1009 }
1010 }
1011 if (TypeErrorFound)
1012 return ExprError();
1013
1014 // If we determined that the generic selection is result-dependent, don't
1015 // try to compute the result expression.
1016 if (IsResultDependent)
1017 return Owned(new (Context) GenericSelectionExpr(
1018 Context, KeyLoc, ControllingExpr,
1019 Types, Exprs, NumAssocs, DefaultLoc,
1020 RParenLoc, ContainsUnexpandedParameterPack));
1021
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001022 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001023 unsigned DefaultIndex = -1U;
1024 for (unsigned i = 0; i < NumAssocs; ++i) {
1025 if (!Types[i])
1026 DefaultIndex = i;
1027 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1028 Types[i]->getType()))
1029 CompatIndices.push_back(i);
1030 }
1031
1032 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1033 // type compatible with at most one of the types named in its generic
1034 // association list."
1035 if (CompatIndices.size() > 1) {
1036 // We strip parens here because the controlling expression is typically
1037 // parenthesized in macro definitions.
1038 ControllingExpr = ControllingExpr->IgnoreParens();
1039 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1040 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1041 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001042 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001043 E = CompatIndices.end(); I != E; ++I) {
1044 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1045 diag::note_compat_assoc)
1046 << Types[*I]->getTypeLoc().getSourceRange()
1047 << Types[*I]->getType();
1048 }
1049 return ExprError();
1050 }
1051
1052 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1053 // its controlling expression shall have type compatible with exactly one of
1054 // the types named in its generic association list."
1055 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1056 // We strip parens here because the controlling expression is typically
1057 // parenthesized in macro definitions.
1058 ControllingExpr = ControllingExpr->IgnoreParens();
1059 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1060 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1061 return ExprError();
1062 }
1063
1064 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1065 // type name that is compatible with the type of the controlling expression,
1066 // then the result expression of the generic selection is the expression
1067 // in that generic association. Otherwise, the result expression of the
1068 // generic selection is the expression in the default generic association."
1069 unsigned ResultIndex =
1070 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1071
1072 return Owned(new (Context) GenericSelectionExpr(
1073 Context, KeyLoc, ControllingExpr,
1074 Types, Exprs, NumAssocs, DefaultLoc,
1075 RParenLoc, ContainsUnexpandedParameterPack,
1076 ResultIndex));
1077}
1078
Steve Naroff83895f72007-09-16 03:34:24 +00001079/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001080/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1081/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1082/// multiple tokens. However, the common case is that StringToks points to one
1083/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001084///
John McCalldadc5752010-08-24 06:29:42 +00001085ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001086Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001087 assert(NumStringToks && "Must have at least one string!");
1088
Chris Lattner8a24e582009-01-16 18:51:42 +00001089 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001090 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001091 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001092
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001093 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001094 for (unsigned i = 0; i != NumStringToks; ++i)
1095 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001096
Chris Lattner36fc8792008-02-11 00:02:17 +00001097 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001098 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001099 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001100 else if (Literal.isUTF16())
1101 StrTy = Context.Char16Ty;
1102 else if (Literal.isUTF32())
1103 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001104 else if (Literal.Pascal)
1105 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001106
Douglas Gregorfb65e592011-07-27 05:40:30 +00001107 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1108 if (Literal.isWide())
1109 Kind = StringLiteral::Wide;
1110 else if (Literal.isUTF8())
1111 Kind = StringLiteral::UTF8;
1112 else if (Literal.isUTF16())
1113 Kind = StringLiteral::UTF16;
1114 else if (Literal.isUTF32())
1115 Kind = StringLiteral::UTF32;
1116
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001117 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001118 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001119 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001120
Chris Lattner36fc8792008-02-11 00:02:17 +00001121 // Get an array type for the string, according to C99 6.4.5. This includes
1122 // the nul terminator character as well as the string length for pascal
1123 // strings.
1124 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001125 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001126 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner5b183d82006-11-10 05:03:26 +00001128 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001129 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001130 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001131 &StringTokLocs[0],
1132 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001133}
1134
John McCallc63de662011-02-02 13:00:07 +00001135enum CaptureResult {
1136 /// No capture is required.
1137 CR_NoCapture,
1138
1139 /// A capture is required.
1140 CR_Capture,
1141
John McCall351762c2011-02-07 10:33:21 +00001142 /// A by-ref capture is required.
1143 CR_CaptureByRef,
1144
John McCallc63de662011-02-02 13:00:07 +00001145 /// An error occurred when trying to capture the given variable.
1146 CR_Error
1147};
1148
1149/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001150///
John McCallc63de662011-02-02 13:00:07 +00001151/// \param var - the variable referenced
1152/// \param DC - the context which we couldn't capture through
1153static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001154diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001155 VarDecl *var, DeclContext *DC) {
1156 switch (S.ExprEvalContexts.back().Context) {
1157 case Sema::Unevaluated:
1158 // The argument will never be evaluated, so don't complain.
1159 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001160
John McCallc63de662011-02-02 13:00:07 +00001161 case Sema::PotentiallyEvaluated:
1162 case Sema::PotentiallyEvaluatedIfUsed:
1163 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001164
John McCallc63de662011-02-02 13:00:07 +00001165 case Sema::PotentiallyPotentiallyEvaluated:
1166 // FIXME: delay these!
1167 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
John McCallc63de662011-02-02 13:00:07 +00001170 // Don't diagnose about capture if we're not actually in code right
1171 // now; in general, there are more appropriate places that will
1172 // diagnose this.
1173 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1174
John McCall92d627e2011-03-22 23:15:50 +00001175 // Certain madnesses can happen with parameter declarations, which
1176 // we want to ignore.
1177 if (isa<ParmVarDecl>(var)) {
1178 // - If the parameter still belongs to the translation unit, then
1179 // we're actually just using one parameter in the declaration of
1180 // the next. This is useful in e.g. VLAs.
1181 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1182 return CR_NoCapture;
1183
1184 // - This particular madness can happen in ill-formed default
1185 // arguments; claim it's okay and let downstream code handle it.
1186 if (S.CurContext == var->getDeclContext()->getParent())
1187 return CR_NoCapture;
1188 }
John McCallc63de662011-02-02 13:00:07 +00001189
1190 DeclarationName functionName;
1191 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1192 functionName = fn->getDeclName();
1193 // FIXME: variable from enclosing block that we couldn't capture from!
1194
1195 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1196 << var->getIdentifier() << functionName;
1197 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1198 << var->getIdentifier();
1199
1200 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001201}
1202
John McCall351762c2011-02-07 10:33:21 +00001203/// There is a well-formed capture at a particular scope level;
1204/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001205static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1206 const BlockDecl::Capture &Capture) {
1207 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001208
1209 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001210 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001211 i != e; ++i) {
1212 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1213 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001214 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1215 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001216 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1217 }
1218
Richard Trieuba63ce62011-09-09 01:45:06 +00001219 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001220}
1221
1222/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001223/// given value in the current context requires a variable capture.
1224///
1225/// This also keeps the captures set in the BlockScopeInfo records
1226/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001227static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001228 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001229 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001230 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001231 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001232
1233 // Fast path: variables from the current context never require capture.
1234 DeclContext *DC = S.CurContext;
1235 if (var->getDeclContext() == DC) return CR_NoCapture;
1236
1237 // Only variables with local storage require capture.
1238 // FIXME: What about 'const' variables in C++?
1239 if (!var->hasLocalStorage()) return CR_NoCapture;
1240
1241 // Otherwise, we need to capture.
1242
1243 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001244 do {
1245 // Only blocks (and eventually C++0x closures) can capture; other
1246 // scopes don't work.
1247 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001248 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001249
1250 BlockScopeInfo *blockScope =
1251 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1252 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1253
John McCall351762c2011-02-07 10:33:21 +00001254 // Check whether we've already captured it in this block. If so,
1255 // we're done.
1256 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1257 return propagateCapture(S, functionScopesIndex,
1258 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001259
1260 functionScopesIndex--;
1261 DC = cast<BlockDecl>(DC)->getDeclContext();
1262 } while (var->getDeclContext() != DC);
1263
John McCall351762c2011-02-07 10:33:21 +00001264 // Okay, we descended all the way to the block that defines the variable.
1265 // Actually try to capture it.
1266 QualType type = var->getType();
1267
1268 // Prohibit variably-modified types.
1269 if (type->isVariablyModifiedType()) {
1270 S.Diag(loc, diag::err_ref_vm_type);
1271 S.Diag(var->getLocation(), diag::note_declared_at);
1272 return CR_Error;
1273 }
1274
1275 // Prohibit arrays, even in __block variables, but not references to
1276 // them.
1277 if (type->isArrayType()) {
1278 S.Diag(loc, diag::err_ref_array_type);
1279 S.Diag(var->getLocation(), diag::note_declared_at);
1280 return CR_Error;
1281 }
1282
1283 S.MarkDeclarationReferenced(loc, var);
1284
1285 // The BlocksAttr indicates the variable is bound by-reference.
1286 bool byRef = var->hasAttr<BlocksAttr>();
1287
1288 // Build a copy expression.
1289 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001290 const RecordType *rtype;
1291 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1292 (rtype = type->getAs<RecordType>())) {
1293
1294 // The capture logic needs the destructor, so make sure we mark it.
1295 // Usually this is unnecessary because most local variables have
1296 // their destructors marked at declaration time, but parameters are
1297 // an exception because it's technically only the call site that
1298 // actually requires the destructor.
1299 if (isa<ParmVarDecl>(var))
1300 S.FinalizeVarWithDestructor(var, rtype);
1301
John McCall351762c2011-02-07 10:33:21 +00001302 // According to the blocks spec, the capture of a variable from
1303 // the stack requires a const copy constructor. This is not true
1304 // of the copy/move done to move a __block variable to the heap.
1305 type.addConst();
1306
1307 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1308 ExprResult result =
1309 S.PerformCopyInitialization(
1310 InitializedEntity::InitializeBlock(var->getLocation(),
1311 type, false),
1312 loc, S.Owned(declRef));
1313
1314 // Build a full-expression copy expression if initialization
1315 // succeeded and used a non-trivial constructor. Recover from
1316 // errors by pretending that the copy isn't necessary.
1317 if (!result.isInvalid() &&
1318 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1319 result = S.MaybeCreateExprWithCleanups(result);
1320 copyExpr = result.take();
1321 }
1322 }
1323
1324 // We're currently at the declarer; go back to the closure.
1325 functionScopesIndex++;
1326 BlockScopeInfo *blockScope =
1327 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1328
1329 // Build a valid capture in this scope.
1330 blockScope->Captures.push_back(
1331 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1332 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1333
1334 // Propagate that to inner captures if necessary.
1335 return propagateCapture(S, functionScopesIndex,
1336 blockScope->Captures.back());
1337}
1338
Richard Trieuba63ce62011-09-09 01:45:06 +00001339static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001340 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001341 bool ByRef) {
1342 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001343
Richard Trieuba63ce62011-09-09 01:45:06 +00001344 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001345 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001346 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001347
1348 QualType exprType = var->getType().getNonReferenceType();
1349
1350 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001351 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001352 // The variable will be bound by copy; make it const within the
1353 // closure, but record that this was done in the expression.
1354 bool constAdded = !exprType.isConstQualified();
1355 exprType.addConst();
1356
1357 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1358 NameInfo.getLoc(), false,
1359 constAdded);
1360 } else {
1361 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1362 NameInfo.getLoc(), true);
1363 }
1364
1365 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001366}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001367
John McCalldadc5752010-08-24 06:29:42 +00001368ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001369Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001370 SourceLocation Loc,
1371 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001372 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001373 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001374}
1375
John McCallf4cd4f92011-02-09 01:13:10 +00001376/// BuildDeclRefExpr - Build an expression that references a
1377/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001378ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001379Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001380 const DeclarationNameInfo &NameInfo,
1381 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001382 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001383
John McCall086a4642010-11-24 05:12:34 +00001384 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001385 SS? SS->getWithLocInContext(Context)
1386 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001387 D, NameInfo, Ty, VK);
1388
1389 // Just in case we're building an illegal pointer-to-member.
1390 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1391 E->setObjectKind(OK_BitField);
1392
1393 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001394}
1395
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001396/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001397/// possibly a list of template arguments.
1398///
1399/// If this produces template arguments, it is permitted to call
1400/// DecomposeTemplateName.
1401///
1402/// This actually loses a lot of source location information for
1403/// non-standard name kinds; we should consider preserving that in
1404/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001405void
1406Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1407 TemplateArgumentListInfo &Buffer,
1408 DeclarationNameInfo &NameInfo,
1409 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001410 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1411 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1412 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1413
Douglas Gregor5476205b2011-06-23 00:49:38 +00001414 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001415 Id.TemplateId->getTemplateArgs(),
1416 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001417 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001418 TemplateArgsPtr.release();
1419
John McCall3e56fd42010-08-23 07:28:44 +00001420 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001421 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001422 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001423 TemplateArgs = &Buffer;
1424 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001425 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001426 TemplateArgs = 0;
1427 }
1428}
1429
John McCalld681c392009-12-16 08:11:27 +00001430/// Diagnose an empty lookup.
1431///
1432/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001433bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001434 CorrectTypoContext CTC,
1435 TemplateArgumentListInfo *ExplicitTemplateArgs,
1436 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001437 DeclarationName Name = R.getLookupName();
1438
John McCalld681c392009-12-16 08:11:27 +00001439 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001440 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001441 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1442 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001443 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001444 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001445 diagnostic_suggest = diag::err_undeclared_use_suggest;
1446 }
John McCalld681c392009-12-16 08:11:27 +00001447
Douglas Gregor598b08f2009-12-31 05:20:13 +00001448 // If the original lookup was an unqualified lookup, fake an
1449 // unqualified lookup. This is useful when (for example) the
1450 // original lookup would not have found something because it was a
1451 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001452 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001453 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001454 if (isa<CXXRecordDecl>(DC)) {
1455 LookupQualifiedName(R, DC);
1456
1457 if (!R.empty()) {
1458 // Don't give errors about ambiguities in this lookup.
1459 R.suppressDiagnostics();
1460
1461 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1462 bool isInstance = CurMethod &&
1463 CurMethod->isInstance() &&
1464 DC == CurMethod->getParent();
1465
1466 // Give a code modification hint to insert 'this->'.
1467 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1468 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001469 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001470 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1471 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001472 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001473 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001474 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001475 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001476 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001477 Diag(R.getNameLoc(), diagnostic) << Name
1478 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1479 QualType DepThisType = DepMethod->getThisType(Context);
1480 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1481 R.getNameLoc(), DepThisType, false);
1482 TemplateArgumentListInfo TList;
1483 if (ULE->hasExplicitTemplateArgs())
1484 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001485
Douglas Gregore16af532011-02-28 18:50:33 +00001486 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001487 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001488 CXXDependentScopeMemberExpr *DepExpr =
1489 CXXDependentScopeMemberExpr::Create(
1490 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001491 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001492 R.getLookupNameInfo(),
1493 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001494 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001495 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001496 // FIXME: we should be able to handle this case too. It is correct
1497 // to add this-> here. This is a workaround for PR7947.
1498 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001499 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001500 } else {
John McCalld681c392009-12-16 08:11:27 +00001501 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001502 }
John McCalld681c392009-12-16 08:11:27 +00001503
1504 // Do we really want to note all of these?
1505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1506 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1507
1508 // Tell the callee to try to recover.
1509 return false;
1510 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001511
1512 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001513 }
1514 }
1515
Douglas Gregor598b08f2009-12-31 05:20:13 +00001516 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001517 TypoCorrection Corrected;
1518 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1519 S, &SS, NULL, false, CTC))) {
1520 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1521 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1522 R.setLookupName(Corrected.getCorrection());
1523
Hans Wennborg38198de2011-07-12 08:45:31 +00001524 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001525 if (Corrected.isOverloaded()) {
1526 OverloadCandidateSet OCS(R.getNameLoc());
1527 OverloadCandidateSet::iterator Best;
1528 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1529 CDEnd = Corrected.end();
1530 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001531 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001532 dyn_cast<FunctionTemplateDecl>(*CD))
1533 AddTemplateOverloadCandidate(
1534 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1535 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001536 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1537 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1538 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1539 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001540 }
1541 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1542 case OR_Success:
1543 ND = Best->Function;
1544 break;
1545 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001546 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001547 }
1548 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001549 R.addDecl(ND);
1550 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001551 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001552 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1553 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001554 else
1555 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001556 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001557 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001558 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1559 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001560 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001561 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001562
1563 // Tell the callee to try to recover.
1564 return false;
1565 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001566
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001567 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001568 // FIXME: If we ended up with a typo for a type name or
1569 // Objective-C class name, we're in trouble because the parser
1570 // is in the wrong place to recover. Suggest the typo
1571 // correction, but don't make it a fix-it since we're not going
1572 // to recover well anyway.
1573 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001574 Diag(R.getNameLoc(), diagnostic_suggest)
1575 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001576 else
1577 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001578 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001579 << SS.getRange();
1580
1581 // Don't try to recover; it won't work.
1582 return true;
1583 }
1584 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001585 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001586 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001587 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001588 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001589 else
Douglas Gregor25363982010-01-01 00:15:04 +00001590 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001591 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001592 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001593 return true;
1594 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001595 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001596 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001597
1598 // Emit a special diagnostic for failed member lookups.
1599 // FIXME: computing the declaration context might fail here (?)
1600 if (!SS.isEmpty()) {
1601 Diag(R.getNameLoc(), diag::err_no_member)
1602 << Name << computeDeclContext(SS, false)
1603 << SS.getRange();
1604 return true;
1605 }
1606
John McCalld681c392009-12-16 08:11:27 +00001607 // Give up, we can't recover.
1608 Diag(R.getNameLoc(), diagnostic) << Name;
1609 return true;
1610}
1611
John McCalldadc5752010-08-24 06:29:42 +00001612ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001613 CXXScopeSpec &SS,
1614 UnqualifiedId &Id,
1615 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001616 bool IsAddressOfOperand) {
1617 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001618 "cannot be direct & operand and have a trailing lparen");
1619
1620 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001621 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001622
John McCall10eae182009-11-30 22:42:35 +00001623 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001624
1625 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001627 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001628 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001629
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001631 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001632 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001633
John McCalle66edc12009-11-24 19:00:30 +00001634 // C++ [temp.dep.expr]p3:
1635 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001636 // -- an identifier that was declared with a dependent type,
1637 // (note: handled after lookup)
1638 // -- a template-id that is dependent,
1639 // (note: handled in BuildTemplateIdExpr)
1640 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001641 // -- a nested-name-specifier that contains a class-name that
1642 // names a dependent type.
1643 // Determine whether this is a member of an unknown specialization;
1644 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001645 bool DependentID = false;
1646 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1647 Name.getCXXNameType()->isDependentType()) {
1648 DependentID = true;
1649 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001650 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001651 if (RequireCompleteDeclContext(SS, DC))
1652 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001653 } else {
1654 DependentID = true;
1655 }
1656 }
1657
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001658 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001659 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001660 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001661
Fariborz Jahanian86151342010-07-22 23:33:21 +00001662 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001663 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001664 LookupResult R(*this, NameInfo,
1665 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1666 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001667 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001668 // Lookup the template name again to correctly establish the context in
1669 // which it was found. This is really unfortunate as we already did the
1670 // lookup to determine that it was a template name in the first place. If
1671 // this becomes a performance hit, we can work harder to preserve those
1672 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001673 bool MemberOfUnknownSpecialization;
1674 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1675 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001676
1677 if (MemberOfUnknownSpecialization ||
1678 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001679 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001680 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001681 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001682 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001683 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregora5226932011-02-04 13:35:07 +00001685 // If the result might be in a dependent base class, this is a dependent
1686 // id-expression.
1687 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001688 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001689 TemplateArgs);
1690
John McCalle66edc12009-11-24 19:00:30 +00001691 // If this reference is in an Objective-C method, then we need to do
1692 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001693 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001694 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001695 if (E.isInvalid())
1696 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001697
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001698 if (Expr *Ex = E.takeAs<Expr>())
1699 return Owned(Ex);
1700
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001701 // for further use, this must be set to false if in class method.
1702 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001703 }
Chris Lattner59a25942008-03-31 00:36:02 +00001704 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001705
John McCalle66edc12009-11-24 19:00:30 +00001706 if (R.isAmbiguous())
1707 return ExprError();
1708
Douglas Gregor171c45a2009-02-18 21:56:37 +00001709 // Determine whether this name might be a candidate for
1710 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001711 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001712
John McCalle66edc12009-11-24 19:00:30 +00001713 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001714 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001715 // in C90, extension in C99, forbidden in C++).
1716 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1717 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1718 if (D) R.addDecl(D);
1719 }
1720
1721 // If this name wasn't predeclared and if this is not a function
1722 // call, diagnose the problem.
1723 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001724
1725 // In Microsoft mode, if we are inside a template class member function
1726 // and we can't resolve an identifier then assume the identifier is type
1727 // dependent. The goal is to postpone name lookup to instantiation time
1728 // to be able to search into type dependent base classes.
1729 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1730 isa<CXXMethodDecl>(CurContext))
1731 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1732 TemplateArgs);
1733
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001734 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001735 return ExprError();
1736
1737 assert(!R.empty() &&
1738 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001739
1740 // If we found an Objective-C instance variable, let
1741 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001742 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001743 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1744 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001745 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001746 // In a hopelessly buggy code, Objective-C instance variable
1747 // lookup fails and no expression will be built to reference it.
1748 if (!E.isInvalid() && !E.get())
1749 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001750 return move(E);
1751 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001752 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001753 }
Mike Stump11289f42009-09-09 15:08:12 +00001754
John McCalle66edc12009-11-24 19:00:30 +00001755 // This is guaranteed from this point on.
1756 assert(!R.empty() || ADL);
1757
John McCall2d74de92009-12-01 22:10:20 +00001758 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001759 // C++ [class.mfct.non-static]p3:
1760 // When an id-expression that is not part of a class member access
1761 // syntax and not used to form a pointer to member is used in the
1762 // body of a non-static member function of class X, if name lookup
1763 // resolves the name in the id-expression to a non-static non-type
1764 // member of some class C, the id-expression is transformed into a
1765 // class member access expression using (*this) as the
1766 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001767 //
1768 // But we don't actually need to do this for '&' operands if R
1769 // resolved to a function or overloaded function set, because the
1770 // expression is ill-formed if it actually works out to be a
1771 // non-static member function:
1772 //
1773 // C++ [expr.ref]p4:
1774 // Otherwise, if E1.E2 refers to a non-static member function. . .
1775 // [t]he expression can be used only as the left-hand operand of a
1776 // member function call.
1777 //
1778 // There are other safeguards against such uses, but it's important
1779 // to get this right here so that we don't end up making a
1780 // spuriously dependent expression if we're inside a dependent
1781 // instance method.
John McCall57500772009-12-16 12:17:52 +00001782 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001783 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001784 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001785 MightBeImplicitMember = true;
1786 else if (!SS.isEmpty())
1787 MightBeImplicitMember = false;
1788 else if (R.isOverloadedResult())
1789 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001790 else if (R.isUnresolvableResult())
1791 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001792 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001793 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1794 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001795
1796 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001797 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001798 }
1799
John McCalle66edc12009-11-24 19:00:30 +00001800 if (TemplateArgs)
1801 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001802
John McCalle66edc12009-11-24 19:00:30 +00001803 return BuildDeclarationNameExpr(SS, R, ADL);
1804}
1805
John McCall10eae182009-11-30 22:42:35 +00001806/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1807/// declaration name, generally during template instantiation.
1808/// There's a large number of things which don't need to be done along
1809/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001810ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001811Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001812 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001813 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001814 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001815 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001816
John McCall0b66eb32010-05-01 00:40:08 +00001817 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001818 return ExprError();
1819
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001820 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001821 LookupQualifiedName(R, DC);
1822
1823 if (R.isAmbiguous())
1824 return ExprError();
1825
1826 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001827 Diag(NameInfo.getLoc(), diag::err_no_member)
1828 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001829 return ExprError();
1830 }
1831
1832 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1833}
1834
1835/// LookupInObjCMethod - The parser has read a name in, and Sema has
1836/// detected that we're currently inside an ObjC method. Perform some
1837/// additional lookup.
1838///
1839/// Ideally, most of this would be done by lookup, but there's
1840/// actually quite a lot of extra work involved.
1841///
1842/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001843ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001844Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001845 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001846 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001847 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001848
John McCalle66edc12009-11-24 19:00:30 +00001849 // There are two cases to handle here. 1) scoped lookup could have failed,
1850 // in which case we should look for an ivar. 2) scoped lookup could have
1851 // found a decl, but that decl is outside the current instance method (i.e.
1852 // a global variable). In these two cases, we do a lookup for an ivar with
1853 // this name, if the lookup sucedes, we replace it our current decl.
1854
1855 // If we're in a class method, we don't normally want to look for
1856 // ivars. But if we don't find anything else, and there's an
1857 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001858 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001859
1860 bool LookForIvars;
1861 if (Lookup.empty())
1862 LookForIvars = true;
1863 else if (IsClassMethod)
1864 LookForIvars = false;
1865 else
1866 LookForIvars = (Lookup.isSingleResult() &&
1867 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001868 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001869 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001870 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001871 ObjCInterfaceDecl *ClassDeclared;
1872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1873 // Diagnose using an ivar in a class method.
1874 if (IsClassMethod)
1875 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1876 << IV->getDeclName());
1877
1878 // If we're referencing an invalid decl, just return this as a silent
1879 // error node. The error diagnostic was already emitted on the decl.
1880 if (IV->isInvalidDecl())
1881 return ExprError();
1882
1883 // Check if referencing a field with __attribute__((deprecated)).
1884 if (DiagnoseUseOfDecl(IV, Loc))
1885 return ExprError();
1886
1887 // Diagnose the use of an ivar outside of the declaring class.
1888 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1889 ClassDeclared != IFace)
1890 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1891
1892 // FIXME: This should use a new expr for a direct reference, don't
1893 // turn this into Self->ivar, just return a BareIVarExpr or something.
1894 IdentifierInfo &II = Context.Idents.get("self");
1895 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001896 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001897 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001898 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001899 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001900 SelfName, false, false);
1901 if (SelfExpr.isInvalid())
1902 return ExprError();
1903
John Wiegley01296292011-04-08 18:41:53 +00001904 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1905 if (SelfExpr.isInvalid())
1906 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001907
John McCalle66edc12009-11-24 19:00:30 +00001908 MarkDeclarationReferenced(Loc, IV);
1909 return Owned(new (Context)
1910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001911 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001912 }
Chris Lattner87313662010-04-12 05:10:17 +00001913 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001914 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001915 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001916 ObjCInterfaceDecl *ClassDeclared;
1917 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1918 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1919 IFace == ClassDeclared)
1920 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1921 }
1922 }
1923
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001924 if (Lookup.empty() && II && AllowBuiltinCreation) {
1925 // FIXME. Consolidate this with similar code in LookupName.
1926 if (unsigned BuiltinID = II->getBuiltinID()) {
1927 if (!(getLangOptions().CPlusPlus &&
1928 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1929 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1930 S, Lookup.isForRedeclaration(),
1931 Lookup.getNameLoc());
1932 if (D) Lookup.addDecl(D);
1933 }
1934 }
1935 }
John McCalle66edc12009-11-24 19:00:30 +00001936 // Sentinel value saying that we didn't do anything special.
1937 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001938}
John McCalld14a8642009-11-21 08:51:07 +00001939
John McCall16df1e52010-03-30 21:47:33 +00001940/// \brief Cast a base object to a member's actual type.
1941///
1942/// Logically this happens in three phases:
1943///
1944/// * First we cast from the base type to the naming class.
1945/// The naming class is the class into which we were looking
1946/// when we found the member; it's the qualifier type if a
1947/// qualifier was provided, and otherwise it's the base type.
1948///
1949/// * Next we cast from the naming class to the declaring class.
1950/// If the member we found was brought into a class's scope by
1951/// a using declaration, this is that class; otherwise it's
1952/// the class declaring the member.
1953///
1954/// * Finally we cast from the declaring class to the "true"
1955/// declaring class of the member. This conversion does not
1956/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001957ExprResult
1958Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001960 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001961 NamedDecl *Member) {
1962 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1963 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001964 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001965
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 QualType DestRecordType;
1967 QualType DestType;
1968 QualType FromRecordType;
1969 QualType FromType = From->getType();
1970 bool PointerConversions = false;
1971 if (isa<FieldDecl>(Member)) {
1972 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 if (FromType->getAs<PointerType>()) {
1975 DestType = Context.getPointerType(DestRecordType);
1976 FromRecordType = FromType->getPointeeType();
1977 PointerConversions = true;
1978 } else {
1979 DestType = DestRecordType;
1980 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001981 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001982 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1983 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001984 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001985
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 DestType = Method->getThisType(Context);
1987 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001988
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 if (FromType->getAs<PointerType>()) {
1990 FromRecordType = FromType->getPointeeType();
1991 PointerConversions = true;
1992 } else {
1993 FromRecordType = FromType;
1994 DestType = DestRecordType;
1995 }
1996 } else {
1997 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001998 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001999 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002000
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002001 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002002 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002003
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002004 // If the unqualified types are the same, no conversion is necessary.
2005 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002006 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002007
John McCall16df1e52010-03-30 21:47:33 +00002008 SourceRange FromRange = From->getSourceRange();
2009 SourceLocation FromLoc = FromRange.getBegin();
2010
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002011 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002012
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002014 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002015 // class name.
2016 //
2017 // If the member was a qualified name and the qualified referred to a
2018 // specific base subobject type, we'll cast to that intermediate type
2019 // first and then to the object in which the member is declared. That allows
2020 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2021 //
2022 // class Base { public: int x; };
2023 // class Derived1 : public Base { };
2024 // class Derived2 : public Base { };
2025 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2026 //
2027 // void VeryDerived::f() {
2028 // x = 17; // error: ambiguous base subobjects
2029 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2030 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002031 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002032 QualType QType = QualType(Qualifier->getAsType(), 0);
2033 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2034 assert(QType->isRecordType() && "lookup done with non-record type");
2035
2036 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2037
2038 // In C++98, the qualifier type doesn't actually have to be a base
2039 // type of the object type, in which case we just ignore it.
2040 // Otherwise build the appropriate casts.
2041 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002045 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002046
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002047 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002048 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002049 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2050 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002051
2052 FromType = QType;
2053 FromRecordType = QRecordType;
2054
2055 // If the qualifier type was the same as the destination type,
2056 // we're done.
2057 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002058 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002059 }
2060 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002061
John McCall16df1e52010-03-30 21:47:33 +00002062 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002063
John McCall16df1e52010-03-30 21:47:33 +00002064 // If we actually found the member through a using declaration, cast
2065 // down to the using declaration's type.
2066 //
2067 // Pointer equality is fine here because only one declaration of a
2068 // class ever has member declarations.
2069 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2070 assert(isa<UsingShadowDecl>(FoundDecl));
2071 QualType URecordType = Context.getTypeDeclType(
2072 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2073
2074 // We only need to do this if the naming-class to declaring-class
2075 // conversion is non-trivial.
2076 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2077 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002078 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002079 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002080 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002081 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002082
John McCall16df1e52010-03-30 21:47:33 +00002083 QualType UType = URecordType;
2084 if (PointerConversions)
2085 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002086 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2087 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002088 FromType = UType;
2089 FromRecordType = URecordType;
2090 }
2091
2092 // We don't do access control for the conversion from the
2093 // declaring class to the true declaring class.
2094 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002095 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002096
John McCallcf142162010-08-07 06:22:56 +00002097 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002098 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2099 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002100 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002101 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002102
John Wiegley01296292011-04-08 18:41:53 +00002103 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2104 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002105}
Douglas Gregor3256d042009-06-30 15:47:41 +00002106
John McCalle66edc12009-11-24 19:00:30 +00002107bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002108 const LookupResult &R,
2109 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002110 // Only when used directly as the postfix-expression of a call.
2111 if (!HasTrailingLParen)
2112 return false;
2113
2114 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002115 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002116 return false;
2117
2118 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002119 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002120 return false;
2121
2122 // Turn off ADL when we find certain kinds of declarations during
2123 // normal lookup:
2124 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2125 NamedDecl *D = *I;
2126
2127 // C++0x [basic.lookup.argdep]p3:
2128 // -- a declaration of a class member
2129 // Since using decls preserve this property, we check this on the
2130 // original decl.
John McCall57500772009-12-16 12:17:52 +00002131 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002132 return false;
2133
2134 // C++0x [basic.lookup.argdep]p3:
2135 // -- a block-scope function declaration that is not a
2136 // using-declaration
2137 // NOTE: we also trigger this for function templates (in fact, we
2138 // don't check the decl type at all, since all other decl types
2139 // turn off ADL anyway).
2140 if (isa<UsingShadowDecl>(D))
2141 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2142 else if (D->getDeclContext()->isFunctionOrMethod())
2143 return false;
2144
2145 // C++0x [basic.lookup.argdep]p3:
2146 // -- a declaration that is neither a function or a function
2147 // template
2148 // And also for builtin functions.
2149 if (isa<FunctionDecl>(D)) {
2150 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2151
2152 // But also builtin functions.
2153 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2154 return false;
2155 } else if (!isa<FunctionTemplateDecl>(D))
2156 return false;
2157 }
2158
2159 return true;
2160}
2161
2162
John McCalld14a8642009-11-21 08:51:07 +00002163/// Diagnoses obvious problems with the use of the given declaration
2164/// as an expression. This is only actually called for lookups that
2165/// were not overloaded, and it doesn't promise that the declaration
2166/// will in fact be used.
2167static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002168 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002169 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2170 return true;
2171 }
2172
2173 if (isa<ObjCInterfaceDecl>(D)) {
2174 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2175 return true;
2176 }
2177
2178 if (isa<NamespaceDecl>(D)) {
2179 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2180 return true;
2181 }
2182
2183 return false;
2184}
2185
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002188 LookupResult &R,
2189 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002190 // If this is a single, fully-resolved result and we don't need ADL,
2191 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002192 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002193 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2194 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002195
2196 // We only need to check the declaration if there's exactly one
2197 // result, because in the overloaded case the results can only be
2198 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002199 if (R.isSingleResult() &&
2200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002201 return ExprError();
2202
John McCall58cc69d2010-01-27 01:50:18 +00002203 // Otherwise, just build an unresolved lookup expression. Suppress
2204 // any lookup-related diagnostics; we'll hash these out later, when
2205 // we've picked a target.
2206 R.suppressDiagnostics();
2207
John McCalld14a8642009-11-21 08:51:07 +00002208 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002210 SS.getWithLocInContext(Context),
2211 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002212 NeedsADL, R.isOverloadedResult(),
2213 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002214
2215 return Owned(ULE);
2216}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002217
John McCalld14a8642009-11-21 08:51:07 +00002218/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002219ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002220Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002221 const DeclarationNameInfo &NameInfo,
2222 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002223 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002224 assert(!isa<FunctionTemplateDecl>(D) &&
2225 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002226
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002227 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002228 if (CheckDeclInExpr(*this, Loc, D))
2229 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002230
Douglas Gregore7488b92009-12-01 16:58:18 +00002231 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2232 // Specifically diagnose references to class templates that are missing
2233 // a template argument list.
2234 Diag(Loc, diag::err_template_decl_ref)
2235 << Template << SS.getRange();
2236 Diag(Template->getLocation(), diag::note_template_decl_here);
2237 return ExprError();
2238 }
2239
2240 // Make sure that we're referring to a value.
2241 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2242 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002243 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002244 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002245 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002246 return ExprError();
2247 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002248
Douglas Gregor171c45a2009-02-18 21:56:37 +00002249 // Check whether this declaration can be used. Note that we suppress
2250 // this check when we're going to perform argument-dependent lookup
2251 // on this function name, because this might not be the function
2252 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002253 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002254 return ExprError();
2255
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002256 // Only create DeclRefExpr's for valid Decl's.
2257 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002258 return ExprError();
2259
John McCallf3a88602011-02-03 08:15:49 +00002260 // Handle members of anonymous structs and unions. If we got here,
2261 // and the reference is to a class member indirect field, then this
2262 // must be the subject of a pointer-to-member expression.
2263 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2264 if (!indirectField->isCXXClassMember())
2265 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2266 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002267
Chris Lattner2a9d9892008-10-20 05:16:36 +00002268 // If the identifier reference is inside a block, and it refers to a value
2269 // that is outside the block, create a BlockDeclRefExpr instead of a
2270 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2271 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002272 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002273 // We do not do this for things like enum constants, global variables, etc,
2274 // as they do not get snapshotted.
2275 //
John McCall351762c2011-02-07 10:33:21 +00002276 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002277 case CR_Error:
2278 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002279
John McCallc63de662011-02-02 13:00:07 +00002280 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002281 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2282 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2283
2284 case CR_CaptureByRef:
2285 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2286 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002287
2288 case CR_NoCapture: {
2289 // If this reference is not in a block or if the referenced
2290 // variable is within the block, create a normal DeclRefExpr.
2291
2292 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002293 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002294
2295 switch (D->getKind()) {
2296 // Ignore all the non-ValueDecl kinds.
2297#define ABSTRACT_DECL(kind)
2298#define VALUE(type, base)
2299#define DECL(type, base) \
2300 case Decl::type:
2301#include "clang/AST/DeclNodes.inc"
2302 llvm_unreachable("invalid value decl kind");
2303 return ExprError();
2304
2305 // These shouldn't make it here.
2306 case Decl::ObjCAtDefsField:
2307 case Decl::ObjCIvar:
2308 llvm_unreachable("forming non-member reference to ivar?");
2309 return ExprError();
2310
2311 // Enum constants are always r-values and never references.
2312 // Unresolved using declarations are dependent.
2313 case Decl::EnumConstant:
2314 case Decl::UnresolvedUsingValue:
2315 valueKind = VK_RValue;
2316 break;
2317
2318 // Fields and indirect fields that got here must be for
2319 // pointer-to-member expressions; we just call them l-values for
2320 // internal consistency, because this subexpression doesn't really
2321 // exist in the high-level semantics.
2322 case Decl::Field:
2323 case Decl::IndirectField:
2324 assert(getLangOptions().CPlusPlus &&
2325 "building reference to field in C?");
2326
2327 // These can't have reference type in well-formed programs, but
2328 // for internal consistency we do this anyway.
2329 type = type.getNonReferenceType();
2330 valueKind = VK_LValue;
2331 break;
2332
2333 // Non-type template parameters are either l-values or r-values
2334 // depending on the type.
2335 case Decl::NonTypeTemplateParm: {
2336 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2337 type = reftype->getPointeeType();
2338 valueKind = VK_LValue; // even if the parameter is an r-value reference
2339 break;
2340 }
2341
2342 // For non-references, we need to strip qualifiers just in case
2343 // the template parameter was declared as 'const int' or whatever.
2344 valueKind = VK_RValue;
2345 type = type.getUnqualifiedType();
2346 break;
2347 }
2348
2349 case Decl::Var:
2350 // In C, "extern void blah;" is valid and is an r-value.
2351 if (!getLangOptions().CPlusPlus &&
2352 !type.hasQualifiers() &&
2353 type->isVoidType()) {
2354 valueKind = VK_RValue;
2355 break;
2356 }
2357 // fallthrough
2358
2359 case Decl::ImplicitParam:
2360 case Decl::ParmVar:
2361 // These are always l-values.
2362 valueKind = VK_LValue;
2363 type = type.getNonReferenceType();
2364 break;
2365
2366 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002367 const FunctionType *fty = type->castAs<FunctionType>();
2368
2369 // If we're referring to a function with an __unknown_anytype
2370 // result type, make the entire expression __unknown_anytype.
2371 if (fty->getResultType() == Context.UnknownAnyTy) {
2372 type = Context.UnknownAnyTy;
2373 valueKind = VK_RValue;
2374 break;
2375 }
2376
John McCallf4cd4f92011-02-09 01:13:10 +00002377 // Functions are l-values in C++.
2378 if (getLangOptions().CPlusPlus) {
2379 valueKind = VK_LValue;
2380 break;
2381 }
2382
2383 // C99 DR 316 says that, if a function type comes from a
2384 // function definition (without a prototype), that type is only
2385 // used for checking compatibility. Therefore, when referencing
2386 // the function, we pretend that we don't have the full function
2387 // type.
John McCall2979fe02011-04-12 00:42:48 +00002388 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2389 isa<FunctionProtoType>(fty))
2390 type = Context.getFunctionNoProtoType(fty->getResultType(),
2391 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002392
2393 // Functions are r-values in C.
2394 valueKind = VK_RValue;
2395 break;
2396 }
2397
2398 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002399 // If we're referring to a method with an __unknown_anytype
2400 // result type, make the entire expression __unknown_anytype.
2401 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002402 if (const FunctionProtoType *proto
2403 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002404 if (proto->getResultType() == Context.UnknownAnyTy) {
2405 type = Context.UnknownAnyTy;
2406 valueKind = VK_RValue;
2407 break;
2408 }
2409
John McCallf4cd4f92011-02-09 01:13:10 +00002410 // C++ methods are l-values if static, r-values if non-static.
2411 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2412 valueKind = VK_LValue;
2413 break;
2414 }
2415 // fallthrough
2416
2417 case Decl::CXXConversion:
2418 case Decl::CXXDestructor:
2419 case Decl::CXXConstructor:
2420 valueKind = VK_RValue;
2421 break;
2422 }
2423
2424 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2425 }
2426
John McCallc63de662011-02-02 13:00:07 +00002427 }
John McCall7decc9e2010-11-18 06:31:45 +00002428
John McCall351762c2011-02-07 10:33:21 +00002429 llvm_unreachable("unknown capture result");
2430 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002431}
Chris Lattnere168f762006-11-10 05:29:30 +00002432
John McCall2979fe02011-04-12 00:42:48 +00002433ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002434 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002435
Chris Lattnere168f762006-11-10 05:29:30 +00002436 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002437 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002438 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2439 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2440 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002441 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002442
Chris Lattnera81a0272008-01-12 08:14:25 +00002443 // Pre-defined identifiers are of type char[x], where x is the length of the
2444 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002445
Anders Carlsson2fb08242009-09-08 18:24:21 +00002446 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002447 if (!currentDecl && getCurBlock())
2448 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002449 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002450 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002451 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002452 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002453
Anders Carlsson0b209a82009-09-11 01:22:35 +00002454 QualType ResTy;
2455 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2456 ResTy = Context.DependentTy;
2457 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002458 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002459
Anders Carlsson0b209a82009-09-11 01:22:35 +00002460 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002461 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002462 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2463 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002464 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002465}
2466
John McCalldadc5752010-08-24 06:29:42 +00002467ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002468 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002469 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002470 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002471 if (Invalid)
2472 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002473
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002474 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002475 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002476 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002478
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002479 QualType Ty;
2480 if (!getLangOptions().CPlusPlus)
2481 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2482 else if (Literal.isWide())
2483 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002484 else if (Literal.isUTF16())
2485 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2486 else if (Literal.isUTF32())
2487 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002488 else if (Literal.isMultiChar())
2489 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002490 else
2491 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002492
Douglas Gregorfb65e592011-07-27 05:40:30 +00002493 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2494 if (Literal.isWide())
2495 Kind = CharacterLiteral::Wide;
2496 else if (Literal.isUTF16())
2497 Kind = CharacterLiteral::UTF16;
2498 else if (Literal.isUTF32())
2499 Kind = CharacterLiteral::UTF32;
2500
2501 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2502 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002503}
2504
John McCalldadc5752010-08-24 06:29:42 +00002505ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002506 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002507 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2508 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002509 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002510 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002511 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002512 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002513 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002514
Chris Lattner23b7eb62007-06-15 23:05:46 +00002515 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002516 // Add padding so that NumericLiteralParser can overread by one character.
2517 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002518 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002519
Chris Lattner67ca9252007-05-21 01:08:44 +00002520 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002521 bool Invalid = false;
2522 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2523 if (Invalid)
2524 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002525
Mike Stump11289f42009-09-09 15:08:12 +00002526 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002527 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002528 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529 return ExprError();
2530
Chris Lattner1c20a172007-08-26 03:42:43 +00002531 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002532
Chris Lattner1c20a172007-08-26 03:42:43 +00002533 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002534 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002535 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002536 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002537 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002538 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002539 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002540 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002541
2542 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2543
John McCall53b93a02009-12-24 09:08:04 +00002544 using llvm::APFloat;
2545 APFloat Val(Format);
2546
2547 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002548
2549 // Overflow is always an error, but underflow is only an error if
2550 // we underflowed to zero (APFloat reports denormals as underflow).
2551 if ((result & APFloat::opOverflow) ||
2552 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002553 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002554 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002555 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002556 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002557 APFloat::getLargest(Format).toString(buffer);
2558 } else {
John McCall62abc942010-02-26 23:35:57 +00002559 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002560 APFloat::getSmallest(Format).toString(buffer);
2561 }
2562
2563 Diag(Tok.getLocation(), diagnostic)
2564 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002565 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002566 }
2567
2568 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002569 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002571 if (Ty == Context.DoubleTy) {
2572 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002573 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002574 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2575 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002576 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002577 }
2578 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002579 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002580 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002581 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002582 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002583
Neil Boothac582c52007-08-29 22:00:19 +00002584 // long long is a C99 feature.
2585 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002586 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002587 Diag(Tok.getLocation(), diag::ext_longlong);
2588
Chris Lattner67ca9252007-05-21 01:08:44 +00002589 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002590 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002591
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 if (Literal.GetIntegerValue(ResultVal)) {
2593 // If this value didn't fit into uintmax_t, warn and force to ull.
2594 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002595 Ty = Context.UnsignedLongLongTy;
2596 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002597 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002598 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002599 // If this value fits into a ULL, try to figure out what else it fits into
2600 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002601
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2603 // be an unsigned int.
2604 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2605
2606 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002607 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002608 if (!Literal.isLong && !Literal.isLongLong) {
2609 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002610 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002611
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 // Does it fit in a unsigned int?
2613 if (ResultVal.isIntN(IntSize)) {
2614 // Does it fit in a signed int?
2615 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002616 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002617 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002618 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002619 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002620 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002625 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002626
Chris Lattner67ca9252007-05-21 01:08:44 +00002627 // Does it fit in a unsigned long?
2628 if (ResultVal.isIntN(LongSize)) {
2629 // Does it fit in a signed long?
2630 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002633 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002634 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002636 }
2637
Chris Lattner67ca9252007-05-21 01:08:44 +00002638 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002639 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002640 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002641
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 // Does it fit in a unsigned long long?
2643 if (ResultVal.isIntN(LongLongSize)) {
2644 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002645 // To be compatible with MSVC, hex integer literals ending with the
2646 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002647 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002648 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002649 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002651 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002652 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002653 }
2654 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // If we still couldn't decide a type, we probably have something that
2657 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002658 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002660 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002661 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002662 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002663
Chris Lattner55258cf2008-05-09 05:59:00 +00002664 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002665 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002666 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002667 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002668 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002669
Chris Lattner1c20a172007-08-26 03:42:43 +00002670 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2671 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002672 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002673 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002674
2675 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002676}
2677
Richard Trieuba63ce62011-09-09 01:45:06 +00002678ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002679 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002680 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002681}
2682
Chandler Carruth62da79c2011-05-26 08:53:12 +00002683static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2684 SourceLocation Loc,
2685 SourceRange ArgRange) {
2686 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2687 // scalar or vector data type argument..."
2688 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2689 // type (C99 6.2.5p18) or void.
2690 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2691 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2692 << T << ArgRange;
2693 return true;
2694 }
2695
2696 assert((T->isVoidType() || !T->isIncompleteType()) &&
2697 "Scalar types should always be complete");
2698 return false;
2699}
2700
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002701static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2702 SourceLocation Loc,
2703 SourceRange ArgRange,
2704 UnaryExprOrTypeTrait TraitKind) {
2705 // C99 6.5.3.4p1:
2706 if (T->isFunctionType()) {
2707 // alignof(function) is allowed as an extension.
2708 if (TraitKind == UETT_SizeOf)
2709 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2710 return false;
2711 }
2712
2713 // Allow sizeof(void)/alignof(void) as an extension.
2714 if (T->isVoidType()) {
2715 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2716 return false;
2717 }
2718
2719 return true;
2720}
2721
2722static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2723 SourceLocation Loc,
2724 SourceRange ArgRange,
2725 UnaryExprOrTypeTrait TraitKind) {
2726 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2727 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2728 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2729 << T << (TraitKind == UETT_SizeOf)
2730 << ArgRange;
2731 return true;
2732 }
2733
2734 return false;
2735}
2736
Chandler Carruth14502c22011-05-26 08:53:10 +00002737/// \brief Check the constrains on expression operands to unary type expression
2738/// and type traits.
2739///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002740/// Completes any types necessary and validates the constraints on the operand
2741/// expression. The logic mostly mirrors the type-based overload, but may modify
2742/// the expression as it completes the type for that expression through template
2743/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002744bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002745 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002746 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002747
2748 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2749 // the result is the size of the referenced type."
2750 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2751 // result shall be the alignment of the referenced type."
2752 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2753 ExprTy = Ref->getPointeeType();
2754
2755 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002756 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2757 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002758
2759 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002760 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2761 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002762 return false;
2763
Richard Trieuba63ce62011-09-09 01:45:06 +00002764 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002766 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002767 std::make_pair(SourceLocation(), PDiag(0))))
2768 return true;
2769
2770 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002771 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002772 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2773 ExprTy = Ref->getPointeeType();
2774
Richard Trieuba63ce62011-09-09 01:45:06 +00002775 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2776 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002777 return true;
2778
Nico Weber0870deb2011-06-15 02:47:03 +00002779 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002780 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002781 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2782 QualType OType = PVD->getOriginalType();
2783 QualType Type = PVD->getType();
2784 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002785 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002786 << Type << OType;
2787 Diag(PVD->getLocation(), diag::note_declared_at);
2788 }
2789 }
2790 }
2791 }
2792
Chandler Carruth7c430c02011-05-27 01:33:31 +00002793 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002794}
2795
2796/// \brief Check the constraints on operands to unary expression and type
2797/// traits.
2798///
2799/// This will complete any types necessary, and validate the various constraints
2800/// on those operands.
2801///
Steve Naroff71b59a92007-06-04 22:22:31 +00002802/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002803/// C99 6.3.2.1p[2-4] all state:
2804/// Except when it is the operand of the sizeof operator ...
2805///
2806/// C++ [expr.sizeof]p4
2807/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2808/// standard conversions are not applied to the operand of sizeof.
2809///
2810/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002811bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002812 SourceLocation OpLoc,
2813 SourceRange ExprRange,
2814 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002815 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002816 return false;
2817
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002818 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2819 // the result is the size of the referenced type."
2820 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2821 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002822 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2823 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002824
Chandler Carruth62da79c2011-05-26 08:53:12 +00002825 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002826 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002827
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002828 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002829 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002830 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002831 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002832
Richard Trieuba63ce62011-09-09 01:45:06 +00002833 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002834 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002835 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002836 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002837
Richard Trieuba63ce62011-09-09 01:45:06 +00002838 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002839 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002840 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002841
Chris Lattner62975a72009-04-24 00:30:45 +00002842 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002843}
2844
Chandler Carruth14502c22011-05-26 08:53:10 +00002845static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002846 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002847
Mike Stump11289f42009-09-09 15:08:12 +00002848 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002849 if (isa<DeclRefExpr>(E))
2850 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002851
2852 // Cannot know anything else if the expression is dependent.
2853 if (E->isTypeDependent())
2854 return false;
2855
Douglas Gregor71235ec2009-05-02 02:18:30 +00002856 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002857 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2858 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002859 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002860 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002861
2862 // Alignment of a field access is always okay, so long as it isn't a
2863 // bit-field.
2864 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002865 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002866 return false;
2867
Chandler Carruth14502c22011-05-26 08:53:10 +00002868 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002869}
2870
Chandler Carruth14502c22011-05-26 08:53:10 +00002871bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002872 E = E->IgnoreParens();
2873
2874 // Cannot know anything else if the expression is dependent.
2875 if (E->isTypeDependent())
2876 return false;
2877
Chandler Carruth14502c22011-05-26 08:53:10 +00002878 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002879}
2880
Douglas Gregor0950e412009-03-13 21:01:28 +00002881/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002882ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002883Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2884 SourceLocation OpLoc,
2885 UnaryExprOrTypeTrait ExprKind,
2886 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002887 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002888 return ExprError();
2889
John McCallbcd03502009-12-07 02:54:59 +00002890 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002891
Douglas Gregor0950e412009-03-13 21:01:28 +00002892 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002894 return ExprError();
2895
2896 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2898 Context.getSizeType(),
2899 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002900}
2901
2902/// \brief Build a sizeof or alignof expression given an expression
2903/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002904ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002905Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2906 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002907 ExprResult PE = CheckPlaceholderExpr(E);
2908 if (PE.isInvalid())
2909 return ExprError();
2910
2911 E = PE.get();
2912
Douglas Gregor0950e412009-03-13 21:01:28 +00002913 // Verify that the operand is valid.
2914 bool isInvalid = false;
2915 if (E->isTypeDependent()) {
2916 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002917 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002918 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002919 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002920 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002921 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002922 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002923 isInvalid = true;
2924 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002925 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002926 }
2927
2928 if (isInvalid)
2929 return ExprError();
2930
2931 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002932 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002933 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002934 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002935}
2936
Peter Collingbournee190dee2011-03-11 19:24:49 +00002937/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2938/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002939/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002940ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002941Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002942 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002943 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002944 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002945 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002946
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002948 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002949 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002950 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002951 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002952
Douglas Gregor0950e412009-03-13 21:01:28 +00002953 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002954 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002955 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002956}
2957
John Wiegley01296292011-04-08 18:41:53 +00002958static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002959 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002960 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002961 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002962
John McCall34376a62010-12-04 03:47:34 +00002963 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002964 if (V.get()->getObjectKind() != OK_Ordinary) {
2965 V = S.DefaultLvalueConversion(V.take());
2966 if (V.isInvalid())
2967 return QualType();
2968 }
John McCall34376a62010-12-04 03:47:34 +00002969
Chris Lattnere267f5d2007-08-26 05:39:26 +00002970 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002971 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002972 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002973
Chris Lattnere267f5d2007-08-26 05:39:26 +00002974 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002975 if (V.get()->getType()->isArithmeticType())
2976 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002977
John McCall36226622010-10-12 02:09:17 +00002978 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002979 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002980 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002981 if (PR.get() != V.get()) {
2982 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002983 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002984 }
2985
Chris Lattnere267f5d2007-08-26 05:39:26 +00002986 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002987 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002988 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002989 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002990}
2991
2992
Chris Lattnere168f762006-11-10 05:29:30 +00002993
John McCalldadc5752010-08-24 06:29:42 +00002994ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002995Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002996 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002997 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002998 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002999 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003000 case tok::plusplus: Opc = UO_PostInc; break;
3001 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003002 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003003
John McCallb268a282010-08-23 23:25:46 +00003004 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003005}
3006
John McCalldadc5752010-08-24 06:29:42 +00003007ExprResult
John McCallb268a282010-08-23 23:25:46 +00003008Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3009 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003010 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003011 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003012 if (Result.isInvalid()) return ExprError();
3013 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003014
John McCallb268a282010-08-23 23:25:46 +00003015 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregor40412ac2008-11-19 17:17:41 +00003017 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003018 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003019 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003020 Context.DependentTy,
3021 VK_LValue, OK_Ordinary,
3022 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003023 }
3024
Mike Stump11289f42009-09-09 15:08:12 +00003025 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003027 LHSExp->getType()->isEnumeralType() ||
3028 RHSExp->getType()->isRecordType() ||
3029 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003030 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003031 }
3032
John McCallb268a282010-08-23 23:25:46 +00003033 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003034}
3035
3036
John McCalldadc5752010-08-24 06:29:42 +00003037ExprResult
John McCallb268a282010-08-23 23:25:46 +00003038Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003039 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003040 Expr *LHSExp = Base;
3041 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003042
Chris Lattner36d572b2007-07-16 00:14:47 +00003043 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003044 if (!LHSExp->getType()->getAs<VectorType>()) {
3045 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3046 if (Result.isInvalid())
3047 return ExprError();
3048 LHSExp = Result.take();
3049 }
3050 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3051 if (Result.isInvalid())
3052 return ExprError();
3053 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003054
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003056 ExprValueKind VK = VK_LValue;
3057 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003058
Steve Naroffc1aadb12007-03-28 21:49:40 +00003059 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003060 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003061 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003062 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003063 Expr *BaseExpr, *IndexExpr;
3064 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003065 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3066 BaseExpr = LHSExp;
3067 IndexExpr = RHSExp;
3068 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003069 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003070 BaseExpr = LHSExp;
3071 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003072 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003073 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003074 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003075 BaseExpr = RHSExp;
3076 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003077 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003078 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003079 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003083 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003084 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003085 // Handle the uncommon case of "123[Ptr]".
3086 BaseExpr = RHSExp;
3087 IndexExpr = LHSExp;
3088 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003089 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003090 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003091 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003092 VK = LHSExp->getValueKind();
3093 if (VK != VK_RValue)
3094 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003095
Chris Lattner36d572b2007-07-16 00:14:47 +00003096 // FIXME: need to deal with const...
3097 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003098 } else if (LHSTy->isArrayType()) {
3099 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003100 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003101 // wasn't promoted because of the C90 rule that doesn't
3102 // allow promoting non-lvalue arrays. Warn, then
3103 // force the promotion here.
3104 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3105 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003106 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3107 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003108 LHSTy = LHSExp->getType();
3109
3110 BaseExpr = LHSExp;
3111 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003112 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003113 } else if (RHSTy->isArrayType()) {
3114 // Same as previous, except for 123[f().a] case
3115 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3116 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003117 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3118 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003119 RHSTy = RHSExp->getType();
3120
3121 BaseExpr = RHSExp;
3122 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003123 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003124 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003125 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3126 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003127 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003128 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003129 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003130 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3131 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003132
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003133 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003134 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3135 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003136 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3137
Douglas Gregorac1fb652009-03-24 19:52:54 +00003138 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003139 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3140 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003141 // incomplete types are not object types.
3142 if (ResultType->isFunctionType()) {
3143 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3144 << ResultType << BaseExpr->getSourceRange();
3145 return ExprError();
3146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003148 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3149 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003150 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3151 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003152
3153 // C forbids expressions of unqualified void type from being l-values.
3154 // See IsCForbiddenLValueType.
3155 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003156 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003157 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003158 PDiag(diag::err_subscript_incomplete_type)
3159 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003160 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner62975a72009-04-24 00:30:45 +00003162 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003163 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003164 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3165 << ResultType << BaseExpr->getSourceRange();
3166 return ExprError();
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
John McCall4bc41ae2010-11-18 19:01:18 +00003169 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003170 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003171
Mike Stump4e1f26a2009-02-19 03:04:26 +00003172 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003173 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003174}
3175
John McCalldadc5752010-08-24 06:29:42 +00003176ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003177 FunctionDecl *FD,
3178 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003179 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003180 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003181 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003182 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003183 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003184 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003185 return ExprError();
3186 }
3187
3188 if (Param->hasUninstantiatedDefaultArg()) {
3189 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003190
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003191 // Instantiate the expression.
3192 MultiLevelTemplateArgumentList ArgList
3193 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003194
Nico Weber44887f62010-11-29 18:19:25 +00003195 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003196 = ArgList.getInnermost();
3197 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3198 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003199
Nico Weber44887f62010-11-29 18:19:25 +00003200 ExprResult Result;
3201 {
3202 // C++ [dcl.fct.default]p5:
3203 // The names in the [default argument] expression are bound, and
3204 // the semantic constraints are checked, at the point where the
3205 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003206 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003207 Result = SubstExpr(UninstExpr, ArgList);
3208 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003209 if (Result.isInvalid())
3210 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003212 // Check the expression as an initializer for the parameter.
3213 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003214 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003215 InitializationKind Kind
3216 = InitializationKind::CreateCopy(Param->getLocation(),
3217 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3218 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003219
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003220 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3221 Result = InitSeq.Perform(*this, Entity, Kind,
3222 MultiExprArg(*this, &ResultE, 1));
3223 if (Result.isInvalid())
3224 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003225
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003226 // Build the default argument expression.
3227 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3228 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003229 }
3230
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003231 // If the default expression creates temporaries, we need to
3232 // push them to the current stack of expression temporaries so they'll
3233 // be properly destroyed.
3234 // FIXME: We should really be rebuilding the default argument with new
3235 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003236 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3237 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3238 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3239 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3240 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003241 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003242 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003243
3244 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003245 // Just mark all of the declarations in this potentially-evaluated expression
3246 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003247 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003248 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003249}
3250
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003251/// ConvertArgumentsForCall - Converts the arguments specified in
3252/// Args/NumArgs to the parameter types of the function FDecl with
3253/// function prototype Proto. Call is the call expression itself, and
3254/// Fn is the function expression. For a C++ member function, this
3255/// routine does not attempt to convert the object argument. Returns
3256/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003257bool
3258Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003259 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003260 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003261 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003262 SourceLocation RParenLoc,
3263 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003264 // Bail out early if calling a builtin with custom typechecking.
3265 // We don't need to do this in the
3266 if (FDecl)
3267 if (unsigned ID = FDecl->getBuiltinID())
3268 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3269 return false;
3270
Mike Stump4e1f26a2009-02-19 03:04:26 +00003271 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003272 // assignment, to the types of the corresponding parameter, ...
3273 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003274 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003275 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003276 unsigned FnKind = Fn->getType()->isBlockPointerType()
3277 ? 1 /* block */
3278 : (IsExecConfig ? 3 /* kernel function (exec config) */
3279 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003280
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003281 // If too few arguments are available (and we don't have default
3282 // arguments for the remaining parameters), don't make the call.
3283 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003284 if (NumArgs < MinArgs) {
3285 Diag(RParenLoc, MinArgs == NumArgsInProto
3286 ? diag::err_typecheck_call_too_few_args
3287 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003288 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003289 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003290
3291 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003292 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003293 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3294 << FDecl;
3295
3296 return true;
3297 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003298 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003299 }
3300
3301 // If too many are passed and not variadic, error on the extras and drop
3302 // them.
3303 if (NumArgs > NumArgsInProto) {
3304 if (!Proto->isVariadic()) {
3305 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003306 MinArgs == NumArgsInProto
3307 ? diag::err_typecheck_call_too_many_args
3308 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003309 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003310 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003311 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3312 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003313
3314 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003315 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003316 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3317 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003318
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003319 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003320 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003321 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003322 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003323 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003324 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003325 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003326 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3327 if (Fn->getType()->isBlockPointerType())
3328 CallType = VariadicBlock; // Block
3329 else if (isa<MemberExpr>(Fn))
3330 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003331 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003332 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003333 if (Invalid)
3334 return true;
3335 unsigned TotalNumArgs = AllArgs.size();
3336 for (unsigned i = 0; i < TotalNumArgs; ++i)
3337 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003338
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003339 return false;
3340}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003341
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003342bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3343 FunctionDecl *FDecl,
3344 const FunctionProtoType *Proto,
3345 unsigned FirstProtoArg,
3346 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003347 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003348 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003349 unsigned NumArgsInProto = Proto->getNumArgs();
3350 unsigned NumArgsToCheck = NumArgs;
3351 bool Invalid = false;
3352 if (NumArgs != NumArgsInProto)
3353 // Use default arguments for missing arguments
3354 NumArgsToCheck = NumArgsInProto;
3355 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003356 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003358 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003359
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003360 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003361 if (ArgIx < NumArgs) {
3362 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003363
Eli Friedman3164fb12009-03-22 22:00:50 +00003364 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3365 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003366 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003367 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003368 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003369
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003370 // Pass the argument
3371 ParmVarDecl *Param = 0;
3372 if (FDecl && i < FDecl->getNumParams())
3373 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003374
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003375 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003376 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003377 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3378 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003379 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003380 SourceLocation(),
3381 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003382 if (ArgE.isInvalid())
3383 return true;
3384
3385 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003386 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003387 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003388
John McCalldadc5752010-08-24 06:29:42 +00003389 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003390 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003391 if (ArgExpr.isInvalid())
3392 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003393
Anders Carlsson355933d2009-08-25 03:49:14 +00003394 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003395 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003396
3397 // Check for array bounds violations for each argument to the call. This
3398 // check only triggers warnings when the argument isn't a more complex Expr
3399 // with its own checking, such as a BinaryOperator.
3400 CheckArrayAccess(Arg);
3401
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003402 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003403 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003404
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003406 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003407
3408 // Assume that extern "C" functions with variadic arguments that
3409 // return __unknown_anytype aren't *really* variadic.
3410 if (Proto->getResultType() == Context.UnknownAnyTy &&
3411 FDecl && FDecl->isExternC()) {
3412 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3413 ExprResult arg;
3414 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3415 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3416 else
3417 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3418 Invalid |= arg.isInvalid();
3419 AllArgs.push_back(arg.take());
3420 }
3421
3422 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3423 } else {
3424 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003425 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3426 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003427 Invalid |= Arg.isInvalid();
3428 AllArgs.push_back(Arg.take());
3429 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003430 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003431
3432 // Check for array bounds violations.
3433 for (unsigned i = ArgIx; i != NumArgs; ++i)
3434 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003435 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003436 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003437}
3438
John McCall2979fe02011-04-12 00:42:48 +00003439/// Given a function expression of unknown-any type, try to rebuild it
3440/// to have a function type.
3441static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3442
Steve Naroff83895f72007-09-16 03:34:24 +00003443/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003444/// This provides the location of the left/right parens and a list of comma
3445/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003446ExprResult
John McCallb268a282010-08-23 23:25:46 +00003447Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003448 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003449 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003450 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003451
3452 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003453 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003454 if (Result.isInvalid()) return ExprError();
3455 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003456
Richard Trieuba63ce62011-09-09 01:45:06 +00003457 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003459 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003460 // If this is a pseudo-destructor expression, build the call immediately.
3461 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3462 if (NumArgs > 0) {
3463 // Pseudo-destructor calls should not have any arguments.
3464 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003465 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003466 SourceRange(Args[0]->getLocStart(),
3467 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003468
Douglas Gregorad8a3362009-09-04 17:36:40 +00003469 NumArgs = 0;
3470 }
Mike Stump11289f42009-09-09 15:08:12 +00003471
Douglas Gregorad8a3362009-09-04 17:36:40 +00003472 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003473 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003476 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003477 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003478 // FIXME: Will need to cache the results of name lookup (including ADL) in
3479 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003480 bool Dependent = false;
3481 if (Fn->isTypeDependent())
3482 Dependent = true;
3483 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3484 Dependent = true;
3485
Peter Collingbourne41f85462011-02-09 21:07:24 +00003486 if (Dependent) {
3487 if (ExecConfig) {
3488 return Owned(new (Context) CUDAKernelCallExpr(
3489 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3490 Context.DependentTy, VK_RValue, RParenLoc));
3491 } else {
3492 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3493 Context.DependentTy, VK_RValue,
3494 RParenLoc));
3495 }
3496 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003497
3498 // Determine whether this is a call to an object (C++ [over.call.object]).
3499 if (Fn->getType()->isRecordType())
3500 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003501 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003502
John McCall2979fe02011-04-12 00:42:48 +00003503 if (Fn->getType() == Context.UnknownAnyTy) {
3504 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3505 if (result.isInvalid()) return ExprError();
3506 Fn = result.take();
3507 }
3508
John McCall0009fcc2011-04-26 20:42:42 +00003509 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003510 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003511 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003512 }
John McCall0009fcc2011-04-26 20:42:42 +00003513 }
John McCall10eae182009-11-30 22:42:35 +00003514
John McCall0009fcc2011-04-26 20:42:42 +00003515 // Check for overloaded calls. This can happen even in C due to extensions.
3516 if (Fn->getType() == Context.OverloadTy) {
3517 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3518
3519 // We aren't supposed to apply this logic if there's an '&' involved.
3520 if (!find.IsAddressOfOperand) {
3521 OverloadExpr *ovl = find.Expression;
3522 if (isa<UnresolvedLookupExpr>(ovl)) {
3523 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3524 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3525 RParenLoc, ExecConfig);
3526 } else {
John McCall2d74de92009-12-01 22:10:20 +00003527 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003528 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003529 }
3530 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003531 }
3532
Douglas Gregore254f902009-02-04 00:32:51 +00003533 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003534
Eli Friedmane14b1992009-12-26 03:35:45 +00003535 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003536
John McCall57500772009-12-16 12:17:52 +00003537 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003538 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3539 if (UnOp->getOpcode() == UO_AddrOf)
3540 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3541
John McCall57500772009-12-16 12:17:52 +00003542 if (isa<DeclRefExpr>(NakedFn))
3543 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003544 else if (isa<MemberExpr>(NakedFn))
3545 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003546
Peter Collingbourne41f85462011-02-09 21:07:24 +00003547 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003548 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003549}
3550
3551ExprResult
3552Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003553 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003554 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3555 if (!ConfigDecl)
3556 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3557 << "cudaConfigureCall");
3558 QualType ConfigQTy = ConfigDecl->getType();
3559
3560 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3561 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3562
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003563 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3564 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003565}
3566
Tanya Lattner55808c12011-06-04 00:47:47 +00003567/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3568///
3569/// __builtin_astype( value, dst type )
3570///
Richard Trieuba63ce62011-09-09 01:45:06 +00003571ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003572 SourceLocation BuiltinLoc,
3573 SourceLocation RParenLoc) {
3574 ExprValueKind VK = VK_RValue;
3575 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003576 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3577 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003578 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3579 return ExprError(Diag(BuiltinLoc,
3580 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003581 << DstTy
3582 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003583 << E->getSourceRange());
3584 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003585 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003586}
3587
John McCall57500772009-12-16 12:17:52 +00003588/// BuildResolvedCallExpr - Build a call to a resolved expression,
3589/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003590/// unary-convert to an expression of function-pointer or
3591/// block-pointer type.
3592///
3593/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003594ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003595Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3596 SourceLocation LParenLoc,
3597 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003598 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003599 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003600 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3601
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003602 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003603 ExprResult Result = UsualUnaryConversions(Fn);
3604 if (Result.isInvalid())
3605 return ExprError();
3606 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003607
Chris Lattner08464942007-12-28 05:29:59 +00003608 // Make the call expr early, before semantic checks. This guarantees cleanup
3609 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003610 CallExpr *TheCall;
3611 if (Config) {
3612 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3613 cast<CallExpr>(Config),
3614 Args, NumArgs,
3615 Context.BoolTy,
3616 VK_RValue,
3617 RParenLoc);
3618 } else {
3619 TheCall = new (Context) CallExpr(Context, Fn,
3620 Args, NumArgs,
3621 Context.BoolTy,
3622 VK_RValue,
3623 RParenLoc);
3624 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003625
John McCallbebede42011-02-26 05:39:39 +00003626 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3627
3628 // Bail out early if calling a builtin with custom typechecking.
3629 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3630 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3631
John McCall31996342011-04-07 08:22:57 +00003632 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003633 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003634 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003635 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3636 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003637 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003638 if (FuncT == 0)
3639 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3640 << Fn->getType() << Fn->getSourceRange());
3641 } else if (const BlockPointerType *BPT =
3642 Fn->getType()->getAs<BlockPointerType>()) {
3643 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3644 } else {
John McCall31996342011-04-07 08:22:57 +00003645 // Handle calls to expressions of unknown-any type.
3646 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003647 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003648 if (rewrite.isInvalid()) return ExprError();
3649 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003650 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003651 goto retry;
3652 }
3653
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003654 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3655 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003656 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003657
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003658 if (getLangOptions().CUDA) {
3659 if (Config) {
3660 // CUDA: Kernel calls must be to global functions
3661 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3662 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3663 << FDecl->getName() << Fn->getSourceRange());
3664
3665 // CUDA: Kernel function must have 'void' return type
3666 if (!FuncT->getResultType()->isVoidType())
3667 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3668 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003669 } else {
3670 // CUDA: Calls to global functions must be configured
3671 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3672 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3673 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003674 }
3675 }
3676
Eli Friedman3164fb12009-03-22 22:00:50 +00003677 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003678 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003679 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003680 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003681 return ExprError();
3682
Chris Lattner08464942007-12-28 05:29:59 +00003683 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003684 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003685 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003686
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003687 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003688 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003689 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003690 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003691 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003692 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003693
Douglas Gregord8e97de2009-04-02 15:37:10 +00003694 if (FDecl) {
3695 // Check if we have too few/too many template arguments, based
3696 // on our knowledge of the function definition.
3697 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003698 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003699 const FunctionProtoType *Proto
3700 = Def->getType()->getAs<FunctionProtoType>();
3701 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003702 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3703 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003704 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003705
3706 // If the function we're calling isn't a function prototype, but we have
3707 // a function prototype from a prior declaratiom, use that prototype.
3708 if (!FDecl->hasPrototype())
3709 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003710 }
3711
Steve Naroff0b661582007-08-28 23:30:39 +00003712 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003713 for (unsigned i = 0; i != NumArgs; i++) {
3714 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003715
3716 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003717 InitializedEntity Entity
3718 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003719 Proto->getArgType(i),
3720 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003721 ExprResult ArgE = PerformCopyInitialization(Entity,
3722 SourceLocation(),
3723 Owned(Arg));
3724 if (ArgE.isInvalid())
3725 return true;
3726
3727 Arg = ArgE.takeAs<Expr>();
3728
3729 } else {
John Wiegley01296292011-04-08 18:41:53 +00003730 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3731
3732 if (ArgE.isInvalid())
3733 return true;
3734
3735 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003736 }
3737
Douglas Gregor83025412010-10-26 05:45:40 +00003738 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3739 Arg->getType(),
3740 PDiag(diag::err_call_incomplete_argument)
3741 << Arg->getSourceRange()))
3742 return ExprError();
3743
Chris Lattner08464942007-12-28 05:29:59 +00003744 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003745 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003746 }
Chris Lattner08464942007-12-28 05:29:59 +00003747
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003748 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3749 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003750 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3751 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003752
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003753 // Check for sentinels
3754 if (NDecl)
3755 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003756
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003757 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003758 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003759 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003760 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003761
John McCallbebede42011-02-26 05:39:39 +00003762 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003763 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003764 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003765 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003766 return ExprError();
3767 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003768
John McCallb268a282010-08-23 23:25:46 +00003769 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003770}
3771
John McCalldadc5752010-08-24 06:29:42 +00003772ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003773Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003774 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003775 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003776 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003777 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003778
3779 TypeSourceInfo *TInfo;
3780 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3781 if (!TInfo)
3782 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3783
John McCallb268a282010-08-23 23:25:46 +00003784 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003785}
3786
John McCalldadc5752010-08-24 06:29:42 +00003787ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003788Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003789 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003790 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003791
Eli Friedman37a186d2008-05-20 05:22:08 +00003792 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003793 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3794 PDiag(diag::err_illegal_decl_array_incomplete_type)
3795 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003796 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003797 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003798 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003799 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003800 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003801 } else if (!literalType->isDependentType() &&
3802 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003803 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003804 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003805 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003806 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003807
Douglas Gregor85dabae2009-12-16 01:38:02 +00003808 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003809 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003810 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003811 = InitializationKind::CreateCStyleCast(LParenLoc,
3812 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003813 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003814 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003815 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003816 &literalType);
3817 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003818 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003819 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003820
Chris Lattner79413952008-12-04 23:50:19 +00003821 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003822 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003823 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003824 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003825 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003826
John McCall7decc9e2010-11-18 06:31:45 +00003827 // In C, compound literals are l-values for some reason.
3828 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3829
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003830 return MaybeBindToTemporary(
3831 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003832 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003833}
3834
John McCalldadc5752010-08-24 06:29:42 +00003835ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003836Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003837 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003838 unsigned NumInit = InitArgList.size();
3839 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003840
Steve Naroff30d242c2007-09-15 18:49:24 +00003841 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003842 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003843
Ted Kremenekac034612010-04-13 23:39:13 +00003844 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3845 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003846 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003847 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003848}
3849
John McCallcd78e802011-09-10 01:16:55 +00003850/// Do an explicit extend of the given block pointer if we're in ARC.
3851static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3852 assert(E.get()->getType()->isBlockPointerType());
3853 assert(E.get()->isRValue());
3854
3855 // Only do this in an r-value context.
3856 if (!S.getLangOptions().ObjCAutoRefCount) return;
3857
3858 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003859 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003860 /*base path*/ 0, VK_RValue);
3861 S.ExprNeedsCleanups = true;
3862}
3863
3864/// Prepare a conversion of the given expression to an ObjC object
3865/// pointer type.
3866CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3867 QualType type = E.get()->getType();
3868 if (type->isObjCObjectPointerType()) {
3869 return CK_BitCast;
3870 } else if (type->isBlockPointerType()) {
3871 maybeExtendBlockObject(*this, E);
3872 return CK_BlockPointerToObjCPointerCast;
3873 } else {
3874 assert(type->isPointerType());
3875 return CK_CPointerToObjCPointerCast;
3876 }
3877}
3878
John McCalld7646252010-11-14 08:17:51 +00003879/// Prepares for a scalar cast, performing all the necessary stages
3880/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003881static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003882 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3883 // Also, callers should have filtered out the invalid cases with
3884 // pointers. Everything else should be possible.
3885
John Wiegley01296292011-04-08 18:41:53 +00003886 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003887 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003888 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003889
John McCall9320b872011-09-09 05:25:32 +00003890 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003891 case Type::STK_MemberPointer:
3892 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003893
John McCall9320b872011-09-09 05:25:32 +00003894 case Type::STK_CPointer:
3895 case Type::STK_BlockPointer:
3896 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003897 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003898 case Type::STK_CPointer:
3899 return CK_BitCast;
3900 case Type::STK_BlockPointer:
3901 return (SrcKind == Type::STK_BlockPointer
3902 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3903 case Type::STK_ObjCObjectPointer:
3904 if (SrcKind == Type::STK_ObjCObjectPointer)
3905 return CK_BitCast;
3906 else if (SrcKind == Type::STK_CPointer)
3907 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003908 else {
3909 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003910 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003911 }
John McCall8cb679e2010-11-15 09:13:47 +00003912 case Type::STK_Bool:
3913 return CK_PointerToBoolean;
3914 case Type::STK_Integral:
3915 return CK_PointerToIntegral;
3916 case Type::STK_Floating:
3917 case Type::STK_FloatingComplex:
3918 case Type::STK_IntegralComplex:
3919 case Type::STK_MemberPointer:
3920 llvm_unreachable("illegal cast from pointer");
3921 }
3922 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003923
John McCall8cb679e2010-11-15 09:13:47 +00003924 case Type::STK_Bool: // casting from bool is like casting from an integer
3925 case Type::STK_Integral:
3926 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003927 case Type::STK_CPointer:
3928 case Type::STK_ObjCObjectPointer:
3929 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003930 if (Src.get()->isNullPointerConstant(S.Context,
3931 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003932 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003933 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003934 case Type::STK_Bool:
3935 return CK_IntegralToBoolean;
3936 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003937 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003938 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003939 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003940 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003941 Src = S.ImpCastExprToType(Src.take(),
3942 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003943 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003944 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003945 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003946 Src = S.ImpCastExprToType(Src.take(),
3947 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003948 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003949 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003950 case Type::STK_MemberPointer:
3951 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003952 }
3953 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003954
John McCall8cb679e2010-11-15 09:13:47 +00003955 case Type::STK_Floating:
3956 switch (DestTy->getScalarTypeKind()) {
3957 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003958 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003959 case Type::STK_Bool:
3960 return CK_FloatingToBoolean;
3961 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003962 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003963 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003964 Src = S.ImpCastExprToType(Src.take(),
3965 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003966 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003967 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003968 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003969 Src = S.ImpCastExprToType(Src.take(),
3970 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003971 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003972 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003973 case Type::STK_CPointer:
3974 case Type::STK_ObjCObjectPointer:
3975 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003976 llvm_unreachable("valid float->pointer cast?");
3977 case Type::STK_MemberPointer:
3978 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003979 }
3980 break;
3981
John McCall8cb679e2010-11-15 09:13:47 +00003982 case Type::STK_FloatingComplex:
3983 switch (DestTy->getScalarTypeKind()) {
3984 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003985 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003986 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003987 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003988 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003989 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003990 if (S.Context.hasSameType(ET, DestTy))
3991 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003992 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003993 return CK_FloatingCast;
3994 }
John McCall8cb679e2010-11-15 09:13:47 +00003995 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003996 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003997 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003998 Src = S.ImpCastExprToType(Src.take(),
3999 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004000 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004001 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004002 case Type::STK_CPointer:
4003 case Type::STK_ObjCObjectPointer:
4004 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004005 llvm_unreachable("valid complex float->pointer cast?");
4006 case Type::STK_MemberPointer:
4007 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004008 }
4009 break;
4010
John McCall8cb679e2010-11-15 09:13:47 +00004011 case Type::STK_IntegralComplex:
4012 switch (DestTy->getScalarTypeKind()) {
4013 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004014 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004015 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004016 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004017 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004018 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004019 if (S.Context.hasSameType(ET, DestTy))
4020 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00004021 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004022 return CK_IntegralCast;
4023 }
John McCall8cb679e2010-11-15 09:13:47 +00004024 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004025 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004026 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00004027 Src = S.ImpCastExprToType(Src.take(),
4028 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004029 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004030 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004031 case Type::STK_CPointer:
4032 case Type::STK_ObjCObjectPointer:
4033 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004034 llvm_unreachable("valid complex int->pointer cast?");
4035 case Type::STK_MemberPointer:
4036 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004037 }
4038 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004039 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004040
John McCalld7646252010-11-14 08:17:51 +00004041 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004042}
4043
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004044/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004045ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4046 SourceRange TypeRange, QualType CastType,
4047 Expr *CastExpr, CastKind &Kind,
4048 ExprValueKind &VK, CXXCastPath &BasePath,
4049 bool FunctionalStyle) {
4050 if (CastExpr->getType() == Context.UnknownAnyTy)
4051 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4052 BasePath);
John McCall31996342011-04-07 08:22:57 +00004053
Sebastian Redl9f831db2009-07-25 15:41:38 +00004054 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004055 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004056 CastExpr->getLocEnd()),
4057 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004058 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004059
Richard Trieuba63ce62011-09-09 01:45:06 +00004060 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004061
John McCall7decc9e2010-11-18 06:31:45 +00004062 // We only support r-value casts in C.
4063 VK = VK_RValue;
4064
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004065 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4066 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004067 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004068 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004069 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004070 if (castExprRes.isInvalid())
4071 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004072 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004073
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004074 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004075 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004076 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004077 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004078
Richard Trieuba63ce62011-09-09 01:45:06 +00004079 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004080 if (castExprRes.isInvalid())
4081 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004082 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004083
Richard Trieuba63ce62011-09-09 01:45:06 +00004084 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004085 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004086 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004087
Richard Trieuba63ce62011-09-09 01:45:06 +00004088 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4089 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4090 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004091 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004092 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004093 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4094 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004095 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004096 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004097 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004098
Richard Trieuba63ce62011-09-09 01:45:06 +00004099 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004100 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004101 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004102 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004103 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004104 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004105 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004106 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004107 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004108 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4109 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004110 break;
4111 }
4112 }
John Wiegley01296292011-04-08 18:41:53 +00004113 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004114 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4115 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004116 return ExprError();
4117 }
John McCalle3027922010-08-25 11:45:40 +00004118 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004119 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004120 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004121
Anders Carlsson525b76b2009-10-16 02:48:28 +00004122 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004123 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4124 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004125 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004126 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004127
John McCalld7646252010-11-14 08:17:51 +00004128 // The type we're casting to is known to be a scalar or vector.
4129
4130 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004131 if (!CastExpr->getType()->isScalarType() &&
4132 !CastExpr->getType()->isVectorType()) {
4133 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004134 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004135 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004136 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004137 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004138
Richard Trieuba63ce62011-09-09 01:45:06 +00004139 if (CastType->isExtVectorType())
4140 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004141
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 if (CastType->isVectorType()) {
4143 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004144 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004145 (CastExpr->getType()->isIntegerType() ||
4146 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004147 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004148 return Owned(CastExpr);
4149 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4150 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004151 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004152 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004153 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004154 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004155 if (CastExpr->getType()->isVectorType()) {
4156 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004157 return ExprError();
4158 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004159 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004160 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004161
John McCalld7646252010-11-14 08:17:51 +00004162 // The source and target types are both scalars, i.e.
4163 // - arithmetic types (fundamental, enum, and complex)
4164 // - all kinds of pointers
4165 // Note that member pointers were filtered out with C++, above.
4166
Richard Trieuba63ce62011-09-09 01:45:06 +00004167 if (isa<ObjCSelectorExpr>(CastExpr)) {
4168 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004169 return ExprError();
4170 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004171
John McCalld7646252010-11-14 08:17:51 +00004172 // If either type is a pointer, the other type has to be either an
4173 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004174 QualType CastExprType = CastExpr->getType();
4175 if (!CastType->isArithmeticType()) {
4176 if (!CastExprType->isIntegralType(Context) &&
4177 CastExprType->isArithmeticType()) {
4178 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004179 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004180 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004181 return ExprError();
4182 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004183 } else if (!CastExpr->getType()->isArithmeticType()) {
4184 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4185 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4186 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004187 return ExprError();
4188 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004189 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004190
John McCall31168b02011-06-15 23:02:42 +00004191 if (getLangOptions().ObjCAutoRefCount) {
4192 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004193 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4194 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004195
Richard Trieuba63ce62011-09-09 01:45:06 +00004196 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4197 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004198 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4199 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4200 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4201 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4202 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004203 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004204 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004205 << CastExprType << CastType << AA_Casting
4206 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004207
4208 return ExprError();
4209 }
4210 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004211 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004212 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4213 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004214 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004215 << CastExprType << CastType
4216 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004217 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004218 }
4219 }
4220
Richard Trieuba63ce62011-09-09 01:45:06 +00004221 castExprRes = Owned(CastExpr);
4222 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004223 if (castExprRes.isInvalid())
4224 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004225 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004226
John McCalld7646252010-11-14 08:17:51 +00004227 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004228 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004229
Richard Trieuba63ce62011-09-09 01:45:06 +00004230 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004231}
4232
Anders Carlsson525b76b2009-10-16 02:48:28 +00004233bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004234 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004235 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004236
Anders Carlssonde71adf2007-11-27 05:51:55 +00004237 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004238 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004239 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004240 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004241 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004242 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004243 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004244 } else
4245 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004246 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004247 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004248
John McCalle3027922010-08-25 11:45:40 +00004249 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004250 return false;
4251}
4252
John Wiegley01296292011-04-08 18:41:53 +00004253ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4254 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004255 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004256
Anders Carlsson43d70f82009-10-16 05:23:41 +00004257 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004258
Nate Begemanc8961a42009-06-27 22:05:55 +00004259 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4260 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004261 // In OpenCL, casts between vectors of different types are not allowed.
4262 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004263 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004264 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4265 || (getLangOptions().OpenCL &&
4266 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004267 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004268 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004269 return ExprError();
4270 }
John McCalle3027922010-08-25 11:45:40 +00004271 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004272 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004273 }
4274
Nate Begemanbd956c42009-06-28 02:36:38 +00004275 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004276 // conversion will take place first from scalar to elt type, and then
4277 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004278 if (SrcTy->isPointerType())
4279 return Diag(R.getBegin(),
4280 diag::err_invalid_conversion_between_vector_and_scalar)
4281 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004282
4283 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004284 ExprResult CastExprRes = Owned(CastExpr);
4285 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4286 if (CastExprRes.isInvalid())
4287 return ExprError();
4288 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004289
John McCalle3027922010-08-25 11:45:40 +00004290 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004291 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004292}
4293
John McCalldadc5752010-08-24 06:29:42 +00004294ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004295Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4296 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004297 SourceLocation RParenLoc, Expr *CastExpr) {
4298 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004299 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004300
Richard Trieuba63ce62011-09-09 01:45:06 +00004301 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004302 if (D.isInvalidType())
4303 return ExprError();
4304
4305 if (getLangOptions().CPlusPlus) {
4306 // Check that there are no default arguments (C++ only).
4307 CheckExtraCXXDefaultArguments(D);
4308 }
4309
John McCall42856de2011-10-01 05:17:03 +00004310 checkUnusedDeclAttributes(D);
4311
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004312 QualType castType = castTInfo->getType();
4313 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004314
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004315 bool isVectorLiteral = false;
4316
4317 // Check for an altivec or OpenCL literal,
4318 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004319 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4320 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004321 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4322 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004323 if (PLE && PLE->getNumExprs() == 0) {
4324 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4325 return ExprError();
4326 }
4327 if (PE || PLE->getNumExprs() == 1) {
4328 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4329 if (!E->getType()->isVectorType())
4330 isVectorLiteral = true;
4331 }
4332 else
4333 isVectorLiteral = true;
4334 }
4335
4336 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4337 // then handle it as such.
4338 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004339 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004340
Nate Begeman5ec4b312009-08-10 23:49:36 +00004341 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004342 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4343 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004344 if (isa<ParenListExpr>(CastExpr)) {
4345 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004346 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004347 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004348 }
John McCallebe54742010-01-15 18:56:44 +00004349
Richard Trieuba63ce62011-09-09 01:45:06 +00004350 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004351}
4352
John McCalldadc5752010-08-24 06:29:42 +00004353ExprResult
John McCallebe54742010-01-15 18:56:44 +00004354Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004355 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004356 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004357 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004358 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004359 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004360 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004361 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004362 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004363 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004364 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004365
Richard Trieucfc491d2011-08-02 04:35:43 +00004366 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004367 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004368 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004369}
4370
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004371ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4372 SourceLocation RParenLoc, Expr *E,
4373 TypeSourceInfo *TInfo) {
4374 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4375 "Expected paren or paren list expression");
4376
4377 Expr **exprs;
4378 unsigned numExprs;
4379 Expr *subExpr;
4380 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4381 exprs = PE->getExprs();
4382 numExprs = PE->getNumExprs();
4383 } else {
4384 subExpr = cast<ParenExpr>(E)->getSubExpr();
4385 exprs = &subExpr;
4386 numExprs = 1;
4387 }
4388
4389 QualType Ty = TInfo->getType();
4390 assert(Ty->isVectorType() && "Expected vector type");
4391
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004392 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004393 const VectorType *VTy = Ty->getAs<VectorType>();
4394 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4395
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004396 // '(...)' form of vector initialization in AltiVec: the number of
4397 // initializers must be one or must match the size of the vector.
4398 // If a single value is specified in the initializer then it will be
4399 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004400 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004401 // The number of initializers must be one or must match the size of the
4402 // vector. If a single value is specified in the initializer then it will
4403 // be replicated to all the components of the vector
4404 if (numExprs == 1) {
4405 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4406 ExprResult Literal = Owned(exprs[0]);
4407 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4408 PrepareScalarCast(*this, Literal, ElemTy));
4409 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4410 }
4411 else if (numExprs < numElems) {
4412 Diag(E->getExprLoc(),
4413 diag::err_incorrect_number_of_vector_initializers);
4414 return ExprError();
4415 }
4416 else
4417 for (unsigned i = 0, e = numExprs; i != e; ++i)
4418 initExprs.push_back(exprs[i]);
4419 }
Tanya Lattner83559382011-07-15 23:07:01 +00004420 else {
4421 // For OpenCL, when the number of initializers is a single value,
4422 // it will be replicated to all components of the vector.
4423 if (getLangOptions().OpenCL &&
4424 VTy->getVectorKind() == VectorType::GenericVector &&
4425 numExprs == 1) {
4426 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4427 ExprResult Literal = Owned(exprs[0]);
4428 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4429 PrepareScalarCast(*this, Literal, ElemTy));
4430 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4431 }
4432
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004433 for (unsigned i = 0, e = numExprs; i != e; ++i)
4434 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004435 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004436 // FIXME: This means that pretty-printing the final AST will produce curly
4437 // braces instead of the original commas.
4438 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4439 &initExprs[0],
4440 initExprs.size(), RParenLoc);
4441 initE->setType(Ty);
4442 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4443}
4444
Nate Begeman5ec4b312009-08-10 23:49:36 +00004445/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4446/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004447ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004448Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4449 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004450 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004451 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004452
John McCalldadc5752010-08-24 06:29:42 +00004453 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004454
Nate Begeman5ec4b312009-08-10 23:49:36 +00004455 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004456 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4457 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004458
John McCallb268a282010-08-23 23:25:46 +00004459 if (Result.isInvalid()) return ExprError();
4460
4461 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004462}
4463
John McCalldadc5752010-08-24 06:29:42 +00004464ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004465 SourceLocation R,
4466 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004467 unsigned nexprs = Val.size();
4468 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004469 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4470 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004471 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004472 expr = new (Context) ParenExpr(L, R, exprs[0]);
4473 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004474 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4475 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004476 return Owned(expr);
4477}
4478
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004479/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004480/// constant and the other is not a pointer. Returns true if a diagnostic is
4481/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004482bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004483 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004484 Expr *NullExpr = LHSExpr;
4485 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004486 Expr::NullPointerConstantKind NullKind =
4487 NullExpr->isNullPointerConstant(Context,
4488 Expr::NPC_ValueDependentIsNotNull);
4489
4490 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004491 NullExpr = RHSExpr;
4492 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004493 NullKind =
4494 NullExpr->isNullPointerConstant(Context,
4495 Expr::NPC_ValueDependentIsNotNull);
4496 }
4497
4498 if (NullKind == Expr::NPCK_NotNull)
4499 return false;
4500
4501 if (NullKind == Expr::NPCK_ZeroInteger) {
4502 // In this case, check to make sure that we got here from a "NULL"
4503 // string in the source code.
4504 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004505 SourceLocation loc = NullExpr->getExprLoc();
4506 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004507 return false;
4508 }
4509
4510 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4511 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4512 << NonPointerExpr->getType() << DiagType
4513 << NonPointerExpr->getSourceRange();
4514 return true;
4515}
4516
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004517/// \brief Return false if the condition expression is valid, true otherwise.
4518static bool checkCondition(Sema &S, Expr *Cond) {
4519 QualType CondTy = Cond->getType();
4520
4521 // C99 6.5.15p2
4522 if (CondTy->isScalarType()) return false;
4523
4524 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4525 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4526 return false;
4527
4528 // Emit the proper error message.
4529 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4530 diag::err_typecheck_cond_expect_scalar :
4531 diag::err_typecheck_cond_expect_scalar_or_vector)
4532 << CondTy;
4533 return true;
4534}
4535
4536/// \brief Return false if the two expressions can be converted to a vector,
4537/// true otherwise
4538static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4539 ExprResult &RHS,
4540 QualType CondTy) {
4541 // Both operands should be of scalar type.
4542 if (!LHS.get()->getType()->isScalarType()) {
4543 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4544 << CondTy;
4545 return true;
4546 }
4547 if (!RHS.get()->getType()->isScalarType()) {
4548 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4549 << CondTy;
4550 return true;
4551 }
4552
4553 // Implicity convert these scalars to the type of the condition.
4554 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4555 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4556 return false;
4557}
4558
4559/// \brief Handle when one or both operands are void type.
4560static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4561 ExprResult &RHS) {
4562 Expr *LHSExpr = LHS.get();
4563 Expr *RHSExpr = RHS.get();
4564
4565 if (!LHSExpr->getType()->isVoidType())
4566 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4567 << RHSExpr->getSourceRange();
4568 if (!RHSExpr->getType()->isVoidType())
4569 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4570 << LHSExpr->getSourceRange();
4571 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4572 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4573 return S.Context.VoidTy;
4574}
4575
4576/// \brief Return false if the NullExpr can be promoted to PointerTy,
4577/// true otherwise.
4578static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4579 QualType PointerTy) {
4580 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4581 !NullExpr.get()->isNullPointerConstant(S.Context,
4582 Expr::NPC_ValueDependentIsNull))
4583 return true;
4584
4585 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4586 return false;
4587}
4588
4589/// \brief Checks compatibility between two pointers and return the resulting
4590/// type.
4591static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4592 ExprResult &RHS,
4593 SourceLocation Loc) {
4594 QualType LHSTy = LHS.get()->getType();
4595 QualType RHSTy = RHS.get()->getType();
4596
4597 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4598 // Two identical pointers types are always compatible.
4599 return LHSTy;
4600 }
4601
4602 QualType lhptee, rhptee;
4603
4604 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004605 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4606 lhptee = LHSBTy->getPointeeType();
4607 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004608 } else {
John McCall9320b872011-09-09 05:25:32 +00004609 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4610 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004611 }
4612
4613 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4614 rhptee.getUnqualifiedType())) {
4615 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4616 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4617 << RHS.get()->getSourceRange();
4618 // In this situation, we assume void* type. No especially good
4619 // reason, but this is what gcc does, and we do have to pick
4620 // to get a consistent AST.
4621 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4622 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4623 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4624 return incompatTy;
4625 }
4626
4627 // The pointer types are compatible.
4628 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4629 // differently qualified versions of compatible types, the result type is
4630 // a pointer to an appropriately qualified version of the *composite*
4631 // type.
4632 // FIXME: Need to calculate the composite type.
4633 // FIXME: Need to add qualifiers
4634
4635 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4636 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4637 return LHSTy;
4638}
4639
4640/// \brief Return the resulting type when the operands are both block pointers.
4641static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4642 ExprResult &LHS,
4643 ExprResult &RHS,
4644 SourceLocation Loc) {
4645 QualType LHSTy = LHS.get()->getType();
4646 QualType RHSTy = RHS.get()->getType();
4647
4648 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4649 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4650 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4651 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4652 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4653 return destType;
4654 }
4655 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4656 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4657 << RHS.get()->getSourceRange();
4658 return QualType();
4659 }
4660
4661 // We have 2 block pointer types.
4662 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4663}
4664
4665/// \brief Return the resulting type when the operands are both pointers.
4666static QualType
4667checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4668 ExprResult &RHS,
4669 SourceLocation Loc) {
4670 // get the pointer types
4671 QualType LHSTy = LHS.get()->getType();
4672 QualType RHSTy = RHS.get()->getType();
4673
4674 // get the "pointed to" types
4675 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4676 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4677
4678 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4679 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4680 // Figure out necessary qualifiers (C99 6.5.15p6)
4681 QualType destPointee
4682 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4683 QualType destType = S.Context.getPointerType(destPointee);
4684 // Add qualifiers if necessary.
4685 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4686 // Promote to void*.
4687 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4688 return destType;
4689 }
4690 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4691 QualType destPointee
4692 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4693 QualType destType = S.Context.getPointerType(destPointee);
4694 // Add qualifiers if necessary.
4695 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4696 // Promote to void*.
4697 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4698 return destType;
4699 }
4700
4701 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4702}
4703
4704/// \brief Return false if the first expression is not an integer and the second
4705/// expression is not a pointer, true otherwise.
4706static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4707 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004708 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004709 if (!PointerExpr->getType()->isPointerType() ||
4710 !Int.get()->getType()->isIntegerType())
4711 return false;
4712
Richard Trieuba63ce62011-09-09 01:45:06 +00004713 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4714 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004715
4716 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4717 << Expr1->getType() << Expr2->getType()
4718 << Expr1->getSourceRange() << Expr2->getSourceRange();
4719 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4720 CK_IntegralToPointer);
4721 return true;
4722}
4723
Richard Trieud33e46e2011-09-06 20:06:39 +00004724/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4725/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004726/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004727QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4728 ExprResult &RHS, ExprValueKind &VK,
4729 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004730 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004731
Richard Trieud33e46e2011-09-06 20:06:39 +00004732 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4733 if (!LHSResult.isUsable()) return QualType();
4734 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004735
Richard Trieud33e46e2011-09-06 20:06:39 +00004736 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4737 if (!RHSResult.isUsable()) return QualType();
4738 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004739
Sebastian Redl1a99f442009-04-16 17:51:27 +00004740 // C++ is sufficiently different to merit its own checker.
4741 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004742 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004743
4744 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004745 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004746
John Wiegley01296292011-04-08 18:41:53 +00004747 Cond = UsualUnaryConversions(Cond.take());
4748 if (Cond.isInvalid())
4749 return QualType();
4750 LHS = UsualUnaryConversions(LHS.take());
4751 if (LHS.isInvalid())
4752 return QualType();
4753 RHS = UsualUnaryConversions(RHS.take());
4754 if (RHS.isInvalid())
4755 return QualType();
4756
4757 QualType CondTy = Cond.get()->getType();
4758 QualType LHSTy = LHS.get()->getType();
4759 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004760
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004761 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004762 if (checkCondition(*this, Cond.get()))
4763 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004764
Chris Lattnere2949f42008-01-06 22:42:25 +00004765 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004766 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004767 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004768
Nate Begemanabb5a732010-09-20 22:41:17 +00004769 // OpenCL: If the condition is a vector, and both operands are scalar,
4770 // attempt to implicity convert them to the vector type to act like the
4771 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004772 if (getLangOptions().OpenCL && CondTy->isVectorType())
4773 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004774 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004775
Chris Lattnere2949f42008-01-06 22:42:25 +00004776 // If both operands have arithmetic type, do the usual arithmetic conversions
4777 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004778 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4779 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004780 if (LHS.isInvalid() || RHS.isInvalid())
4781 return QualType();
4782 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004783 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004784
Chris Lattnere2949f42008-01-06 22:42:25 +00004785 // If both operands are the same structure or union type, the result is that
4786 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004787 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4788 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004789 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004790 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004791 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004792 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004793 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004794 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004795
Chris Lattnere2949f42008-01-06 22:42:25 +00004796 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004797 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004798 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004799 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004800 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004801
Steve Naroff039ad3c2008-01-08 01:11:38 +00004802 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4803 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004804 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4805 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004806
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004807 // All objective-c pointer type analysis is done here.
4808 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4809 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004810 if (LHS.isInvalid() || RHS.isInvalid())
4811 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004812 if (!compositeType.isNull())
4813 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004814
4815
Steve Naroff05efa972009-07-01 14:36:47 +00004816 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004817 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4818 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4819 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004820
Steve Naroff05efa972009-07-01 14:36:47 +00004821 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004822 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4823 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4824 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004825
John McCalle84af4e2010-11-13 01:35:44 +00004826 // GCC compatibility: soften pointer/integer mismatch. Note that
4827 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004828 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4829 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004830 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004831 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4832 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004833 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004834
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004835 // Emit a better diagnostic if one of the expressions is a null pointer
4836 // constant and the other is not a pointer type. In this case, the user most
4837 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004838 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004839 return QualType();
4840
Chris Lattnere2949f42008-01-06 22:42:25 +00004841 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004842 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004843 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4844 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004845 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004846}
4847
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004848/// FindCompositeObjCPointerType - Helper method to find composite type of
4849/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004850QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004851 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004852 QualType LHSTy = LHS.get()->getType();
4853 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004854
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004855 // Handle things like Class and struct objc_class*. Here we case the result
4856 // to the pseudo-builtin, because that will be implicitly cast back to the
4857 // redefinition type if an attempt is made to access its fields.
4858 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004859 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004860 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004861 return LHSTy;
4862 }
4863 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004864 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004865 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004866 return RHSTy;
4867 }
4868 // And the same for struct objc_object* / id
4869 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004870 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004871 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004872 return LHSTy;
4873 }
4874 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004875 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004876 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004877 return RHSTy;
4878 }
4879 // And the same for struct objc_selector* / SEL
4880 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004881 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004882 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004883 return LHSTy;
4884 }
4885 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004886 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004887 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004888 return RHSTy;
4889 }
4890 // Check constraints for Objective-C object pointers types.
4891 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004892
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004893 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4894 // Two identical object pointer types are always compatible.
4895 return LHSTy;
4896 }
John McCall9320b872011-09-09 05:25:32 +00004897 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4898 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004899 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004900
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004901 // If both operands are interfaces and either operand can be
4902 // assigned to the other, use that type as the composite
4903 // type. This allows
4904 // xxx ? (A*) a : (B*) b
4905 // where B is a subclass of A.
4906 //
4907 // Additionally, as for assignment, if either type is 'id'
4908 // allow silent coercion. Finally, if the types are
4909 // incompatible then make sure to use 'id' as the composite
4910 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004911
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004912 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4913 // It could return the composite type.
4914 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4915 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4916 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4917 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4918 } else if ((LHSTy->isObjCQualifiedIdType() ||
4919 RHSTy->isObjCQualifiedIdType()) &&
4920 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4921 // Need to handle "id<xx>" explicitly.
4922 // GCC allows qualified id and any Objective-C type to devolve to
4923 // id. Currently localizing to here until clear this should be
4924 // part of ObjCQualifiedIdTypesAreCompatible.
4925 compositeType = Context.getObjCIdType();
4926 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4927 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004928 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004929 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4930 ;
4931 else {
4932 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4933 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004935 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004936 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4937 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004938 return incompatTy;
4939 }
4940 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004941 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4942 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004943 return compositeType;
4944 }
4945 // Check Objective-C object pointer types and 'void *'
4946 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4947 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4948 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4949 QualType destPointee
4950 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4951 QualType destType = Context.getPointerType(destPointee);
4952 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004953 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004954 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004955 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004956 return destType;
4957 }
4958 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4959 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4960 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4961 QualType destPointee
4962 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4963 QualType destType = Context.getPointerType(destPointee);
4964 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004965 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004966 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004967 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004968 return destType;
4969 }
4970 return QualType();
4971}
4972
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004973/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004974/// ParenRange in parentheses.
4975static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004976 const PartialDiagnostic &Note,
4977 SourceRange ParenRange) {
4978 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4979 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4980 EndLoc.isValid()) {
4981 Self.Diag(Loc, Note)
4982 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4983 << FixItHint::CreateInsertion(EndLoc, ")");
4984 } else {
4985 // We can't display the parentheses, so just show the bare note.
4986 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004987 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004988}
4989
4990static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4991 return Opc >= BO_Mul && Opc <= BO_Shr;
4992}
4993
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004994/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4995/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004996/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4997/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004998static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004999 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005000 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5001 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005002 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005003 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005004
5005 // Built-in binary operator.
5006 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5007 if (IsArithmeticOp(OP->getOpcode())) {
5008 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005009 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005010 return true;
5011 }
5012 }
5013
5014 // Overloaded operator.
5015 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5016 if (Call->getNumArgs() != 2)
5017 return false;
5018
5019 // Make sure this is really a binary operator that is safe to pass into
5020 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5021 OverloadedOperatorKind OO = Call->getOperator();
5022 if (OO < OO_Plus || OO > OO_Arrow)
5023 return false;
5024
5025 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5026 if (IsArithmeticOp(OpKind)) {
5027 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005028 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005029 return true;
5030 }
5031 }
5032
5033 return false;
5034}
5035
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005036static bool IsLogicOp(BinaryOperatorKind Opc) {
5037 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5038}
5039
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005040/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5041/// or is a logical expression such as (x==y) which has int type, but is
5042/// commonly interpreted as boolean.
5043static bool ExprLooksBoolean(Expr *E) {
5044 E = E->IgnoreParenImpCasts();
5045
5046 if (E->getType()->isBooleanType())
5047 return true;
5048 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5049 return IsLogicOp(OP->getOpcode());
5050 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5051 return OP->getOpcode() == UO_LNot;
5052
5053 return false;
5054}
5055
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005056/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5057/// and binary operator are mixed in a way that suggests the programmer assumed
5058/// the conditional operator has higher precedence, for example:
5059/// "int x = a + someBinaryCondition ? 1 : 2".
5060static void DiagnoseConditionalPrecedence(Sema &Self,
5061 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005062 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005063 Expr *LHSExpr,
5064 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005065 BinaryOperatorKind CondOpcode;
5066 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005067
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005068 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005069 return;
5070 if (!ExprLooksBoolean(CondRHS))
5071 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005072
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005073 // The condition is an arithmetic binary expression, with a right-
5074 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005075
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005076 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005077 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005078 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005079
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005080 SuggestParentheses(Self, OpLoc,
5081 Self.PDiag(diag::note_precedence_conditional_silence)
5082 << BinaryOperator::getOpcodeStr(CondOpcode),
5083 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005084
5085 SuggestParentheses(Self, OpLoc,
5086 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005087 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005088}
5089
Steve Naroff83895f72007-09-16 03:34:24 +00005090/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005091/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005092ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005093 SourceLocation ColonLoc,
5094 Expr *CondExpr, Expr *LHSExpr,
5095 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005096 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5097 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005098 OpaqueValueExpr *opaqueValue = 0;
5099 Expr *commonExpr = 0;
5100 if (LHSExpr == 0) {
5101 commonExpr = CondExpr;
5102
5103 // We usually want to apply unary conversions *before* saving, except
5104 // in the special case of a C++ l-value conditional.
5105 if (!(getLangOptions().CPlusPlus
5106 && !commonExpr->isTypeDependent()
5107 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5108 && commonExpr->isGLValue()
5109 && commonExpr->isOrdinaryOrBitFieldObject()
5110 && RHSExpr->isOrdinaryOrBitFieldObject()
5111 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005112 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5113 if (commonRes.isInvalid())
5114 return ExprError();
5115 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005116 }
5117
5118 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5119 commonExpr->getType(),
5120 commonExpr->getValueKind(),
5121 commonExpr->getObjectKind());
5122 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005123 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005124
John McCall7decc9e2010-11-18 06:31:45 +00005125 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005126 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005127 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5128 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005129 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005130 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5131 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005132 return ExprError();
5133
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005134 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5135 RHS.get());
5136
John McCallc07a0c72011-02-17 10:25:35 +00005137 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005138 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5139 LHS.take(), ColonLoc,
5140 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005141
5142 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005143 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005144 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5145 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005146}
5147
John McCallaba90822011-01-31 23:13:11 +00005148// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005149// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005150// routine is it effectively iqnores the qualifiers on the top level pointee.
5151// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5152// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005153static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005154checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5155 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5156 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005157
Steve Naroff1f4d7272007-05-11 04:00:31 +00005158 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005159 const Type *lhptee, *rhptee;
5160 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005161 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5162 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163
John McCallaba90822011-01-31 23:13:11 +00005164 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
5166 // C99 6.5.16.1p1: This following citation is common to constraints
5167 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5168 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005169 Qualifiers lq;
5170
John McCall31168b02011-06-15 23:02:42 +00005171 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5172 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5173 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5174 // Ignore lifetime for further calculation.
5175 lhq.removeObjCLifetime();
5176 rhq.removeObjCLifetime();
5177 }
5178
John McCall4fff8f62011-02-01 00:10:29 +00005179 if (!lhq.compatiblyIncludes(rhq)) {
5180 // Treat address-space mismatches as fatal. TODO: address subspaces
5181 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5182 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5183
John McCall31168b02011-06-15 23:02:42 +00005184 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005185 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005186 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5187 .compatiblyIncludes(
5188 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005189 && (lhptee->isVoidType() || rhptee->isVoidType()))
5190 ; // keep old
5191
John McCall31168b02011-06-15 23:02:42 +00005192 // Treat lifetime mismatches as fatal.
5193 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5194 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5195
John McCall4fff8f62011-02-01 00:10:29 +00005196 // For GCC compatibility, other qualifier mismatches are treated
5197 // as still compatible in C.
5198 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5199 }
Steve Naroff3f597292007-05-11 22:18:03 +00005200
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5202 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005203 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005204 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005205 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005206 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005207
Chris Lattner0a788432008-01-03 22:56:36 +00005208 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005209 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005210 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005211 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005212
Chris Lattner0a788432008-01-03 22:56:36 +00005213 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005214 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005215 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005216
5217 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005218 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005219 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005220 }
John McCall4fff8f62011-02-01 00:10:29 +00005221
Mike Stump4e1f26a2009-02-19 03:04:26 +00005222 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005223 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005224 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5225 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005226 // Check if the pointee types are compatible ignoring the sign.
5227 // We explicitly check for char so that we catch "char" vs
5228 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005229 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005230 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005231 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005232 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005233
Chris Lattnerec3a1562009-10-17 20:33:28 +00005234 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005235 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005236 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005237 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005238
John McCall4fff8f62011-02-01 00:10:29 +00005239 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005240 // Types are compatible ignoring the sign. Qualifier incompatibility
5241 // takes priority over sign incompatibility because the sign
5242 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005243 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005244 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005245
John McCallaba90822011-01-31 23:13:11 +00005246 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005247 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005248
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005249 // If we are a multi-level pointer, it's possible that our issue is simply
5250 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5251 // the eventual target type is the same and the pointers have the same
5252 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005253 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005254 do {
John McCall4fff8f62011-02-01 00:10:29 +00005255 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5256 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005257 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005258
John McCall4fff8f62011-02-01 00:10:29 +00005259 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005260 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005261 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005262
Eli Friedman80160bd2009-03-22 23:59:44 +00005263 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005264 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005265 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005266 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005267}
5268
John McCallaba90822011-01-31 23:13:11 +00005269/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005270/// block pointer types are compatible or whether a block and normal pointer
5271/// are compatible. It is more restrict than comparing two function pointer
5272// types.
John McCallaba90822011-01-31 23:13:11 +00005273static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005274checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5275 QualType RHSType) {
5276 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5277 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005278
Steve Naroff081c7422008-09-04 15:10:53 +00005279 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005280
Steve Naroff081c7422008-09-04 15:10:53 +00005281 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005282 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5283 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005284
John McCallaba90822011-01-31 23:13:11 +00005285 // In C++, the types have to match exactly.
5286 if (S.getLangOptions().CPlusPlus)
5287 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005288
John McCallaba90822011-01-31 23:13:11 +00005289 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005290
Steve Naroff081c7422008-09-04 15:10:53 +00005291 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005292 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5293 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005294
Richard Trieua871b972011-09-06 20:21:22 +00005295 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005296 return Sema::IncompatibleBlockPointer;
5297
Steve Naroff081c7422008-09-04 15:10:53 +00005298 return ConvTy;
5299}
5300
John McCallaba90822011-01-31 23:13:11 +00005301/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005302/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005303static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005304checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5305 QualType RHSType) {
5306 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5307 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005308
Richard Trieua871b972011-09-06 20:21:22 +00005309 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005310 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005311 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5312 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005313 return Sema::IncompatiblePointer;
5314 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005315 }
Richard Trieua871b972011-09-06 20:21:22 +00005316 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005317 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5318 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005319 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005320 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005321 }
Richard Trieua871b972011-09-06 20:21:22 +00005322 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5323 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005324
John McCallaba90822011-01-31 23:13:11 +00005325 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5326 return Sema::CompatiblePointerDiscardsQualifiers;
5327
Richard Trieua871b972011-09-06 20:21:22 +00005328 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005329 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005330 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005331 return Sema::IncompatibleObjCQualifiedId;
5332 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005333}
5334
John McCall29600e12010-11-16 02:32:08 +00005335Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005336Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005337 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005338 // Fake up an opaque expression. We don't actually care about what
5339 // cast operations are required, so if CheckAssignmentConstraints
5340 // adds casts to this they'll be wasted, but fortunately that doesn't
5341 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005342 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5343 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005344 CastKind K = CK_Invalid;
5345
Richard Trieua871b972011-09-06 20:21:22 +00005346 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005347}
5348
Mike Stump4e1f26a2009-02-19 03:04:26 +00005349/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5350/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005351/// pointers. Here are some objectionable examples that GCC considers warnings:
5352///
5353/// int a, *pint;
5354/// short *pshort;
5355/// struct foo *pfoo;
5356///
5357/// pint = pshort; // warning: assignment from incompatible pointer type
5358/// a = pint; // warning: assignment makes integer from pointer without a cast
5359/// pint = a; // warning: assignment makes pointer from integer without a cast
5360/// pint = pfoo; // warning: assignment from incompatible pointer type
5361///
5362/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005363/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005364///
John McCall8cb679e2010-11-15 09:13:47 +00005365/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005366Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005367Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005368 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005369 QualType RHSType = RHS.get()->getType();
5370 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005371
Chris Lattnera52c2f22008-01-04 23:18:45 +00005372 // Get canonical types. We're not formatting these types, just comparing
5373 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005374 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5375 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005376
John McCalle5255932011-01-31 22:28:28 +00005377 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005378 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005379 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005380 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005381 }
5382
Douglas Gregor6b754842008-10-28 00:22:11 +00005383 // If the left-hand side is a reference type, then we are in a
5384 // (rare!) case where we've allowed the use of references in C,
5385 // e.g., as a parameter type in a built-in function. In this case,
5386 // just make sure that the type referenced is compatible with the
5387 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005388 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005389 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005390 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5391 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005392 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005393 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005394 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005395 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005396 }
John McCalle5255932011-01-31 22:28:28 +00005397
Nate Begemanbd956c42009-06-28 02:36:38 +00005398 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5399 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005400 if (LHSType->isExtVectorType()) {
5401 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005402 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005403 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005404 // CK_VectorSplat does T -> vector T, so first cast to the
5405 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005406 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5407 if (elType != RHSType) {
5408 Kind = PrepareScalarCast(*this, RHS, elType);
5409 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005410 }
5411 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005412 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005413 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005414 }
Mike Stump11289f42009-09-09 15:08:12 +00005415
John McCalle5255932011-01-31 22:28:28 +00005416 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005417 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5418 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005419 // Allow assignments of an AltiVec vector type to an equivalent GCC
5420 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005421 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005422 Kind = CK_BitCast;
5423 return Compatible;
5424 }
5425
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005426 // If we are allowing lax vector conversions, and LHS and RHS are both
5427 // vectors, the total size only needs to be the same. This is a bitcast;
5428 // no bits are changed but the result type is different.
5429 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005430 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005431 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005432 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005433 }
Chris Lattner881a2122008-01-04 23:32:24 +00005434 }
5435 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005436 }
Eli Friedman3360d892008-05-30 18:07:22 +00005437
John McCalle5255932011-01-31 22:28:28 +00005438 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005439 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5440 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5441 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005442 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005443 }
Eli Friedman3360d892008-05-30 18:07:22 +00005444
John McCalle5255932011-01-31 22:28:28 +00005445 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005446 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005447 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005448 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005449 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005450 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005451 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005452
John McCalle5255932011-01-31 22:28:28 +00005453 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005454 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005455 Kind = CK_IntegralToPointer; // FIXME: null?
5456 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005457 }
John McCalle5255932011-01-31 22:28:28 +00005458
5459 // C pointers are not compatible with ObjC object pointers,
5460 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005461 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005462 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005463 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005464 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005465 return Compatible;
5466 }
5467
5468 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005469 if (RHSType->isObjCClassType() &&
5470 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005471 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005472 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005473 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005474 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005475
John McCalle5255932011-01-31 22:28:28 +00005476 Kind = CK_BitCast;
5477 return IncompatiblePointer;
5478 }
5479
5480 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005481 if (RHSType->getAs<BlockPointerType>()) {
5482 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005483 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005484 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005485 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005486 }
John McCalle5255932011-01-31 22:28:28 +00005487
Steve Naroff081c7422008-09-04 15:10:53 +00005488 return Incompatible;
5489 }
5490
John McCalle5255932011-01-31 22:28:28 +00005491 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005492 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005493 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005494 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005495 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005496 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005497 }
5498
5499 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005500 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005501 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005502 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005503 }
5504
John McCalle5255932011-01-31 22:28:28 +00005505 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005506 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005507 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005508 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005509 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005510
John McCalle5255932011-01-31 22:28:28 +00005511 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005512 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005513 if (RHSPT->getPointeeType()->isVoidType()) {
5514 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005515 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005516 }
John McCall8cb679e2010-11-15 09:13:47 +00005517
Chris Lattnera52c2f22008-01-04 23:18:45 +00005518 return Incompatible;
5519 }
5520
John McCalle5255932011-01-31 22:28:28 +00005521 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005522 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005523 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005524 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005525 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005526 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005527 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005528 if (getLangOptions().ObjCAutoRefCount &&
5529 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005530 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005531 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005532 return result;
John McCalle5255932011-01-31 22:28:28 +00005533 }
5534
5535 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005536 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005537 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005538 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005539 }
5540
John McCalle5255932011-01-31 22:28:28 +00005541 // In general, C pointers are not compatible with ObjC object pointers,
5542 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005543 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005544 Kind = CK_CPointerToObjCPointerCast;
5545
John McCalle5255932011-01-31 22:28:28 +00005546 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005547 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005548 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005549 }
5550
5551 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005552 if (LHSType->isObjCClassType() &&
5553 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005554 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005555 return Compatible;
5556 }
5557
Steve Naroffaccc4882009-07-20 17:56:53 +00005558 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005559 }
John McCalle5255932011-01-31 22:28:28 +00005560
5561 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005562 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005563 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005564 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005565 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005566 }
5567
Steve Naroff7cae42b2009-07-10 23:34:53 +00005568 return Incompatible;
5569 }
John McCalle5255932011-01-31 22:28:28 +00005570
5571 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005572 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005573 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005574 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005575 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005576 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005577 }
Eli Friedman3360d892008-05-30 18:07:22 +00005578
John McCalle5255932011-01-31 22:28:28 +00005579 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005580 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005581 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005582 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005583 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005584
Chris Lattnera52c2f22008-01-04 23:18:45 +00005585 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005586 }
John McCalle5255932011-01-31 22:28:28 +00005587
5588 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005589 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005590 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005591 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005592 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005593 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005594 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595
John McCalle5255932011-01-31 22:28:28 +00005596 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005597 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005598 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005599 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005600 }
5601
Steve Naroff7cae42b2009-07-10 23:34:53 +00005602 return Incompatible;
5603 }
Eli Friedman3360d892008-05-30 18:07:22 +00005604
John McCalle5255932011-01-31 22:28:28 +00005605 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005606 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5607 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005608 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005609 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005610 }
Bill Wendling216423b2007-05-30 06:30:29 +00005611 }
John McCalle5255932011-01-31 22:28:28 +00005612
Steve Naroff98cf3e92007-06-06 18:38:38 +00005613 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005614}
5615
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005616/// \brief Constructs a transparent union from an expression that is
5617/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005618static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5619 ExprResult &EResult, QualType UnionType,
5620 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005621 // Build an initializer list that designates the appropriate member
5622 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005623 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005624 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005625 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005626 SourceLocation());
5627 Initializer->setType(UnionType);
5628 Initializer->setInitializedFieldInUnion(Field);
5629
5630 // Build a compound literal constructing a value of the transparent
5631 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005632 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005633 EResult = S.Owned(
5634 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5635 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005636}
5637
5638Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005639Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005640 ExprResult &RHS) {
5641 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005642
Mike Stump11289f42009-09-09 15:08:12 +00005643 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005644 // transparent_union GCC extension.
5645 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005646 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005647 return Incompatible;
5648
5649 // The field to initialize within the transparent union.
5650 RecordDecl *UD = UT->getDecl();
5651 FieldDecl *InitField = 0;
5652 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005653 for (RecordDecl::field_iterator it = UD->field_begin(),
5654 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005655 it != itend; ++it) {
5656 if (it->getType()->isPointerType()) {
5657 // If the transparent union contains a pointer type, we allow:
5658 // 1) void pointer
5659 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005660 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005661 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005662 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005663 InitField = *it;
5664 break;
5665 }
Mike Stump11289f42009-09-09 15:08:12 +00005666
Richard Trieueb299142011-09-06 20:40:12 +00005667 if (RHS.get()->isNullPointerConstant(Context,
5668 Expr::NPC_ValueDependentIsNull)) {
5669 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5670 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005671 InitField = *it;
5672 break;
5673 }
5674 }
5675
John McCall8cb679e2010-11-15 09:13:47 +00005676 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005677 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005678 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005679 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005680 InitField = *it;
5681 break;
5682 }
5683 }
5684
5685 if (!InitField)
5686 return Incompatible;
5687
Richard Trieueb299142011-09-06 20:40:12 +00005688 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005689 return Compatible;
5690}
5691
Chris Lattner9bad62c2008-01-04 18:04:52 +00005692Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005693Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5694 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005695 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005696 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005697 // C++ 5.17p3: If the left operand is not of class type, the
5698 // expression is implicitly converted (C++ 4) to the
5699 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005700 ExprResult Res = PerformImplicitConversion(RHS.get(),
5701 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005702 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005703 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005704 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005705 Sema::AssignConvertType result = Compatible;
5706 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005707 !CheckObjCARCUnavailableWeakConversion(LHSType,
5708 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005709 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005710 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005711 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005712 }
5713
5714 // FIXME: Currently, we fall through and treat C++ classes like C
5715 // structures.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005716 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005717
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005718 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5719 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005720 if ((LHSType->isPointerType() ||
5721 LHSType->isObjCObjectPointerType() ||
5722 LHSType->isBlockPointerType())
5723 && RHS.get()->isNullPointerConstant(Context,
5724 Expr::NPC_ValueDependentIsNull)) {
5725 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005726 return Compatible;
5727 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005728
Chris Lattnere6dcd502007-10-16 02:55:40 +00005729 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005730 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005731 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005732 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005733 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005734 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005735 if (!LHSType->isReferenceType()) {
5736 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5737 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005738 return Incompatible;
5739 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005740
John McCall8cb679e2010-11-15 09:13:47 +00005741 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005742 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005743 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005744
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005745 // C99 6.5.16.1p2: The value of the right operand is converted to the
5746 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005747 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5748 // so that we can use references in built-in functions even in C.
5749 // The getNonReferenceType() call makes sure that the resulting expression
5750 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005751 if (result != Incompatible && RHS.get()->getType() != LHSType)
5752 RHS = ImpCastExprToType(RHS.take(),
5753 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005754 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005755}
5756
Richard Trieueb299142011-09-06 20:40:12 +00005757QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5758 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005759 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005760 << LHS.get()->getType() << RHS.get()->getType()
5761 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005762 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005763}
5764
Richard Trieu859d23f2011-09-06 21:01:04 +00005765QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005766 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005767 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005768 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005769 QualType LHSType =
5770 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5771 QualType RHSType =
5772 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005773
Nate Begeman191a6b12008-07-14 18:02:46 +00005774 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005775 if (LHSType == RHSType)
5776 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005777
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005778 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005779 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5780 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5781 if (LHSType->isExtVectorType()) {
5782 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5783 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005784 }
5785
Richard Trieuba63ce62011-09-09 01:45:06 +00005786 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005787 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5788 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005789 }
5790
Eli Friedman1408bc92011-06-23 18:10:35 +00005791 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005792 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005793 // If we are allowing lax vector conversions, and LHS and RHS are both
5794 // vectors, the total size only needs to be the same. This is a
5795 // bitcast; no bits are changed but the result type is different.
5796 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005797 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5798 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005799 }
5800
Nate Begemanbd956c42009-06-28 02:36:38 +00005801 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5802 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5803 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005804 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005805 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005806 std::swap(RHS, LHS);
5807 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005808 }
Mike Stump11289f42009-09-09 15:08:12 +00005809
Nate Begeman886448d2009-06-28 19:12:57 +00005810 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005811 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005812 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005813 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5814 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005815 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005816 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005817 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005818 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5819 if (swapped) std::swap(RHS, LHS);
5820 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005821 }
5822 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005823 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5824 RHSType->isRealFloatingType()) {
5825 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005826 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005827 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005828 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005829 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5830 if (swapped) std::swap(RHS, LHS);
5831 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005832 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005833 }
5834 }
Mike Stump11289f42009-09-09 15:08:12 +00005835
Nate Begeman886448d2009-06-28 19:12:57 +00005836 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005837 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005838 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005839 << LHS.get()->getType() << RHS.get()->getType()
5840 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005841 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005842}
5843
Richard Trieuf8916e12011-09-16 00:53:10 +00005844// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5845// expression. These are mainly cases where the null pointer is used as an
5846// integer instead of a pointer.
5847static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5848 SourceLocation Loc, bool IsCompare) {
5849 // The canonical way to check for a GNU null is with isNullPointerConstant,
5850 // but we use a bit of a hack here for speed; this is a relatively
5851 // hot path, and isNullPointerConstant is slow.
5852 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5853 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5854
5855 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5856
5857 // Avoid analyzing cases where the result will either be invalid (and
5858 // diagnosed as such) or entirely valid and not something to warn about.
5859 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5860 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5861 return;
5862
5863 // Comparison operations would not make sense with a null pointer no matter
5864 // what the other expression is.
5865 if (!IsCompare) {
5866 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5867 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5868 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5869 return;
5870 }
5871
5872 // The rest of the operations only make sense with a null pointer
5873 // if the other expression is a pointer.
5874 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5875 NonNullType->canDecayToPointerType())
5876 return;
5877
5878 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5879 << LHSNull /* LHS is NULL */ << NonNullType
5880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5881}
5882
Richard Trieu859d23f2011-09-06 21:01:04 +00005883QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005884 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005885 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005886 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5887
Richard Trieu859d23f2011-09-06 21:01:04 +00005888 if (LHS.get()->getType()->isVectorType() ||
5889 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005890 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005891
Richard Trieuba63ce62011-09-09 01:45:06 +00005892 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005893 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005894 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005895
Richard Trieu859d23f2011-09-06 21:01:04 +00005896 if (!LHS.get()->getType()->isArithmeticType() ||
5897 !RHS.get()->getType()->isArithmeticType())
5898 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005899
Chris Lattnerfaa54172010-01-12 21:23:57 +00005900 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005901 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005902 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005903 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005904 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5905 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005906
Chris Lattnerfaa54172010-01-12 21:23:57 +00005907 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005908}
5909
Chris Lattnerfaa54172010-01-12 21:23:57 +00005910QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005911 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005912 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5913
Richard Trieu859d23f2011-09-06 21:01:04 +00005914 if (LHS.get()->getType()->isVectorType() ||
5915 RHS.get()->getType()->isVectorType()) {
5916 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5917 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005918 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005919 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005920 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005921
Richard Trieuba63ce62011-09-09 01:45:06 +00005922 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005923 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005924 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005925
Richard Trieu859d23f2011-09-06 21:01:04 +00005926 if (!LHS.get()->getType()->isIntegerType() ||
5927 !RHS.get()->getType()->isIntegerType())
5928 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005929
Chris Lattnerfaa54172010-01-12 21:23:57 +00005930 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005931 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005932 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005933 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5934 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005935
Chris Lattnerfaa54172010-01-12 21:23:57 +00005936 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005937}
5938
Chandler Carruthc9332212011-06-27 08:02:19 +00005939/// \brief Diagnose invalid arithmetic on two void pointers.
5940static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005941 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005942 S.Diag(Loc, S.getLangOptions().CPlusPlus
5943 ? diag::err_typecheck_pointer_arith_void_type
5944 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005945 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5946 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005947}
5948
5949/// \brief Diagnose invalid arithmetic on a void pointer.
5950static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5951 Expr *Pointer) {
5952 S.Diag(Loc, S.getLangOptions().CPlusPlus
5953 ? diag::err_typecheck_pointer_arith_void_type
5954 : diag::ext_gnu_void_ptr)
5955 << 0 /* one pointer */ << Pointer->getSourceRange();
5956}
5957
5958/// \brief Diagnose invalid arithmetic on two function pointers.
5959static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5960 Expr *LHS, Expr *RHS) {
5961 assert(LHS->getType()->isAnyPointerType());
5962 assert(RHS->getType()->isAnyPointerType());
5963 S.Diag(Loc, S.getLangOptions().CPlusPlus
5964 ? diag::err_typecheck_pointer_arith_function_type
5965 : diag::ext_gnu_ptr_func_arith)
5966 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5967 // We only show the second type if it differs from the first.
5968 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5969 RHS->getType())
5970 << RHS->getType()->getPointeeType()
5971 << LHS->getSourceRange() << RHS->getSourceRange();
5972}
5973
5974/// \brief Diagnose invalid arithmetic on a function pointer.
5975static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5976 Expr *Pointer) {
5977 assert(Pointer->getType()->isAnyPointerType());
5978 S.Diag(Loc, S.getLangOptions().CPlusPlus
5979 ? diag::err_typecheck_pointer_arith_function_type
5980 : diag::ext_gnu_ptr_func_arith)
5981 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5982 << 0 /* one pointer, so only one type */
5983 << Pointer->getSourceRange();
5984}
5985
Richard Trieu993f3ab2011-09-12 18:08:02 +00005986/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005987///
5988/// \returns True if pointer has incomplete type
5989static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5990 Expr *Operand) {
5991 if ((Operand->getType()->isPointerType() &&
5992 !Operand->getType()->isDependentType()) ||
5993 Operand->getType()->isObjCObjectPointerType()) {
5994 QualType PointeeTy = Operand->getType()->getPointeeType();
5995 if (S.RequireCompleteType(
5996 Loc, PointeeTy,
5997 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5998 << PointeeTy << Operand->getSourceRange()))
5999 return true;
6000 }
6001 return false;
6002}
6003
Chandler Carruthc9332212011-06-27 08:02:19 +00006004/// \brief Check the validity of an arithmetic pointer operand.
6005///
6006/// If the operand has pointer type, this code will check for pointer types
6007/// which are invalid in arithmetic operations. These will be diagnosed
6008/// appropriately, including whether or not the use is supported as an
6009/// extension.
6010///
6011/// \returns True when the operand is valid to use (even if as an extension).
6012static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6013 Expr *Operand) {
6014 if (!Operand->getType()->isAnyPointerType()) return true;
6015
6016 QualType PointeeTy = Operand->getType()->getPointeeType();
6017 if (PointeeTy->isVoidType()) {
6018 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6019 return !S.getLangOptions().CPlusPlus;
6020 }
6021 if (PointeeTy->isFunctionType()) {
6022 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6023 return !S.getLangOptions().CPlusPlus;
6024 }
6025
Richard Trieuaba22802011-09-02 02:15:37 +00006026 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006027
6028 return true;
6029}
6030
6031/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6032/// operands.
6033///
6034/// This routine will diagnose any invalid arithmetic on pointer operands much
6035/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6036/// for emitting a single diagnostic even for operations where both LHS and RHS
6037/// are (potentially problematic) pointers.
6038///
6039/// \returns True when the operand is valid to use (even if as an extension).
6040static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006041 Expr *LHSExpr, Expr *RHSExpr) {
6042 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6043 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006044 if (!isLHSPointer && !isRHSPointer) return true;
6045
6046 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006047 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6048 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006049
6050 // Check for arithmetic on pointers to incomplete types.
6051 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6052 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6053 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006054 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6055 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6056 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006057
6058 return !S.getLangOptions().CPlusPlus;
6059 }
6060
6061 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6062 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6063 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006064 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6065 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6066 RHSExpr);
6067 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006068
6069 return !S.getLangOptions().CPlusPlus;
6070 }
6071
Richard Trieu4ae7e972011-09-06 21:13:51 +00006072 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6073 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006074
Chandler Carruthc9332212011-06-27 08:02:19 +00006075 return true;
6076}
6077
Richard Trieub10c6312011-09-01 22:53:23 +00006078/// \brief Check bad cases where we step over interface counts.
6079static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6080 SourceLocation OpLoc,
6081 Expr *Op) {
6082 assert(Op->getType()->isAnyPointerType());
6083 QualType PointeeTy = Op->getType()->getPointeeType();
6084 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6085 return true;
6086
6087 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6088 << PointeeTy << Op->getSourceRange();
6089 return false;
6090}
6091
Richard Trieu993f3ab2011-09-12 18:08:02 +00006092/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006093static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006094 Expr *LHSExpr, Expr *RHSExpr) {
6095 assert(LHSExpr->getType()->isAnyPointerType());
6096 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006097 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006098 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6099 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006100}
6101
Chris Lattnerfaa54172010-01-12 21:23:57 +00006102QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006103 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006104 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6105
Richard Trieu4ae7e972011-09-06 21:13:51 +00006106 if (LHS.get()->getType()->isVectorType() ||
6107 RHS.get()->getType()->isVectorType()) {
6108 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006109 if (CompLHSTy) *CompLHSTy = compType;
6110 return compType;
6111 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006112
Richard Trieu4ae7e972011-09-06 21:13:51 +00006113 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6114 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006115 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006116
Steve Naroffe4718892007-04-27 18:30:00 +00006117 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006118 if (LHS.get()->getType()->isArithmeticType() &&
6119 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006120 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006121 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006122 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006123
Eli Friedman8e122982008-05-18 18:08:51 +00006124 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006125 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006126 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006127 std::swap(PExp, IExp);
6128
Richard Trieub420bca2011-09-12 18:37:54 +00006129 if (!PExp->getType()->isAnyPointerType())
6130 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006131
Richard Trieub420bca2011-09-12 18:37:54 +00006132 if (!IExp->getType()->isIntegerType())
6133 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006134
Richard Trieub420bca2011-09-12 18:37:54 +00006135 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6136 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006137
Richard Trieub420bca2011-09-12 18:37:54 +00006138 // Diagnose bad cases where we step over interface counts.
6139 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6140 return QualType();
6141
6142 // Check array bounds for pointer arithemtic
6143 CheckArrayAccess(PExp, IExp);
6144
6145 if (CompLHSTy) {
6146 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6147 if (LHSTy.isNull()) {
6148 LHSTy = LHS.get()->getType();
6149 if (LHSTy->isPromotableIntegerType())
6150 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006151 }
Richard Trieub420bca2011-09-12 18:37:54 +00006152 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006153 }
6154
Richard Trieub420bca2011-09-12 18:37:54 +00006155 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006156}
6157
Chris Lattner2a3569b2008-04-07 05:30:13 +00006158// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006159QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006160 SourceLocation Loc,
6161 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006162 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6163
Richard Trieu4ae7e972011-09-06 21:13:51 +00006164 if (LHS.get()->getType()->isVectorType() ||
6165 RHS.get()->getType()->isVectorType()) {
6166 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006167 if (CompLHSTy) *CompLHSTy = compType;
6168 return compType;
6169 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006170
Richard Trieu4ae7e972011-09-06 21:13:51 +00006171 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6172 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006173 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006174
Chris Lattner4d62f422007-12-09 21:53:25 +00006175 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006176
Chris Lattner4d62f422007-12-09 21:53:25 +00006177 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006178 if (LHS.get()->getType()->isArithmeticType() &&
6179 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006180 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006181 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006182 }
Mike Stump11289f42009-09-09 15:08:12 +00006183
Chris Lattner4d62f422007-12-09 21:53:25 +00006184 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006185 if (LHS.get()->getType()->isAnyPointerType()) {
6186 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006187
Chris Lattner12bdebb2009-04-24 23:50:08 +00006188 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006189 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006190 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006191
Chris Lattner4d62f422007-12-09 21:53:25 +00006192 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006193 if (RHS.get()->getType()->isIntegerType()) {
6194 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006195 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006196
Richard Trieu4ae7e972011-09-06 21:13:51 +00006197 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006198 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6199 OK_Ordinary, IExpr->getExprLoc());
6200 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006201 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006202
Richard Trieu4ae7e972011-09-06 21:13:51 +00006203 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6204 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006205 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006206
Chris Lattner4d62f422007-12-09 21:53:25 +00006207 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006208 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006209 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006210 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006211
Eli Friedman168fe152009-05-16 13:54:38 +00006212 if (getLangOptions().CPlusPlus) {
6213 // Pointee types must be the same: C++ [expr.add]
6214 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006215 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006216 }
6217 } else {
6218 // Pointee types must be compatible C99 6.5.6p3
6219 if (!Context.typesAreCompatible(
6220 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6221 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006222 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006223 return QualType();
6224 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006225 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006226
Chandler Carruthc9332212011-06-27 08:02:19 +00006227 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006228 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006229 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006230
Richard Trieu4ae7e972011-09-06 21:13:51 +00006231 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006232 return Context.getPointerDiffType();
6233 }
6234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235
Richard Trieu4ae7e972011-09-06 21:13:51 +00006236 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006237}
6238
Douglas Gregor0bf31402010-10-08 23:50:27 +00006239static bool isScopedEnumerationType(QualType T) {
6240 if (const EnumType *ET = dyn_cast<EnumType>(T))
6241 return ET->getDecl()->isScoped();
6242 return false;
6243}
6244
Richard Trieue4a19fb2011-09-06 21:21:28 +00006245static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006246 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006247 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006248 llvm::APSInt Right;
6249 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006250 if (RHS.get()->isValueDependent() ||
6251 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006252 return;
6253
6254 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006255 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006256 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006257 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006258 return;
6259 }
6260 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006261 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006262 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006263 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006264 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006265 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006266 return;
6267 }
6268 if (Opc != BO_Shl)
6269 return;
6270
6271 // When left shifting an ICE which is signed, we can check for overflow which
6272 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6273 // integers have defined behavior modulo one more than the maximum value
6274 // representable in the result type, so never warn for those.
6275 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006276 if (LHS.get()->isValueDependent() ||
6277 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6278 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006279 return;
6280 llvm::APInt ResultBits =
6281 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6282 if (LeftBits.uge(ResultBits))
6283 return;
6284 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6285 Result = Result.shl(Right);
6286
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006287 // Print the bit representation of the signed integer as an unsigned
6288 // hexadecimal number.
6289 llvm::SmallString<40> HexResult;
6290 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6291
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006292 // If we are only missing a sign bit, this is less likely to result in actual
6293 // bugs -- if the result is cast back to an unsigned type, it will have the
6294 // expected value. Thus we place this behind a different warning that can be
6295 // turned off separately if needed.
6296 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006297 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006298 << HexResult.str() << LHSType
6299 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006300 return;
6301 }
6302
6303 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006304 << HexResult.str() << Result.getMinSignedBits() << LHSType
6305 << Left.getBitWidth() << LHS.get()->getSourceRange()
6306 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006307}
6308
Chris Lattner2a3569b2008-04-07 05:30:13 +00006309// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006310QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006311 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006312 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006313 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6314
Chris Lattner5c11c412007-12-12 05:47:28 +00006315 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006316 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6317 !RHS.get()->getType()->hasIntegerRepresentation())
6318 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319
Douglas Gregor0bf31402010-10-08 23:50:27 +00006320 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6321 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006322 if (isScopedEnumerationType(LHS.get()->getType()) ||
6323 isScopedEnumerationType(RHS.get()->getType())) {
6324 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006325 }
6326
Nate Begemane46ee9a2009-10-25 02:26:48 +00006327 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006328 if (LHS.get()->getType()->isVectorType() ||
6329 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006330 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006331
Chris Lattner5c11c412007-12-12 05:47:28 +00006332 // Shifts don't perform usual arithmetic conversions, they just do integer
6333 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006334
John McCall57cdd882010-12-16 19:28:59 +00006335 // For the LHS, do usual unary conversions, but then reset them away
6336 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006337 ExprResult OldLHS = LHS;
6338 LHS = UsualUnaryConversions(LHS.take());
6339 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006340 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006341 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006342 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006343
6344 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006345 RHS = UsualUnaryConversions(RHS.take());
6346 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006347 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Ryan Flynnf53fab82009-08-07 16:20:20 +00006349 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006350 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006351
Chris Lattner5c11c412007-12-12 05:47:28 +00006352 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006353 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006354}
6355
Chandler Carruth17773fc2010-07-10 12:30:03 +00006356static bool IsWithinTemplateSpecialization(Decl *D) {
6357 if (DeclContext *DC = D->getDeclContext()) {
6358 if (isa<ClassTemplateSpecializationDecl>(DC))
6359 return true;
6360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6361 return FD->isFunctionTemplateSpecialization();
6362 }
6363 return false;
6364}
6365
Richard Trieueea56f72011-09-02 03:48:46 +00006366/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006367static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6368 ExprResult &RHS) {
6369 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6370 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006371
6372 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6373 if (!LHSEnumType)
6374 return;
6375 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6376 if (!RHSEnumType)
6377 return;
6378
6379 // Ignore anonymous enums.
6380 if (!LHSEnumType->getDecl()->getIdentifier())
6381 return;
6382 if (!RHSEnumType->getDecl()->getIdentifier())
6383 return;
6384
6385 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6386 return;
6387
6388 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6389 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006391}
6392
Richard Trieudd82a5c2011-09-02 02:55:45 +00006393/// \brief Diagnose bad pointer comparisons.
6394static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006395 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006396 bool IsError) {
6397 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006398 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006399 << LHS.get()->getType() << RHS.get()->getType()
6400 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006401}
6402
6403/// \brief Returns false if the pointers are converted to a composite type,
6404/// true otherwise.
6405static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006406 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006407 // C++ [expr.rel]p2:
6408 // [...] Pointer conversions (4.10) and qualification
6409 // conversions (4.4) are performed on pointer operands (or on
6410 // a pointer operand and a null pointer constant) to bring
6411 // them to their composite pointer type. [...]
6412 //
6413 // C++ [expr.eq]p1 uses the same notion for (in)equality
6414 // comparisons of pointers.
6415
6416 // C++ [expr.eq]p2:
6417 // In addition, pointers to members can be compared, or a pointer to
6418 // member and a null pointer constant. Pointer to member conversions
6419 // (4.11) and qualification conversions (4.4) are performed to bring
6420 // them to a common type. If one operand is a null pointer constant,
6421 // the common type is the type of the other operand. Otherwise, the
6422 // common type is a pointer to member type similar (4.4) to the type
6423 // of one of the operands, with a cv-qualification signature (4.4)
6424 // that is the union of the cv-qualification signatures of the operand
6425 // types.
6426
Richard Trieu1762d7c2011-09-06 21:27:33 +00006427 QualType LHSType = LHS.get()->getType();
6428 QualType RHSType = RHS.get()->getType();
6429 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6430 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006431
6432 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006433 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006434 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006435 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006436 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006437 return true;
6438 }
6439
6440 if (NonStandardCompositeType)
6441 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006442 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6443 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006444
Richard Trieu1762d7c2011-09-06 21:27:33 +00006445 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6446 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006447 return false;
6448}
6449
6450static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006451 ExprResult &LHS,
6452 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006453 bool IsError) {
6454 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6455 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006456 << LHS.get()->getType() << RHS.get()->getType()
6457 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006458}
6459
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006460// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006461QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006462 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006463 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006464 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6465
John McCalle3027922010-08-25 11:45:40 +00006466 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006467
Chris Lattner9a152e22009-12-05 05:40:13 +00006468 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006469 if (LHS.get()->getType()->isVectorType() ||
6470 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006471 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006472
Richard Trieub80728f2011-09-06 21:43:51 +00006473 QualType LHSType = LHS.get()->getType();
6474 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006475
Richard Trieub80728f2011-09-06 21:43:51 +00006476 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6477 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006478
Richard Trieub80728f2011-09-06 21:43:51 +00006479 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006480
Richard Trieub80728f2011-09-06 21:43:51 +00006481 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006482 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006483 !LHS.get()->getLocStart().isMacroID() &&
6484 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006485 // For non-floating point types, check for self-comparisons of the form
6486 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6487 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006488 //
6489 // NOTE: Don't warn about comparison expressions resulting from macro
6490 // expansion. Also don't warn about comparisons which are only self
6491 // comparisons within a template specialization. The warnings should catch
6492 // obvious cases in the definition of the template anyways. The idea is to
6493 // warn when the typed comparison operator will always evaluate to the same
6494 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006495 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006496 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006497 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006498 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006499 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006500 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006501 << (Opc == BO_EQ
6502 || Opc == BO_LE
6503 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006504 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006505 !DRL->getDecl()->getType()->isReferenceType() &&
6506 !DRR->getDecl()->getType()->isReferenceType()) {
6507 // what is it always going to eval to?
6508 char always_evals_to;
6509 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006510 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006511 always_evals_to = 0; // false
6512 break;
John McCalle3027922010-08-25 11:45:40 +00006513 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006514 always_evals_to = 1; // true
6515 break;
6516 default:
6517 // best we can say is 'a constant'
6518 always_evals_to = 2; // e.g. array1 <= array2
6519 break;
6520 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006521 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006522 << 1 // array
6523 << always_evals_to);
6524 }
6525 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006526 }
Mike Stump11289f42009-09-09 15:08:12 +00006527
Chris Lattner222b8bd2009-03-08 19:39:53 +00006528 if (isa<CastExpr>(LHSStripped))
6529 LHSStripped = LHSStripped->IgnoreParenCasts();
6530 if (isa<CastExpr>(RHSStripped))
6531 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006532
Chris Lattner222b8bd2009-03-08 19:39:53 +00006533 // Warn about comparisons against a string constant (unless the other
6534 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006535 Expr *literalString = 0;
6536 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006537 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006538 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006539 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006540 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006541 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006542 } else if ((isa<StringLiteral>(RHSStripped) ||
6543 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006544 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006545 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006546 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006547 literalStringStripped = RHSStripped;
6548 }
6549
6550 if (literalString) {
6551 std::string resultComparison;
6552 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006553 case BO_LT: resultComparison = ") < 0"; break;
6554 case BO_GT: resultComparison = ") > 0"; break;
6555 case BO_LE: resultComparison = ") <= 0"; break;
6556 case BO_GE: resultComparison = ") >= 0"; break;
6557 case BO_EQ: resultComparison = ") == 0"; break;
6558 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006559 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006560 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006561
Ted Kremenek3427fac2011-02-23 01:52:04 +00006562 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006563 PDiag(diag::warn_stringcompare)
6564 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006565 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006566 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006567 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006568
Douglas Gregorec170db2010-06-08 19:50:34 +00006569 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006570 if (LHS.get()->getType()->isArithmeticType() &&
6571 RHS.get()->getType()->isArithmeticType()) {
6572 UsualArithmeticConversions(LHS, RHS);
6573 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006574 return QualType();
6575 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006576 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006577 LHS = UsualUnaryConversions(LHS.take());
6578 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006579 return QualType();
6580
Richard Trieub80728f2011-09-06 21:43:51 +00006581 RHS = UsualUnaryConversions(RHS.take());
6582 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006583 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006584 }
6585
Richard Trieub80728f2011-09-06 21:43:51 +00006586 LHSType = LHS.get()->getType();
6587 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006588
Douglas Gregorca63811b2008-11-19 03:25:36 +00006589 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006590 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006591
Richard Trieuba63ce62011-09-09 01:45:06 +00006592 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006593 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006594 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006595 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006596 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006597 if (LHSType->hasFloatingRepresentation())
6598 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006599
Richard Trieub80728f2011-09-06 21:43:51 +00006600 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006601 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006602 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006603
Richard Trieub80728f2011-09-06 21:43:51 +00006604 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006605 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006606 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006607 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006608
Douglas Gregorf267edd2010-06-15 21:38:40 +00006609 // All of the following pointer-related warnings are GCC extensions, except
6610 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006611 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006612 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006613 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006614 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006615 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006616
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006617 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006618 if (LCanPointeeTy == RCanPointeeTy)
6619 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006620 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006621 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6622 // Valid unless comparison between non-null pointer and function pointer
6623 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006624 // In a SFINAE context, we treat this as a hard error to maintain
6625 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006626 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6627 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006628 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006629 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006630
6631 if (isSFINAEContext())
6632 return QualType();
6633
Richard Trieub80728f2011-09-06 21:43:51 +00006634 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006635 return ResultTy;
6636 }
6637 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006638
Richard Trieub80728f2011-09-06 21:43:51 +00006639 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006640 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006641 else
6642 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006643 }
Eli Friedman16c209612009-08-23 00:27:47 +00006644 // C99 6.5.9p2 and C99 6.5.8p2
6645 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6646 RCanPointeeTy.getUnqualifiedType())) {
6647 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006648 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006649 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006650 << LHSType << RHSType << LHS.get()->getSourceRange()
6651 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006652 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006653 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006654 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6655 // Valid unless comparison between non-null pointer and function pointer
6656 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006657 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006658 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006659 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006660 } else {
6661 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006662 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006663 }
John McCall7684dde2011-03-11 04:25:25 +00006664 if (LCanPointeeTy != RCanPointeeTy) {
6665 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006666 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006667 else
Richard Trieub80728f2011-09-06 21:43:51 +00006668 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006669 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006670 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006671 }
Mike Stump11289f42009-09-09 15:08:12 +00006672
Sebastian Redl576fd422009-05-10 18:38:11 +00006673 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006674 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006675 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006676 return ResultTy;
6677
Mike Stump11289f42009-09-09 15:08:12 +00006678 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006679 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006680 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006681 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006682 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006683 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6684 RHS = ImpCastExprToType(RHS.take(), LHSType,
6685 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006686 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006687 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006688 return ResultTy;
6689 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006690 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006691 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006692 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006693 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6694 LHS = ImpCastExprToType(LHS.take(), RHSType,
6695 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006696 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006697 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006698 return ResultTy;
6699 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006700
6701 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006702 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006703 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6704 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006705 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006706 else
6707 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006708 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006709
6710 // Handle scoped enumeration types specifically, since they don't promote
6711 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006712 if (LHS.get()->getType()->isEnumeralType() &&
6713 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6714 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006715 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006716 }
Mike Stump11289f42009-09-09 15:08:12 +00006717
Steve Naroff081c7422008-09-04 15:10:53 +00006718 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006719 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006720 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006721 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6722 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006723
Steve Naroff081c7422008-09-04 15:10:53 +00006724 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006725 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006726 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006727 << LHSType << RHSType << LHS.get()->getSourceRange()
6728 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006729 }
Richard Trieub80728f2011-09-06 21:43:51 +00006730 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006731 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006732 }
John Wiegley01296292011-04-08 18:41:53 +00006733
Steve Naroffe18f94c2008-09-28 01:11:11 +00006734 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006735 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006736 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6737 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006738 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006739 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006740 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006741 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006742 ->getPointeeType()->isVoidType())))
6743 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006744 << LHSType << RHSType << LHS.get()->getSourceRange()
6745 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006746 }
John McCall7684dde2011-03-11 04:25:25 +00006747 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006748 LHS = ImpCastExprToType(LHS.take(), RHSType,
6749 RHSType->isPointerType() ? CK_BitCast
6750 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006751 else
John McCall9320b872011-09-09 05:25:32 +00006752 RHS = ImpCastExprToType(RHS.take(), LHSType,
6753 LHSType->isPointerType() ? CK_BitCast
6754 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006755 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006756 }
Steve Naroff081c7422008-09-04 15:10:53 +00006757
Richard Trieub80728f2011-09-06 21:43:51 +00006758 if (LHSType->isObjCObjectPointerType() ||
6759 RHSType->isObjCObjectPointerType()) {
6760 const PointerType *LPT = LHSType->getAs<PointerType>();
6761 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006762 if (LPT || RPT) {
6763 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6764 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006765
Steve Naroff753567f2008-11-17 19:49:16 +00006766 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006767 !Context.typesAreCompatible(LHSType, RHSType)) {
6768 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006769 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006770 }
John McCall7684dde2011-03-11 04:25:25 +00006771 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006772 LHS = ImpCastExprToType(LHS.take(), RHSType,
6773 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006774 else
John McCall9320b872011-09-09 05:25:32 +00006775 RHS = ImpCastExprToType(RHS.take(), LHSType,
6776 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006777 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006778 }
Richard Trieub80728f2011-09-06 21:43:51 +00006779 if (LHSType->isObjCObjectPointerType() &&
6780 RHSType->isObjCObjectPointerType()) {
6781 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6782 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006783 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006784 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006785 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006786 else
Richard Trieub80728f2011-09-06 21:43:51 +00006787 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006788 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006789 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006790 }
Richard Trieub80728f2011-09-06 21:43:51 +00006791 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6792 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006793 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006794 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006795 if ((LHSIsNull && LHSType->isIntegerType()) ||
6796 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006797 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006798 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006799 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006800 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006801 else if (getLangOptions().CPlusPlus) {
6802 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6803 isError = true;
6804 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006805 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006806
Chris Lattnerd99bd522009-08-23 00:03:44 +00006807 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006808 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006809 << LHSType << RHSType << LHS.get()->getSourceRange()
6810 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006811 if (isError)
6812 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006813 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006814
Richard Trieub80728f2011-09-06 21:43:51 +00006815 if (LHSType->isIntegerType())
6816 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006817 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006818 else
Richard Trieub80728f2011-09-06 21:43:51 +00006819 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006820 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006821 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006822 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006823
Steve Naroff4b191572008-09-04 16:56:14 +00006824 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006825 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006826 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6827 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006828 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006829 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006830 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006831 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6832 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006833 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006834 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006835
Richard Trieub80728f2011-09-06 21:43:51 +00006836 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006837}
6838
Nate Begeman191a6b12008-07-14 18:02:46 +00006839/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006840/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006841/// like a scalar comparison, a vector comparison produces a vector of integer
6842/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006843QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006844 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006845 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006846 // Check to make sure we're operating on vectors of the same type and width,
6847 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006848 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006849 if (vType.isNull())
6850 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006851
Richard Trieubcce2f72011-09-07 01:19:57 +00006852 QualType LHSType = LHS.get()->getType();
6853 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006854
Anton Yartsev530deb92011-03-27 15:36:07 +00006855 // If AltiVec, the comparison results in a numeric type, i.e.
6856 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006857 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006858 return Context.getLogicalOperationType();
6859
Nate Begeman191a6b12008-07-14 18:02:46 +00006860 // For non-floating point types, check for self-comparisons of the form
6861 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6862 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006863 if (!LHSType->hasFloatingRepresentation()) {
6864 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6865 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006866 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006867 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006868 PDiag(diag::warn_comparison_always)
6869 << 0 // self-
6870 << 2 // "a constant"
6871 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006872 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006873
Nate Begeman191a6b12008-07-14 18:02:46 +00006874 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006875 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006876 assert (RHSType->hasFloatingRepresentation());
6877 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006878 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006879
Nate Begeman191a6b12008-07-14 18:02:46 +00006880 // Return the type for the comparison, which is the same as vector type for
6881 // integer vectors, or an integer type of identical size and number of
6882 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006883 if (LHSType->hasIntegerRepresentation())
6884 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006885
Richard Trieubcce2f72011-09-07 01:19:57 +00006886 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006887 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006888 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006889 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006890 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006891 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6892
Mike Stump4e1f26a2009-02-19 03:04:26 +00006893 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006894 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006895 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6896}
6897
Steve Naroff218bc2b2007-05-04 21:54:46 +00006898inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006899 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006900 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6901
Richard Trieubcce2f72011-09-07 01:19:57 +00006902 if (LHS.get()->getType()->isVectorType() ||
6903 RHS.get()->getType()->isVectorType()) {
6904 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6905 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006906 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006907
Richard Trieubcce2f72011-09-07 01:19:57 +00006908 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006909 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006910
Richard Trieubcce2f72011-09-07 01:19:57 +00006911 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6912 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006913 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006914 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006915 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006916 LHS = LHSResult.take();
6917 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006918
Richard Trieubcce2f72011-09-07 01:19:57 +00006919 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6920 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006921 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006922 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006923}
6924
Steve Naroff218bc2b2007-05-04 21:54:46 +00006925inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006926 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006927
6928 // Diagnose cases where the user write a logical and/or but probably meant a
6929 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6930 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006931 if (LHS.get()->getType()->isIntegerType() &&
6932 !LHS.get()->getType()->isBooleanType() &&
6933 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006934 // Don't warn in macros or template instantiations.
6935 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006936 // If the RHS can be constant folded, and if it constant folds to something
6937 // that isn't 0 or 1 (which indicate a potential logical operation that
6938 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006939 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006940 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006941 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6942 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006943 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6944 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006945 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006946 << (Opc == BO_LAnd ? "&&" : "||");
6947 // Suggest replacing the logical operator with the bitwise version
6948 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6949 << (Opc == BO_LAnd ? "&" : "|")
6950 << FixItHint::CreateReplacement(SourceRange(
6951 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6952 getLangOptions())),
6953 Opc == BO_LAnd ? "&" : "|");
6954 if (Opc == BO_LAnd)
6955 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6956 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6957 << FixItHint::CreateRemoval(
6958 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006959 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006960 0, getSourceManager(),
6961 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006962 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006963 }
Chris Lattner938533d2010-07-24 01:10:11 +00006964 }
Chris Lattner8406c512010-07-13 19:41:32 +00006965
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006966 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006967 LHS = UsualUnaryConversions(LHS.take());
6968 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006969 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006970
Richard Trieubcce2f72011-09-07 01:19:57 +00006971 RHS = UsualUnaryConversions(RHS.take());
6972 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006973 return QualType();
6974
Richard Trieubcce2f72011-09-07 01:19:57 +00006975 if (!LHS.get()->getType()->isScalarType() ||
6976 !RHS.get()->getType()->isScalarType())
6977 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006978
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006979 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006980 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006981
John McCall4a2429a2010-06-04 00:29:51 +00006982 // The following is safe because we only use this method for
6983 // non-overloadable operands.
6984
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006985 // C++ [expr.log.and]p1
6986 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006987 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006988 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6989 if (LHSRes.isInvalid())
6990 return InvalidOperands(Loc, LHS, RHS);
6991 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006992
Richard Trieubcce2f72011-09-07 01:19:57 +00006993 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6994 if (RHSRes.isInvalid())
6995 return InvalidOperands(Loc, LHS, RHS);
6996 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006997
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006998 // C++ [expr.log.and]p2
6999 // C++ [expr.log.or]p2
7000 // The result is a bool.
7001 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007002}
7003
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007004/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7005/// is a read-only property; return true if so. A readonly property expression
7006/// depends on various declarations and thus must be treated specially.
7007///
Mike Stump11289f42009-09-09 15:08:12 +00007008static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007009 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7010 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007011 if (PropExpr->isImplicitProperty()) return false;
7012
7013 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7014 QualType BaseType = PropExpr->isSuperReceiver() ?
7015 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007016 PropExpr->getBase()->getType();
7017
John McCallb7bd14f2010-12-02 01:19:52 +00007018 if (const ObjCObjectPointerType *OPT =
7019 BaseType->getAsObjCInterfacePointerType())
7020 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7021 if (S.isPropertyReadonly(PDecl, IFace))
7022 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007023 }
7024 return false;
7025}
7026
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007027static bool IsConstProperty(Expr *E, Sema &S) {
7028 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7029 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7030 if (PropExpr->isImplicitProperty()) return false;
7031
7032 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7033 QualType T = PDecl->getType();
7034 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007035 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007036 CanQualType CT = S.Context.getCanonicalType(T);
7037 return CT.isConstQualified();
7038 }
7039 return false;
7040}
7041
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007042static bool IsReadonlyMessage(Expr *E, Sema &S) {
7043 if (E->getStmtClass() != Expr::MemberExprClass)
7044 return false;
7045 const MemberExpr *ME = cast<MemberExpr>(E);
7046 NamedDecl *Member = ME->getMemberDecl();
7047 if (isa<FieldDecl>(Member)) {
7048 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7049 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7050 return false;
7051 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7052 }
7053 return false;
7054}
7055
Chris Lattner30bd3272008-11-18 01:22:49 +00007056/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7057/// emit an error and return true. If so, return false.
7058static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007059 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007060 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007061 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007062 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7063 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007064 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7065 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007066 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7067 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007068 if (IsLV == Expr::MLV_Valid)
7069 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007070
Chris Lattner30bd3272008-11-18 01:22:49 +00007071 unsigned Diag = 0;
7072 bool NeedType = false;
7073 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007074 case Expr::MLV_ConstQualified:
7075 Diag = diag::err_typecheck_assign_const;
7076
John McCalld4631322011-06-17 06:42:21 +00007077 // In ARC, use some specialized diagnostics for occasions where we
7078 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007079 if (S.getLangOptions().ObjCAutoRefCount) {
7080 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7081 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7082 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7083
John McCalld4631322011-06-17 06:42:21 +00007084 // Use the normal diagnostic if it's pseudo-__strong but the
7085 // user actually wrote 'const'.
7086 if (var->isARCPseudoStrong() &&
7087 (!var->getTypeSourceInfo() ||
7088 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7089 // There are two pseudo-strong cases:
7090 // - self
John McCall31168b02011-06-15 23:02:42 +00007091 ObjCMethodDecl *method = S.getCurMethodDecl();
7092 if (method && var == method->getSelfDecl())
7093 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007094
7095 // - fast enumeration variables
7096 else
John McCall31168b02011-06-15 23:02:42 +00007097 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007098
John McCall31168b02011-06-15 23:02:42 +00007099 SourceRange Assign;
7100 if (Loc != OrigLoc)
7101 Assign = SourceRange(OrigLoc, OrigLoc);
7102 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7103 // We need to preserve the AST regardless, so migration tool
7104 // can do its job.
7105 return false;
7106 }
7107 }
7108 }
7109
7110 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007111 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007112 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7113 NeedType = true;
7114 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007115 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007116 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7117 NeedType = true;
7118 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007119 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007120 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7121 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007122 case Expr::MLV_Valid:
7123 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007124 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007125 case Expr::MLV_MemberFunction:
7126 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007127 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7128 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007129 case Expr::MLV_IncompleteType:
7130 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007131 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007132 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007133 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007134 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007135 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7136 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007137 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007138 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7139 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007140 case Expr::MLV_ReadonlyProperty:
7141 Diag = diag::error_readonly_property_assignment;
7142 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007143 case Expr::MLV_NoSetterProperty:
7144 Diag = diag::error_nosetter_property_assignment;
7145 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007146 case Expr::MLV_InvalidMessageExpression:
7147 Diag = diag::error_readonly_message_assignment;
7148 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007149 case Expr::MLV_SubObjCPropertySetting:
7150 Diag = diag::error_no_subobject_property_setting;
7151 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007152 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007153
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007154 SourceRange Assign;
7155 if (Loc != OrigLoc)
7156 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007157 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007158 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007159 else
Mike Stump11289f42009-09-09 15:08:12 +00007160 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007161 return true;
7162}
7163
7164
7165
7166// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007167QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007168 SourceLocation Loc,
7169 QualType CompoundType) {
7170 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007171 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007172 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007173
Richard Trieuda4f43a62011-09-07 01:33:52 +00007174 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007175 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7176 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007177 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007178 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007179 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007180 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007181 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7182 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007183 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7184 if (LHSResult.isInvalid())
7185 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007186 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007187 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007188 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007189 if (RHS.isInvalid())
7190 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007191 // Special case of NSObject attributes on c-style pointer types.
7192 if (ConvTy == IncompatiblePointer &&
7193 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007194 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007195 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007196 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007197 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007198
John McCall7decc9e2010-11-18 06:31:45 +00007199 if (ConvTy == Compatible &&
7200 getLangOptions().ObjCNonFragileABI &&
7201 LHSType->isObjCObjectType())
7202 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7203 << LHSType;
7204
Chris Lattnerea714382008-08-21 18:04:13 +00007205 // If the RHS is a unary plus or minus, check to see if they = and + are
7206 // right next to each other. If so, the user may have typo'd "x =+ 4"
7207 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007208 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007209 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7210 RHSCheck = ICE->getSubExpr();
7211 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007212 if ((UO->getOpcode() == UO_Plus ||
7213 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007214 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007215 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007216 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007217 // And there is a space or other character before the subexpr of the
7218 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007219 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007220 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007221 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007222 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007223 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007224 }
Chris Lattnerea714382008-08-21 18:04:13 +00007225 }
John McCall31168b02011-06-15 23:02:42 +00007226
7227 if (ConvTy == Compatible) {
7228 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007229 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007230 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007231 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007232 }
Chris Lattnerea714382008-08-21 18:04:13 +00007233 } else {
7234 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007235 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007236 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007237
Chris Lattner326f7572008-11-18 01:30:42 +00007238 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007239 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007240 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007241
Richard Trieuda4f43a62011-09-07 01:33:52 +00007242 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007243
Steve Naroff98cf3e92007-06-06 18:38:38 +00007244 // C99 6.5.16p3: The type of an assignment expression is the type of the
7245 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007246 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007247 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7248 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007249 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007250 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007251 return (getLangOptions().CPlusPlus
7252 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007253}
7254
Chris Lattner326f7572008-11-18 01:30:42 +00007255// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007256static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007257 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007258 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007259
John McCall3aef3d82011-04-10 19:13:55 +00007260 LHS = S.CheckPlaceholderExpr(LHS.take());
7261 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007262 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007263 return QualType();
7264
John McCall73d36182010-10-12 07:14:40 +00007265 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7266 // operands, but not unary promotions.
7267 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007268
John McCall34376a62010-12-04 03:47:34 +00007269 // So we treat the LHS as a ignored value, and in C++ we allow the
7270 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007271 LHS = S.IgnoredValueConversions(LHS.take());
7272 if (LHS.isInvalid())
7273 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007274
7275 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007276 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7277 if (RHS.isInvalid())
7278 return QualType();
7279 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007280 S.RequireCompleteType(Loc, RHS.get()->getType(),
7281 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007282 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007283
John Wiegley01296292011-04-08 18:41:53 +00007284 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007285}
7286
Steve Naroff7a5af782007-07-13 16:58:59 +00007287/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7288/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007289static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7290 ExprValueKind &VK,
7291 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007292 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007293 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007294 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007295
Chris Lattner6b0cf142008-11-21 07:05:48 +00007296 QualType ResType = Op->getType();
7297 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007298
John McCall4bc41ae2010-11-18 19:01:18 +00007299 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007300 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007301 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007302 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007303 return QualType();
7304 }
7305 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007306 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007307 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007308 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007309 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007310 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007311 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007312 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007313
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007314 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007315 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007316 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007317 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007318 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007319 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007320 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007321 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007322 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007323 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007324 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007325 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007326 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7327 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007328 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007329 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007330 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007331 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007332 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007333 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007334 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007335 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007336 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007337 // In C++, a prefix increment is the same type as the operand. Otherwise
7338 // (in C or with postfix), the increment is the unqualified type of the
7339 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007340 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007341 VK = VK_LValue;
7342 return ResType;
7343 } else {
7344 VK = VK_RValue;
7345 return ResType.getUnqualifiedType();
7346 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007347}
7348
John Wiegley01296292011-04-08 18:41:53 +00007349ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007350 assert(E->getValueKind() == VK_LValue &&
7351 E->getObjectKind() == OK_ObjCProperty);
7352 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7353
Douglas Gregor33823722011-06-11 01:09:30 +00007354 QualType T = E->getType();
7355 QualType ReceiverType;
7356 if (PRE->isObjectReceiver())
7357 ReceiverType = PRE->getBase()->getType();
7358 else if (PRE->isSuperReceiver())
7359 ReceiverType = PRE->getSuperReceiverType();
7360 else
7361 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7362
John McCall34376a62010-12-04 03:47:34 +00007363 ExprValueKind VK = VK_RValue;
7364 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007365 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007366 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007367 T = getMessageSendResultType(ReceiverType, GetterMethod,
7368 PRE->isClassReceiver(),
7369 PRE->isSuperReceiver());
7370 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007371 }
7372 else {
7373 Diag(PRE->getLocation(), diag::err_getter_not_found)
7374 << PRE->getBase()->getType();
7375 }
John McCall34376a62010-12-04 03:47:34 +00007376 }
Douglas Gregor33823722011-06-11 01:09:30 +00007377
7378 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007379 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007380
7381 ExprResult Result = MaybeBindToTemporary(E);
7382 if (!Result.isInvalid())
7383 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007384
7385 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007386}
7387
Richard Trieucfc491d2011-08-02 04:35:43 +00007388void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7389 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007390 assert(LHS.get()->getValueKind() == VK_LValue &&
7391 LHS.get()->getObjectKind() == OK_ObjCProperty);
7392 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007393
John McCall31168b02011-06-15 23:02:42 +00007394 bool Consumed = false;
7395
John Wiegley01296292011-04-08 18:41:53 +00007396 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007397 // If using property-dot syntax notation for assignment, and there is a
7398 // setter, RHS expression is being passed to the setter argument. So,
7399 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007400 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007401 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7402 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007403 Consumed = (getLangOptions().ObjCAutoRefCount &&
7404 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007405
7406 // Otherwise, if the getter returns an l-value, just call that.
7407 } else {
John Wiegley01296292011-04-08 18:41:53 +00007408 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007409 ExprValueKind VK = Expr::getValueKindForType(Result);
7410 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007411 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7412 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007413 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007414 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007415 }
John McCall31168b02011-06-15 23:02:42 +00007416 } else if (getLangOptions().ObjCAutoRefCount) {
7417 const ObjCMethodDecl *setter
7418 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7419 if (setter) {
7420 ObjCMethodDecl::param_iterator P = setter->param_begin();
7421 LHSTy = (*P)->getType();
7422 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7423 }
John McCall34376a62010-12-04 03:47:34 +00007424 }
7425
John McCall31168b02011-06-15 23:02:42 +00007426 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7427 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007428 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007429 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007430 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007431 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007432 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007433 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7434 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7435 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007436 }
7437}
7438
7439
Anders Carlsson806700f2008-02-01 07:15:58 +00007440/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007441/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007442/// where the declaration is needed for type checking. We only need to
7443/// handle cases when the expression references a function designator
7444/// or is an lvalue. Here are some examples:
7445/// - &(x) => x
7446/// - &*****f => f for f a function designator.
7447/// - &s.xx => s
7448/// - &s.zz[1].yy -> s, if zz is an array
7449/// - *(x + 1) -> x, if x is an array
7450/// - &"123"[2] -> 0
7451/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007452static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007453 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007454 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007455 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007456 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007457 // If this is an arrow operator, the address is an offset from
7458 // the base's value, so the object the base refers to is
7459 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007460 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007461 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007462 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007463 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007464 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007465 // FIXME: This code shouldn't be necessary! We should catch the implicit
7466 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007467 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7468 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7469 if (ICE->getSubExpr()->getType()->isArrayType())
7470 return getPrimaryDecl(ICE->getSubExpr());
7471 }
7472 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007473 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007474 case Stmt::UnaryOperatorClass: {
7475 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007476
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007477 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007478 case UO_Real:
7479 case UO_Imag:
7480 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007481 return getPrimaryDecl(UO->getSubExpr());
7482 default:
7483 return 0;
7484 }
7485 }
Steve Naroff47500512007-04-19 23:00:49 +00007486 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007487 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007488 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007489 // If the result of an implicit cast is an l-value, we care about
7490 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007491 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007492 default:
7493 return 0;
7494 }
7495}
7496
Richard Trieu5f376f62011-09-07 21:46:33 +00007497namespace {
7498 enum {
7499 AO_Bit_Field = 0,
7500 AO_Vector_Element = 1,
7501 AO_Property_Expansion = 2,
7502 AO_Register_Variable = 3,
7503 AO_No_Error = 4
7504 };
7505}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007506/// \brief Diagnose invalid operand for address of operations.
7507///
7508/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007509static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7510 Expr *E, unsigned Type) {
7511 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7512}
7513
Steve Naroff47500512007-04-19 23:00:49 +00007514/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007515/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007516/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007517/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007518/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007519/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007520/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007521static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7522 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007523 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007524 return S.Context.DependentTy;
7525 if (OrigOp->getType() == S.Context.OverloadTy)
7526 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007527 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7528 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007529 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7530 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7531 << OrigOp->getSourceRange();
7532 return QualType();
7533 }
John McCall8d08b9b2010-08-27 09:08:28 +00007534
John McCall2979fe02011-04-12 00:42:48 +00007535 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007536
John McCall8d08b9b2010-08-27 09:08:28 +00007537 // Make sure to ignore parentheses in subsequent checks
7538 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007539
John McCall4bc41ae2010-11-18 19:01:18 +00007540 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007541 // Implement C99-only parts of addressof rules.
7542 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007543 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007544 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7545 // (assuming the deref expression is valid).
7546 return uOp->getSubExpr()->getType();
7547 }
7548 // Technically, there should be a check for array subscript
7549 // expressions here, but the result of one is always an lvalue anyway.
7550 }
John McCallf3a88602011-02-03 08:15:49 +00007551 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007552 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007553 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007554
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007555 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007556 bool sfinae = S.isSFINAEContext();
7557 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7558 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007559 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007560 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007561 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007562 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007563 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007564 } else if (lval == Expr::LV_MemberFunction) {
7565 // If it's an instance method, make a member pointer.
7566 // The expression must have exactly the form &A::foo.
7567
7568 // If the underlying expression isn't a decl ref, give up.
7569 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007570 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007571 << OrigOp->getSourceRange();
7572 return QualType();
7573 }
7574 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7575 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7576
7577 // The id-expression was parenthesized.
7578 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007579 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007580 << OrigOp->getSourceRange();
7581
7582 // The method was named without a qualifier.
7583 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007584 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007585 << op->getSourceRange();
7586 }
7587
John McCall4bc41ae2010-11-18 19:01:18 +00007588 return S.Context.getMemberPointerType(op->getType(),
7589 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007590 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007591 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007592 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007593 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007594 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007595 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007596 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007597 return QualType();
7598 }
John McCall086a4642010-11-24 05:12:34 +00007599 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007600 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007601 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007602 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007603 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007604 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007605 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007606 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007607 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007608 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007609 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007610 // with the register storage-class specifier.
7611 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007612 // in C++ it is not error to take address of a register
7613 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007614 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007615 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007616 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007617 }
John McCalld14a8642009-11-21 08:51:07 +00007618 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007619 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007620 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007621 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007622 // Could be a pointer to member, though, if there is an explicit
7623 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007624 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007625 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007626 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007627 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007628 S.Diag(OpLoc,
7629 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007630 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007631 return QualType();
7632 }
Mike Stump11289f42009-09-09 15:08:12 +00007633
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007634 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7635 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007636 return S.Context.getMemberPointerType(op->getType(),
7637 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007638 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007639 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007640 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007641 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007642 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007643
Richard Trieu5f376f62011-09-07 21:46:33 +00007644 if (AddressOfError != AO_No_Error) {
7645 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7646 return QualType();
7647 }
7648
Eli Friedmance7f9002009-05-16 23:27:50 +00007649 if (lval == Expr::LV_IncompleteVoidType) {
7650 // Taking the address of a void variable is technically illegal, but we
7651 // allow it in cases which are otherwise valid.
7652 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007653 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007654 }
7655
Steve Naroff47500512007-04-19 23:00:49 +00007656 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007657 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007658 return S.Context.getObjCObjectPointerType(op->getType());
7659 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007660}
7661
Chris Lattner9156f1b2010-07-05 19:17:26 +00007662/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007663static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7664 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007665 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007666 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007667
John Wiegley01296292011-04-08 18:41:53 +00007668 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7669 if (ConvResult.isInvalid())
7670 return QualType();
7671 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007672 QualType OpTy = Op->getType();
7673 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007674
7675 if (isa<CXXReinterpretCastExpr>(Op)) {
7676 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7677 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7678 Op->getSourceRange());
7679 }
7680
Chris Lattner9156f1b2010-07-05 19:17:26 +00007681 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7682 // is an incomplete type or void. It would be possible to warn about
7683 // dereferencing a void pointer, but it's completely well-defined, and such a
7684 // warning is unlikely to catch any mistakes.
7685 if (const PointerType *PT = OpTy->getAs<PointerType>())
7686 Result = PT->getPointeeType();
7687 else if (const ObjCObjectPointerType *OPT =
7688 OpTy->getAs<ObjCObjectPointerType>())
7689 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007690 else {
John McCall3aef3d82011-04-10 19:13:55 +00007691 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007692 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007693 if (PR.take() != Op)
7694 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007695 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007696
Chris Lattner9156f1b2010-07-05 19:17:26 +00007697 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007698 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007699 << OpTy << Op->getSourceRange();
7700 return QualType();
7701 }
John McCall4bc41ae2010-11-18 19:01:18 +00007702
7703 // Dereferences are usually l-values...
7704 VK = VK_LValue;
7705
7706 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007707 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007708 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007709
7710 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007711}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007712
John McCalle3027922010-08-25 11:45:40 +00007713static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007714 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007715 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007716 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007717 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007718 case tok::periodstar: Opc = BO_PtrMemD; break;
7719 case tok::arrowstar: Opc = BO_PtrMemI; break;
7720 case tok::star: Opc = BO_Mul; break;
7721 case tok::slash: Opc = BO_Div; break;
7722 case tok::percent: Opc = BO_Rem; break;
7723 case tok::plus: Opc = BO_Add; break;
7724 case tok::minus: Opc = BO_Sub; break;
7725 case tok::lessless: Opc = BO_Shl; break;
7726 case tok::greatergreater: Opc = BO_Shr; break;
7727 case tok::lessequal: Opc = BO_LE; break;
7728 case tok::less: Opc = BO_LT; break;
7729 case tok::greaterequal: Opc = BO_GE; break;
7730 case tok::greater: Opc = BO_GT; break;
7731 case tok::exclaimequal: Opc = BO_NE; break;
7732 case tok::equalequal: Opc = BO_EQ; break;
7733 case tok::amp: Opc = BO_And; break;
7734 case tok::caret: Opc = BO_Xor; break;
7735 case tok::pipe: Opc = BO_Or; break;
7736 case tok::ampamp: Opc = BO_LAnd; break;
7737 case tok::pipepipe: Opc = BO_LOr; break;
7738 case tok::equal: Opc = BO_Assign; break;
7739 case tok::starequal: Opc = BO_MulAssign; break;
7740 case tok::slashequal: Opc = BO_DivAssign; break;
7741 case tok::percentequal: Opc = BO_RemAssign; break;
7742 case tok::plusequal: Opc = BO_AddAssign; break;
7743 case tok::minusequal: Opc = BO_SubAssign; break;
7744 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7745 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7746 case tok::ampequal: Opc = BO_AndAssign; break;
7747 case tok::caretequal: Opc = BO_XorAssign; break;
7748 case tok::pipeequal: Opc = BO_OrAssign; break;
7749 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007750 }
7751 return Opc;
7752}
7753
John McCalle3027922010-08-25 11:45:40 +00007754static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007755 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007756 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007757 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007758 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007759 case tok::plusplus: Opc = UO_PreInc; break;
7760 case tok::minusminus: Opc = UO_PreDec; break;
7761 case tok::amp: Opc = UO_AddrOf; break;
7762 case tok::star: Opc = UO_Deref; break;
7763 case tok::plus: Opc = UO_Plus; break;
7764 case tok::minus: Opc = UO_Minus; break;
7765 case tok::tilde: Opc = UO_Not; break;
7766 case tok::exclaim: Opc = UO_LNot; break;
7767 case tok::kw___real: Opc = UO_Real; break;
7768 case tok::kw___imag: Opc = UO_Imag; break;
7769 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007770 }
7771 return Opc;
7772}
7773
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007774/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7775/// This warning is only emitted for builtin assignment operations. It is also
7776/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007777static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007778 SourceLocation OpLoc) {
7779 if (!S.ActiveTemplateInstantiations.empty())
7780 return;
7781 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7782 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007783 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7784 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7785 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7786 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7787 if (!LHSDeclRef || !RHSDeclRef ||
7788 LHSDeclRef->getLocation().isMacroID() ||
7789 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007790 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007791 const ValueDecl *LHSDecl =
7792 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7793 const ValueDecl *RHSDecl =
7794 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7795 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007796 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007797 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007798 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007799 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007800 if (RefTy->getPointeeType().isVolatileQualified())
7801 return;
7802
7803 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007804 << LHSDeclRef->getType()
7805 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007806}
7807
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007808/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7809/// operator @p Opc at location @c TokLoc. This routine only supports
7810/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007811ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007812 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007813 Expr *LHSExpr, Expr *RHSExpr) {
7814 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007815 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007816 // The following two variables are used for compound assignment operators
7817 QualType CompLHSTy; // Type of LHS after promotions for computation
7818 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007819 ExprValueKind VK = VK_RValue;
7820 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007821
Douglas Gregor1beec452011-03-12 01:48:56 +00007822 // Check if a 'foo<int>' involved in a binary op, identifies a single
7823 // function unambiguously (i.e. an lvalue ala 13.4)
7824 // But since an assignment can trigger target based overload, exclude it in
7825 // our blind search. i.e:
7826 // template<class T> void f(); template<class T, class U> void f(U);
7827 // f<int> == 0; // resolve f<int> blindly
7828 // void (*p)(int); p = f<int>; // resolve f<int> using target
7829 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007830 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007831 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007832 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007833
Richard Trieu4a287fb2011-09-07 01:49:20 +00007834 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007835 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007836 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007837 }
7838
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007839 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007840 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007841 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007842 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007843 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7844 VK = LHS.get()->getValueKind();
7845 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007846 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007847 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007848 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007849 break;
John McCalle3027922010-08-25 11:45:40 +00007850 case BO_PtrMemD:
7851 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007852 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007853 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007854 break;
John McCalle3027922010-08-25 11:45:40 +00007855 case BO_Mul:
7856 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007857 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007858 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007859 break;
John McCalle3027922010-08-25 11:45:40 +00007860 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007861 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007862 break;
John McCalle3027922010-08-25 11:45:40 +00007863 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007864 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007865 break;
John McCalle3027922010-08-25 11:45:40 +00007866 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007867 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007868 break;
John McCalle3027922010-08-25 11:45:40 +00007869 case BO_Shl:
7870 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007871 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007872 break;
John McCalle3027922010-08-25 11:45:40 +00007873 case BO_LE:
7874 case BO_LT:
7875 case BO_GE:
7876 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007877 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007878 break;
John McCalle3027922010-08-25 11:45:40 +00007879 case BO_EQ:
7880 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007881 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007882 break;
John McCalle3027922010-08-25 11:45:40 +00007883 case BO_And:
7884 case BO_Xor:
7885 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007886 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007887 break;
John McCalle3027922010-08-25 11:45:40 +00007888 case BO_LAnd:
7889 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007891 break;
John McCalle3027922010-08-25 11:45:40 +00007892 case BO_MulAssign:
7893 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007894 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007895 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007896 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007897 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7898 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007899 break;
John McCalle3027922010-08-25 11:45:40 +00007900 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007901 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007902 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007903 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7904 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007905 break;
John McCalle3027922010-08-25 11:45:40 +00007906 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007907 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7908 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7909 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007910 break;
John McCalle3027922010-08-25 11:45:40 +00007911 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7913 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7914 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007915 break;
John McCalle3027922010-08-25 11:45:40 +00007916 case BO_ShlAssign:
7917 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007918 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007919 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007920 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7921 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007922 break;
John McCalle3027922010-08-25 11:45:40 +00007923 case BO_AndAssign:
7924 case BO_XorAssign:
7925 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007926 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007927 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007928 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7929 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007930 break;
John McCalle3027922010-08-25 11:45:40 +00007931 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7933 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7934 VK = RHS.get()->getValueKind();
7935 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007936 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007937 break;
7938 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007939 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007940 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007941
7942 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007943 CheckArrayAccess(LHS.get());
7944 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007945
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007946 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007947 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007948 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007949 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007950 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007951 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007952 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007953 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007954 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007955 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007956 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007957}
7958
Sebastian Redl44615072009-10-27 12:10:02 +00007959/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7960/// operators are mixed in a way that suggests that the programmer forgot that
7961/// comparison operators have higher precedence. The most typical example of
7962/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007963static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007964 SourceLocation OpLoc, Expr *LHSExpr,
7965 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007966 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007967 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7968 RHSopc = static_cast<BinOp::Opcode>(-1);
7969 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7970 LHSopc = BO->getOpcode();
7971 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7972 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007973
7974 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007975 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007976 return;
7977
7978 // Bitwise operations are sometimes used as eager logical ops.
7979 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007980 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7981 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007982 return;
7983
Richard Trieu4a287fb2011-09-07 01:49:20 +00007984 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7985 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007986 if (!isLeftComp && !isRightComp) return;
7987
Richard Trieu4a287fb2011-09-07 01:49:20 +00007988 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7989 OpLoc)
7990 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7991 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7992 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007993 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007994 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7995 RHSExpr->getLocEnd())
7996 : SourceRange(LHSExpr->getLocStart(),
7997 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007998
7999 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8000 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8001 SuggestParentheses(Self, OpLoc,
8002 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008003 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008004 SuggestParentheses(Self, OpLoc,
8005 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8006 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008007}
8008
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008009/// \brief It accepts a '&' expr that is inside a '|' one.
8010/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8011/// in parentheses.
8012static void
8013EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8014 BinaryOperator *Bop) {
8015 assert(Bop->getOpcode() == BO_And);
8016 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8017 << Bop->getSourceRange() << OpLoc;
8018 SuggestParentheses(Self, Bop->getOperatorLoc(),
8019 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8020 Bop->getSourceRange());
8021}
8022
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008023/// \brief It accepts a '&&' expr that is inside a '||' one.
8024/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8025/// in parentheses.
8026static void
8027EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008028 BinaryOperator *Bop) {
8029 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008030 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8031 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008032 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008033 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008034 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008035}
8036
8037/// \brief Returns true if the given expression can be evaluated as a constant
8038/// 'true'.
8039static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8040 bool Res;
8041 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8042}
8043
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008044/// \brief Returns true if the given expression can be evaluated as a constant
8045/// 'false'.
8046static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8047 bool Res;
8048 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8049}
8050
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008051/// \brief Look for '&&' in the left hand of a '||' expr.
8052static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008053 Expr *LHSExpr, Expr *RHSExpr) {
8054 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008055 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008056 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008057 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008058 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008059 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8060 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8061 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8062 } else if (Bop->getOpcode() == BO_LOr) {
8063 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8064 // If it's "a || b && 1 || c" we didn't warn earlier for
8065 // "a || b && 1", but warn now.
8066 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8067 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8068 }
8069 }
8070 }
8071}
8072
8073/// \brief Look for '&&' in the right hand of a '||' expr.
8074static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008075 Expr *LHSExpr, Expr *RHSExpr) {
8076 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008077 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008078 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008079 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008080 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008081 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8082 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8083 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008084 }
8085 }
8086}
8087
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008088/// \brief Look for '&' in the left or right hand of a '|' expr.
8089static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8090 Expr *OrArg) {
8091 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8092 if (Bop->getOpcode() == BO_And)
8093 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8094 }
8095}
8096
Sebastian Redl43028242009-10-26 15:24:15 +00008097/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008098/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008099static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008100 SourceLocation OpLoc, Expr *LHSExpr,
8101 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008102 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008103 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008104 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008105
8106 // Diagnose "arg1 & arg2 | arg3"
8107 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008108 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8109 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008110 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008111
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008112 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8113 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008114 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008115 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8116 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008117 }
Sebastian Redl43028242009-10-26 15:24:15 +00008118}
8119
Steve Naroff218bc2b2007-05-04 21:54:46 +00008120// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008121ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008122 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008123 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008124 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008125 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8126 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008127
Sebastian Redl43028242009-10-26 15:24:15 +00008128 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008129 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008130
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008131 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008132}
8133
John McCalldadc5752010-08-24 06:29:42 +00008134ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008135 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008136 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008137 if (getLangOptions().CPlusPlus) {
8138 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008139
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008140 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008141 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008142 } else if (Opc == BO_Assign &&
8143 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008144 UseBuiltinOperator = true;
8145 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008146 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8147 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008148 }
8149
8150 if (!UseBuiltinOperator) {
8151 // Find all of the overloaded operators visible from this
8152 // point. We perform both an operator-name lookup from the local
8153 // scope and an argument-dependent lookup based on the types of
8154 // the arguments.
8155 UnresolvedSet<16> Functions;
8156 OverloadedOperatorKind OverOp
8157 = BinaryOperator::getOverloadedOperator(Opc);
8158 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008159 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8160 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008161
8162 // Build the (potentially-overloaded, potentially-dependent)
8163 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008164 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008165 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008166 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008167
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008168 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008169 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008170}
8171
John McCalldadc5752010-08-24 06:29:42 +00008172ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008173 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008174 Expr *InputExpr) {
8175 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008176 ExprValueKind VK = VK_RValue;
8177 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008178 QualType resultType;
8179 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008180 case UO_PreInc:
8181 case UO_PreDec:
8182 case UO_PostInc:
8183 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008184 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008185 Opc == UO_PreInc ||
8186 Opc == UO_PostInc,
8187 Opc == UO_PreInc ||
8188 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008189 break;
John McCalle3027922010-08-25 11:45:40 +00008190 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008191 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008192 break;
John McCall31996342011-04-07 08:22:57 +00008193 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008194 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008195 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008196 Input = move(resolved);
8197 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8198 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008199 break;
John McCall31996342011-04-07 08:22:57 +00008200 }
John McCalle3027922010-08-25 11:45:40 +00008201 case UO_Plus:
8202 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008203 Input = UsualUnaryConversions(Input.take());
8204 if (Input.isInvalid()) return ExprError();
8205 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008206 if (resultType->isDependentType())
8207 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008208 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8209 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008210 break;
8211 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8212 resultType->isEnumeralType())
8213 break;
8214 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008215 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008216 resultType->isPointerType())
8217 break;
John McCall36226622010-10-12 02:09:17 +00008218 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008219 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008220 if (Input.isInvalid()) return ExprError();
8221 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008222 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008223
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008224 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008225 << resultType << Input.get()->getSourceRange());
8226
John McCalle3027922010-08-25 11:45:40 +00008227 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008228 Input = UsualUnaryConversions(Input.take());
8229 if (Input.isInvalid()) return ExprError();
8230 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008231 if (resultType->isDependentType())
8232 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008233 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8234 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8235 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008236 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008237 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008238 else if (resultType->hasIntegerRepresentation())
8239 break;
8240 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008241 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008242 if (Input.isInvalid()) return ExprError();
8243 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008244 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008245 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008246 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008247 }
Steve Naroff35d85152007-05-07 00:24:15 +00008248 break;
John Wiegley01296292011-04-08 18:41:53 +00008249
John McCalle3027922010-08-25 11:45:40 +00008250 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008251 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008252 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8253 if (Input.isInvalid()) return ExprError();
8254 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008255 if (resultType->isDependentType())
8256 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008257 if (resultType->isScalarType()) {
8258 // C99 6.5.3.3p1: ok, fallthrough;
8259 if (Context.getLangOptions().CPlusPlus) {
8260 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8261 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008262 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8263 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008264 }
John McCall36226622010-10-12 02:09:17 +00008265 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008266 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008267 if (Input.isInvalid()) return ExprError();
8268 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008269 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008270 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008271 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008272 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008273
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008274 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008275 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008276 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008277 break;
John McCalle3027922010-08-25 11:45:40 +00008278 case UO_Real:
8279 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008280 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008281 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008282 if (Input.isInvalid()) return ExprError();
8283 if (Input.get()->getValueKind() != VK_RValue &&
8284 Input.get()->getObjectKind() == OK_Ordinary)
8285 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008286 break;
John McCalle3027922010-08-25 11:45:40 +00008287 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008288 resultType = Input.get()->getType();
8289 VK = Input.get()->getValueKind();
8290 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008291 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008292 }
John Wiegley01296292011-04-08 18:41:53 +00008293 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008294 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008295
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008296 // Check for array bounds violations in the operand of the UnaryOperator,
8297 // except for the '*' and '&' operators that have to be handled specially
8298 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8299 // that are explicitly defined as valid by the standard).
8300 if (Opc != UO_AddrOf && Opc != UO_Deref)
8301 CheckArrayAccess(Input.get());
8302
John Wiegley01296292011-04-08 18:41:53 +00008303 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008304 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008305}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008306
John McCalldadc5752010-08-24 06:29:42 +00008307ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008308 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008309 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008310 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008311 // Find all of the overloaded operators visible from this
8312 // point. We perform both an operator-name lookup from the local
8313 // scope and an argument-dependent lookup based on the types of
8314 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008315 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008316 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008317 if (S && OverOp != OO_None)
8318 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8319 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008320
John McCallb268a282010-08-23 23:25:46 +00008321 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008322 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008323
John McCallb268a282010-08-23 23:25:46 +00008324 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008325}
8326
Douglas Gregor5287f092009-11-05 00:51:44 +00008327// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008328ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008329 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008330 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008331}
8332
Steve Naroff66356bd2007-09-16 14:56:35 +00008333/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008334ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008335 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008336 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008337 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008338 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008339 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008340}
8341
John McCall31168b02011-06-15 23:02:42 +00008342/// Given the last statement in a statement-expression, check whether
8343/// the result is a producing expression (like a call to an
8344/// ns_returns_retained function) and, if so, rebuild it to hoist the
8345/// release out of the full-expression. Otherwise, return null.
8346/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008347static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008348 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008349 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008350 if (!cleanups) return 0;
8351
8352 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008353 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008354 return 0;
8355
8356 // Splice out the cast. This shouldn't modify any interesting
8357 // features of the statement.
8358 Expr *producer = cast->getSubExpr();
8359 assert(producer->getType() == cast->getType());
8360 assert(producer->getValueKind() == cast->getValueKind());
8361 cleanups->setSubExpr(producer);
8362 return cleanups;
8363}
8364
John McCalldadc5752010-08-24 06:29:42 +00008365ExprResult
John McCallb268a282010-08-23 23:25:46 +00008366Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008367 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008368 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8369 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8370
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008371 bool isFileScope
8372 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008373 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008374 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008375
Chris Lattner366727f2007-07-24 16:58:17 +00008376 // FIXME: there are a variety of strange constraints to enforce here, for
8377 // example, it is not possible to goto into a stmt expression apparently.
8378 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008379
Chris Lattner366727f2007-07-24 16:58:17 +00008380 // If there are sub stmts in the compound stmt, take the type of the last one
8381 // as the type of the stmtexpr.
8382 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008383 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008384 if (!Compound->body_empty()) {
8385 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008386 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008387 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008388 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8389 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008390 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008391 }
John McCall31168b02011-06-15 23:02:42 +00008392
John Wiegley01296292011-04-08 18:41:53 +00008393 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008394 // Do function/array conversion on the last expression, but not
8395 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008396 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8397 if (LastExpr.isInvalid())
8398 return ExprError();
8399 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008400
John Wiegley01296292011-04-08 18:41:53 +00008401 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008402 // In ARC, if the final expression ends in a consume, splice
8403 // the consume out and bind it later. In the alternate case
8404 // (when dealing with a retainable type), the result
8405 // initialization will create a produce. In both cases the
8406 // result will be +1, and we'll need to balance that out with
8407 // a bind.
8408 if (Expr *rebuiltLastStmt
8409 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8410 LastExpr = rebuiltLastStmt;
8411 } else {
8412 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008413 InitializedEntity::InitializeResult(LPLoc,
8414 Ty,
8415 false),
8416 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008417 LastExpr);
8418 }
8419
John Wiegley01296292011-04-08 18:41:53 +00008420 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008421 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008422 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008423 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008424 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008425 else
John Wiegley01296292011-04-08 18:41:53 +00008426 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008427 StmtExprMayBindToTemp = true;
8428 }
8429 }
8430 }
Chris Lattner944d3062008-07-26 19:51:01 +00008431 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008432
Eli Friedmanba961a92009-03-23 00:24:07 +00008433 // FIXME: Check that expression type is complete/non-abstract; statement
8434 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008435 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8436 if (StmtExprMayBindToTemp)
8437 return MaybeBindToTemporary(ResStmtExpr);
8438 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008439}
Steve Naroff78864672007-08-01 22:05:33 +00008440
John McCalldadc5752010-08-24 06:29:42 +00008441ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008442 TypeSourceInfo *TInfo,
8443 OffsetOfComponent *CompPtr,
8444 unsigned NumComponents,
8445 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008446 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008447 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008448 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008449
Chris Lattnerf17bd422007-08-30 17:45:32 +00008450 // We must have at least one component that refers to the type, and the first
8451 // one is known to be a field designator. Verify that the ArgTy represents
8452 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008453 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008454 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8455 << ArgTy << TypeRange);
8456
8457 // Type must be complete per C99 7.17p3 because a declaring a variable
8458 // with an incomplete type would be ill-formed.
8459 if (!Dependent
8460 && RequireCompleteType(BuiltinLoc, ArgTy,
8461 PDiag(diag::err_offsetof_incomplete_type)
8462 << TypeRange))
8463 return ExprError();
8464
Chris Lattner78502cf2007-08-31 21:49:13 +00008465 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8466 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008467 // FIXME: This diagnostic isn't actually visible because the location is in
8468 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008469 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008470 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8471 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008472
8473 bool DidWarnAboutNonPOD = false;
8474 QualType CurrentType = ArgTy;
8475 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008476 SmallVector<OffsetOfNode, 4> Comps;
8477 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008478 for (unsigned i = 0; i != NumComponents; ++i) {
8479 const OffsetOfComponent &OC = CompPtr[i];
8480 if (OC.isBrackets) {
8481 // Offset of an array sub-field. TODO: Should we allow vector elements?
8482 if (!CurrentType->isDependentType()) {
8483 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8484 if(!AT)
8485 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8486 << CurrentType);
8487 CurrentType = AT->getElementType();
8488 } else
8489 CurrentType = Context.DependentTy;
8490
8491 // The expression must be an integral expression.
8492 // FIXME: An integral constant expression?
8493 Expr *Idx = static_cast<Expr*>(OC.U.E);
8494 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8495 !Idx->getType()->isIntegerType())
8496 return ExprError(Diag(Idx->getLocStart(),
8497 diag::err_typecheck_subscript_not_integer)
8498 << Idx->getSourceRange());
8499
8500 // Record this array index.
8501 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8502 Exprs.push_back(Idx);
8503 continue;
8504 }
8505
8506 // Offset of a field.
8507 if (CurrentType->isDependentType()) {
8508 // We have the offset of a field, but we can't look into the dependent
8509 // type. Just record the identifier of the field.
8510 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8511 CurrentType = Context.DependentTy;
8512 continue;
8513 }
8514
8515 // We need to have a complete type to look into.
8516 if (RequireCompleteType(OC.LocStart, CurrentType,
8517 diag::err_offsetof_incomplete_type))
8518 return ExprError();
8519
8520 // Look for the designated field.
8521 const RecordType *RC = CurrentType->getAs<RecordType>();
8522 if (!RC)
8523 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8524 << CurrentType);
8525 RecordDecl *RD = RC->getDecl();
8526
8527 // C++ [lib.support.types]p5:
8528 // The macro offsetof accepts a restricted set of type arguments in this
8529 // International Standard. type shall be a POD structure or a POD union
8530 // (clause 9).
8531 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8532 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008533 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008534 PDiag(diag::warn_offsetof_non_pod_type)
8535 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8536 << CurrentType))
8537 DidWarnAboutNonPOD = true;
8538 }
8539
8540 // Look for the field.
8541 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8542 LookupQualifiedName(R, RD);
8543 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008544 IndirectFieldDecl *IndirectMemberDecl = 0;
8545 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008546 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008547 MemberDecl = IndirectMemberDecl->getAnonField();
8548 }
8549
Douglas Gregor882211c2010-04-28 22:16:22 +00008550 if (!MemberDecl)
8551 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8552 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8553 OC.LocEnd));
8554
Douglas Gregor10982ea2010-04-28 22:36:06 +00008555 // C99 7.17p3:
8556 // (If the specified member is a bit-field, the behavior is undefined.)
8557 //
8558 // We diagnose this as an error.
8559 if (MemberDecl->getBitWidth()) {
8560 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8561 << MemberDecl->getDeclName()
8562 << SourceRange(BuiltinLoc, RParenLoc);
8563 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8564 return ExprError();
8565 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008566
8567 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008568 if (IndirectMemberDecl)
8569 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008570
Douglas Gregord1702062010-04-29 00:18:15 +00008571 // If the member was found in a base class, introduce OffsetOfNodes for
8572 // the base class indirections.
8573 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8574 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008575 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008576 CXXBasePath &Path = Paths.front();
8577 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8578 B != BEnd; ++B)
8579 Comps.push_back(OffsetOfNode(B->Base));
8580 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008581
Francois Pichet783dd6e2010-11-21 06:08:52 +00008582 if (IndirectMemberDecl) {
8583 for (IndirectFieldDecl::chain_iterator FI =
8584 IndirectMemberDecl->chain_begin(),
8585 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8586 assert(isa<FieldDecl>(*FI));
8587 Comps.push_back(OffsetOfNode(OC.LocStart,
8588 cast<FieldDecl>(*FI), OC.LocEnd));
8589 }
8590 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008591 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008592
Douglas Gregor882211c2010-04-28 22:16:22 +00008593 CurrentType = MemberDecl->getType().getNonReferenceType();
8594 }
8595
8596 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8597 TInfo, Comps.data(), Comps.size(),
8598 Exprs.data(), Exprs.size(), RParenLoc));
8599}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008600
John McCalldadc5752010-08-24 06:29:42 +00008601ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008602 SourceLocation BuiltinLoc,
8603 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008604 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008605 OffsetOfComponent *CompPtr,
8606 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008607 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008608
Douglas Gregor882211c2010-04-28 22:16:22 +00008609 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008610 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008611 if (ArgTy.isNull())
8612 return ExprError();
8613
Eli Friedman06dcfd92010-08-05 10:15:45 +00008614 if (!ArgTInfo)
8615 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8616
8617 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008618 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008619}
8620
8621
John McCalldadc5752010-08-24 06:29:42 +00008622ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008623 Expr *CondExpr,
8624 Expr *LHSExpr, Expr *RHSExpr,
8625 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008626 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8627
John McCall7decc9e2010-11-18 06:31:45 +00008628 ExprValueKind VK = VK_RValue;
8629 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008630 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008631 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008632 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008633 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008634 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008635 } else {
8636 // The conditional expression is required to be a constant expression.
8637 llvm::APSInt condEval(32);
8638 SourceLocation ExpLoc;
8639 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008640 return ExprError(Diag(ExpLoc,
8641 diag::err_typecheck_choose_expr_requires_constant)
8642 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008643
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008644 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008645 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8646
8647 resType = ActiveExpr->getType();
8648 ValueDependent = ActiveExpr->isValueDependent();
8649 VK = ActiveExpr->getValueKind();
8650 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008651 }
8652
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008653 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008654 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008655 resType->isDependentType(),
8656 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008657}
8658
Steve Naroffc540d662008-09-03 18:15:37 +00008659//===----------------------------------------------------------------------===//
8660// Clang Extensions.
8661//===----------------------------------------------------------------------===//
8662
8663/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008664void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008665 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008666 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008667 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008668 if (CurScope)
8669 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008670 else
8671 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008672}
8673
Mike Stump82f071f2009-02-04 22:31:32 +00008674void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008675 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008676 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008677 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008678
John McCall8cb7bdf2010-06-04 23:28:52 +00008679 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008680 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008681
John McCall3882ace2011-01-05 12:14:39 +00008682 // GetTypeForDeclarator always produces a function type for a block
8683 // literal signature. Furthermore, it is always a FunctionProtoType
8684 // unless the function was written with a typedef.
8685 assert(T->isFunctionType() &&
8686 "GetTypeForDeclarator made a non-function block signature");
8687
8688 // Look for an explicit signature in that function type.
8689 FunctionProtoTypeLoc ExplicitSignature;
8690
8691 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8692 if (isa<FunctionProtoTypeLoc>(tmp)) {
8693 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8694
8695 // Check whether that explicit signature was synthesized by
8696 // GetTypeForDeclarator. If so, don't save that as part of the
8697 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008698 if (ExplicitSignature.getLocalRangeBegin() ==
8699 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008700 // This would be much cheaper if we stored TypeLocs instead of
8701 // TypeSourceInfos.
8702 TypeLoc Result = ExplicitSignature.getResultLoc();
8703 unsigned Size = Result.getFullDataSize();
8704 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8705 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8706
8707 ExplicitSignature = FunctionProtoTypeLoc();
8708 }
John McCalla3ccba02010-06-04 11:21:44 +00008709 }
Mike Stump11289f42009-09-09 15:08:12 +00008710
John McCall3882ace2011-01-05 12:14:39 +00008711 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8712 CurBlock->FunctionType = T;
8713
8714 const FunctionType *Fn = T->getAs<FunctionType>();
8715 QualType RetTy = Fn->getResultType();
8716 bool isVariadic =
8717 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8718
John McCall8e346702010-06-04 19:02:56 +00008719 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008720
John McCalla3ccba02010-06-04 11:21:44 +00008721 // Don't allow returning a objc interface by value.
8722 if (RetTy->isObjCObjectType()) {
8723 Diag(ParamInfo.getSourceRange().getBegin(),
8724 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8725 return;
8726 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008727
John McCalla3ccba02010-06-04 11:21:44 +00008728 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008729 // return type. TODO: what should we do with declarators like:
8730 // ^ * { ... }
8731 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008732 if (RetTy != Context.DependentTy)
8733 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008734
John McCalla3ccba02010-06-04 11:21:44 +00008735 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008736 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008737 if (ExplicitSignature) {
8738 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8739 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008740 if (Param->getIdentifier() == 0 &&
8741 !Param->isImplicit() &&
8742 !Param->isInvalidDecl() &&
8743 !getLangOptions().CPlusPlus)
8744 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008745 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008746 }
John McCalla3ccba02010-06-04 11:21:44 +00008747
8748 // Fake up parameter variables if we have a typedef, like
8749 // ^ fntype { ... }
8750 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8751 for (FunctionProtoType::arg_type_iterator
8752 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8753 ParmVarDecl *Param =
8754 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8755 ParamInfo.getSourceRange().getBegin(),
8756 *I);
John McCall8e346702010-06-04 19:02:56 +00008757 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008758 }
Steve Naroffc540d662008-09-03 18:15:37 +00008759 }
John McCalla3ccba02010-06-04 11:21:44 +00008760
John McCall8e346702010-06-04 19:02:56 +00008761 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008762 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008763 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008764 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8765 CurBlock->TheDecl->param_end(),
8766 /*CheckParameterNames=*/false);
8767 }
8768
John McCalla3ccba02010-06-04 11:21:44 +00008769 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008770 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008771
John McCall8e346702010-06-04 19:02:56 +00008772 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008773 Diag(ParamInfo.getAttributes()->getLoc(),
8774 diag::warn_attribute_sentinel_not_variadic) << 1;
8775 // FIXME: remove the attribute.
8776 }
8777
8778 // Put the parameter variables in scope. We can bail out immediately
8779 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008780 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008781 return;
8782
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008783 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008784 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8785 (*AI)->setOwningFunction(CurBlock->TheDecl);
8786
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008787 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008788 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008789 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008790
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008791 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008792 }
John McCallf7b2fb52010-01-22 00:28:27 +00008793 }
Steve Naroffc540d662008-09-03 18:15:37 +00008794}
8795
8796/// ActOnBlockError - If there is an error parsing a block, this callback
8797/// is invoked to pop the information about the block from the action impl.
8798void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008799 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008800 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008801 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008802}
8803
8804/// ActOnBlockStmtExpr - This is called when the body of a block statement
8805/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008806ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008807 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008808 // If blocks are disabled, emit an error.
8809 if (!LangOpts.Blocks)
8810 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008811
Douglas Gregor9a28e842010-03-01 23:15:13 +00008812 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008813
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008814 PopDeclContext();
8815
Steve Naroffc540d662008-09-03 18:15:37 +00008816 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008817 if (!BSI->ReturnType.isNull())
8818 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008819
Mike Stump3bf1ab42009-07-28 22:04:01 +00008820 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008821 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008822
John McCallc63de662011-02-02 13:00:07 +00008823 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008824 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8825 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008826
John McCall8e346702010-06-04 19:02:56 +00008827 // If the user wrote a function type in some form, try to use that.
8828 if (!BSI->FunctionType.isNull()) {
8829 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8830
8831 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8832 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8833
8834 // Turn protoless block types into nullary block types.
8835 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008836 FunctionProtoType::ExtProtoInfo EPI;
8837 EPI.ExtInfo = Ext;
8838 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008839
8840 // Otherwise, if we don't need to change anything about the function type,
8841 // preserve its sugar structure.
8842 } else if (FTy->getResultType() == RetTy &&
8843 (!NoReturn || FTy->getNoReturnAttr())) {
8844 BlockTy = BSI->FunctionType;
8845
8846 // Otherwise, make the minimal modifications to the function type.
8847 } else {
8848 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008849 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8850 EPI.TypeQuals = 0; // FIXME: silently?
8851 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008852 BlockTy = Context.getFunctionType(RetTy,
8853 FPT->arg_type_begin(),
8854 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008855 EPI);
John McCall8e346702010-06-04 19:02:56 +00008856 }
8857
8858 // If we don't have a function type, just build one from nothing.
8859 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008860 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008861 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008862 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008863 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008864
John McCall8e346702010-06-04 19:02:56 +00008865 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8866 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008867 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008868
Chris Lattner45542ea2009-04-19 05:28:12 +00008869 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008870 if (getCurFunction()->NeedsScopeChecking() &&
8871 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008872 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008873
Chris Lattner60f84492011-02-17 23:58:47 +00008874 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008875
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008876 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8877 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8878 const VarDecl *variable = ci->getVariable();
8879 QualType T = variable->getType();
8880 QualType::DestructionKind destructKind = T.isDestructedType();
8881 if (destructKind != QualType::DK_none)
8882 getCurFunction()->setHasBranchProtectedScope();
8883 }
8884
Douglas Gregor49695f02011-09-06 20:46:03 +00008885 computeNRVO(Body, getCurBlock());
8886
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008887 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8888 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8889 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8890
Douglas Gregor9a28e842010-03-01 23:15:13 +00008891 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008892}
8893
John McCalldadc5752010-08-24 06:29:42 +00008894ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008895 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008896 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008897 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008898 GetTypeFromParser(Ty, &TInfo);
8899 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008900}
8901
John McCalldadc5752010-08-24 06:29:42 +00008902ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008903 Expr *E, TypeSourceInfo *TInfo,
8904 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008905 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008906
Eli Friedman121ba0c2008-08-09 23:32:40 +00008907 // Get the va_list type
8908 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008909 if (VaListType->isArrayType()) {
8910 // Deal with implicit array decay; for example, on x86-64,
8911 // va_list is an array, but it's supposed to decay to
8912 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008913 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008914 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008915 ExprResult Result = UsualUnaryConversions(E);
8916 if (Result.isInvalid())
8917 return ExprError();
8918 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008919 } else {
8920 // Otherwise, the va_list argument must be an l-value because
8921 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008922 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008923 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008924 return ExprError();
8925 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008926
Douglas Gregorad3150c2009-05-19 23:10:31 +00008927 if (!E->isTypeDependent() &&
8928 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008929 return ExprError(Diag(E->getLocStart(),
8930 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008931 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008932 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008933
David Majnemerc75d1a12011-06-14 05:17:32 +00008934 if (!TInfo->getType()->isDependentType()) {
8935 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8936 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8937 << TInfo->getTypeLoc().getSourceRange()))
8938 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008939
David Majnemerc75d1a12011-06-14 05:17:32 +00008940 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8941 TInfo->getType(),
8942 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8943 << TInfo->getTypeLoc().getSourceRange()))
8944 return ExprError();
8945
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008946 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008947 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008948 TInfo->getType()->isObjCLifetimeType()
8949 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8950 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008951 << TInfo->getType()
8952 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008953 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008954
8955 // Check for va_arg where arguments of the given type will be promoted
8956 // (i.e. this va_arg is guaranteed to have undefined behavior).
8957 QualType PromoteType;
8958 if (TInfo->getType()->isPromotableIntegerType()) {
8959 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8960 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8961 PromoteType = QualType();
8962 }
8963 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8964 PromoteType = Context.DoubleTy;
8965 if (!PromoteType.isNull())
8966 Diag(TInfo->getTypeLoc().getBeginLoc(),
8967 diag::warn_second_parameter_to_va_arg_never_compatible)
8968 << TInfo->getType()
8969 << PromoteType
8970 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008971 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008972
Abramo Bagnara27db2392010-08-10 10:06:15 +00008973 QualType T = TInfo->getType().getNonLValueExprType(Context);
8974 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008975}
8976
John McCalldadc5752010-08-24 06:29:42 +00008977ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008978 // The type of __null will be int or long, depending on the size of
8979 // pointers on the target.
8980 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008981 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8982 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008983 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008984 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008985 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008986 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008987 Ty = Context.LongLongTy;
8988 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008989 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008990 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008991
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008992 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008993}
8994
Alexis Huntc46382e2010-04-28 23:02:27 +00008995static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008996 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008997 if (!SemaRef.getLangOptions().ObjC1)
8998 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008999
Anders Carlssonace5d072009-11-10 04:46:30 +00009000 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9001 if (!PT)
9002 return;
9003
9004 // Check if the destination is of type 'id'.
9005 if (!PT->isObjCIdType()) {
9006 // Check if the destination is the 'NSString' interface.
9007 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9008 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9009 return;
9010 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009011
Anders Carlssonace5d072009-11-10 04:46:30 +00009012 // Strip off any parens and casts.
9013 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00009014 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009015 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009016
Douglas Gregora771f462010-03-31 17:46:05 +00009017 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009018}
9019
Chris Lattner9bad62c2008-01-04 18:04:52 +00009020bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9021 SourceLocation Loc,
9022 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009023 Expr *SrcExpr, AssignmentAction Action,
9024 bool *Complained) {
9025 if (Complained)
9026 *Complained = false;
9027
Chris Lattner9bad62c2008-01-04 18:04:52 +00009028 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009029 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009030 bool isInvalid = false;
9031 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009032 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009033 ConversionFixItGenerator ConvHints;
9034 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009035
Chris Lattner9bad62c2008-01-04 18:04:52 +00009036 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00009037 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009038 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009039 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009040 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009041 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9042 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009043 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009044 case IntToPointer:
9045 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009046 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9047 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009048 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009049 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009050 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009051 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009052 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9053 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009054 if (Hint.isNull() && !CheckInferredResultType) {
9055 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9056 }
9057 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009058 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009059 case IncompatiblePointerSign:
9060 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9061 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009062 case FunctionVoidPointer:
9063 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9064 break;
John McCall4fff8f62011-02-01 00:10:29 +00009065 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009066 // Perform array-to-pointer decay if necessary.
9067 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9068
John McCall4fff8f62011-02-01 00:10:29 +00009069 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9070 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9071 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9072 DiagKind = diag::err_typecheck_incompatible_address_space;
9073 break;
John McCall31168b02011-06-15 23:02:42 +00009074
9075
9076 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009077 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009078 break;
John McCall4fff8f62011-02-01 00:10:29 +00009079 }
9080
9081 llvm_unreachable("unknown error case for discarding qualifiers!");
9082 // fallthrough
9083 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009084 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009085 // If the qualifiers lost were because we were applying the
9086 // (deprecated) C++ conversion from a string literal to a char*
9087 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9088 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009089 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009090 // bit of refactoring (so that the second argument is an
9091 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009092 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009093 // C++ semantics.
9094 if (getLangOptions().CPlusPlus &&
9095 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9096 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009097 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9098 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009099 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009100 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009101 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009102 case IntToBlockPointer:
9103 DiagKind = diag::err_int_to_block_pointer;
9104 break;
9105 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009106 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009107 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009108 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009109 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009110 // it can give a more specific diagnostic.
9111 DiagKind = diag::warn_incompatible_qualified_id;
9112 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009113 case IncompatibleVectors:
9114 DiagKind = diag::warn_incompatible_vectors;
9115 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009116 case IncompatibleObjCWeakRef:
9117 DiagKind = diag::err_arc_weak_unavailable_assign;
9118 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009119 case Incompatible:
9120 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009121 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9122 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009123 isInvalid = true;
9124 break;
9125 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009126
Douglas Gregorc68e1402010-04-09 00:35:39 +00009127 QualType FirstType, SecondType;
9128 switch (Action) {
9129 case AA_Assigning:
9130 case AA_Initializing:
9131 // The destination type comes first.
9132 FirstType = DstType;
9133 SecondType = SrcType;
9134 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009135
Douglas Gregorc68e1402010-04-09 00:35:39 +00009136 case AA_Returning:
9137 case AA_Passing:
9138 case AA_Converting:
9139 case AA_Sending:
9140 case AA_Casting:
9141 // The source type comes first.
9142 FirstType = SrcType;
9143 SecondType = DstType;
9144 break;
9145 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009146
Anna Zaks3b402712011-07-28 19:51:27 +00009147 PartialDiagnostic FDiag = PDiag(DiagKind);
9148 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9149
9150 // If we can fix the conversion, suggest the FixIts.
9151 assert(ConvHints.isNull() || Hint.isNull());
9152 if (!ConvHints.isNull()) {
9153 for (llvm::SmallVector<FixItHint, 1>::iterator
9154 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9155 HI != HE; ++HI)
9156 FDiag << *HI;
9157 } else {
9158 FDiag << Hint;
9159 }
9160 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9161
9162 Diag(Loc, FDiag);
9163
Douglas Gregor33823722011-06-11 01:09:30 +00009164 if (CheckInferredResultType)
9165 EmitRelatedResultTypeNote(SrcExpr);
9166
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009167 if (Complained)
9168 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009169 return isInvalid;
9170}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009171
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009172bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009173 llvm::APSInt ICEResult;
9174 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9175 if (Result)
9176 *Result = ICEResult;
9177 return false;
9178 }
9179
Anders Carlssone54e8a12008-11-30 19:50:32 +00009180 Expr::EvalResult EvalResult;
9181
Mike Stump4e1f26a2009-02-19 03:04:26 +00009182 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009183 EvalResult.HasSideEffects) {
9184 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9185
9186 if (EvalResult.Diag) {
9187 // We only show the note if it's not the usual "invalid subexpression"
9188 // or if it's actually in a subexpression.
9189 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9190 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9191 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9192 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009193
Anders Carlssone54e8a12008-11-30 19:50:32 +00009194 return true;
9195 }
9196
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009197 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9198 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009199
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009200 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009201 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009202 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009203 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009204
Anders Carlssone54e8a12008-11-30 19:50:32 +00009205 if (Result)
9206 *Result = EvalResult.Val.getInt();
9207 return false;
9208}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009209
Douglas Gregorff790f12009-11-26 00:44:06 +00009210void
Mike Stump11289f42009-09-09 15:08:12 +00009211Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009212 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009213 ExpressionEvaluationContextRecord(NewContext,
9214 ExprTemporaries.size(),
9215 ExprNeedsCleanups));
9216 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009217}
9218
Richard Trieucfc491d2011-08-02 04:35:43 +00009219void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009220 // Pop the current expression evaluation context off the stack.
9221 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9222 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009223
Douglas Gregorfab31f42009-12-12 07:57:52 +00009224 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9225 if (Rec.PotentiallyReferenced) {
9226 // Mark any remaining declarations in the current position of the stack
9227 // as "referenced". If they were not meant to be referenced, semantic
9228 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009229 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009230 I = Rec.PotentiallyReferenced->begin(),
9231 IEnd = Rec.PotentiallyReferenced->end();
9232 I != IEnd; ++I)
9233 MarkDeclarationReferenced(I->first, I->second);
9234 }
9235
9236 if (Rec.PotentiallyDiagnosed) {
9237 // Emit any pending diagnostics.
9238 for (PotentiallyEmittedDiagnostics::iterator
9239 I = Rec.PotentiallyDiagnosed->begin(),
9240 IEnd = Rec.PotentiallyDiagnosed->end();
9241 I != IEnd; ++I)
9242 Diag(I->first, I->second);
9243 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009244 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009245
9246 // When are coming out of an unevaluated context, clear out any
9247 // temporaries that we may have created as part of the evaluation of
9248 // the expression in that context: they aren't relevant because they
9249 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009250 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009251 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9252 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009253 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9254
9255 // Otherwise, merge the contexts together.
9256 } else {
9257 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9258 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009259
9260 // Destroy the popped expression evaluation record.
9261 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009262}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009263
John McCall31168b02011-06-15 23:02:42 +00009264void Sema::DiscardCleanupsInEvaluationContext() {
9265 ExprTemporaries.erase(
9266 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9267 ExprTemporaries.end());
9268 ExprNeedsCleanups = false;
9269}
9270
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009271/// \brief Note that the given declaration was referenced in the source code.
9272///
9273/// This routine should be invoke whenever a given declaration is referenced
9274/// in the source code, and where that reference occurred. If this declaration
9275/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9276/// C99 6.9p3), then the declaration will be marked as used.
9277///
9278/// \param Loc the location where the declaration was referenced.
9279///
9280/// \param D the declaration that has been referenced by the source code.
9281void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9282 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009283
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009284 D->setReferenced();
9285
Douglas Gregorebada0772010-06-17 23:14:26 +00009286 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009287 return;
Mike Stump11289f42009-09-09 15:08:12 +00009288
Richard Trieucfc491d2011-08-02 04:35:43 +00009289 // Mark a parameter or variable declaration "used", regardless of whether
9290 // we're in a template or not. The reason for this is that unevaluated
9291 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9292 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009293 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009294 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009295 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009296 return;
9297 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009298
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009299 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9300 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009301
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009302 // Do not mark anything as "used" within a dependent context; wait for
9303 // an instantiation.
9304 if (CurContext->isDependentContext())
9305 return;
Mike Stump11289f42009-09-09 15:08:12 +00009306
Douglas Gregorff790f12009-11-26 00:44:06 +00009307 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009308 case Unevaluated:
9309 // We are in an expression that is not potentially evaluated; do nothing.
9310 return;
Mike Stump11289f42009-09-09 15:08:12 +00009311
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009312 case PotentiallyEvaluated:
9313 // We are in a potentially-evaluated expression, so this declaration is
9314 // "used"; handle this below.
9315 break;
Mike Stump11289f42009-09-09 15:08:12 +00009316
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009317 case PotentiallyPotentiallyEvaluated:
9318 // We are in an expression that may be potentially evaluated; queue this
9319 // declaration reference until we know whether the expression is
9320 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009321 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009322 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009323
9324 case PotentiallyEvaluatedIfUsed:
9325 // Referenced declarations will only be used if the construct in the
9326 // containing expression is used.
9327 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009328 }
Mike Stump11289f42009-09-09 15:08:12 +00009329
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009330 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009331 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009332 if (Constructor->isDefaulted()) {
9333 if (Constructor->isDefaultConstructor()) {
9334 if (Constructor->isTrivial())
9335 return;
9336 if (!Constructor->isUsed(false))
9337 DefineImplicitDefaultConstructor(Loc, Constructor);
9338 } else if (Constructor->isCopyConstructor()) {
9339 if (!Constructor->isUsed(false))
9340 DefineImplicitCopyConstructor(Loc, Constructor);
9341 } else if (Constructor->isMoveConstructor()) {
9342 if (!Constructor->isUsed(false))
9343 DefineImplicitMoveConstructor(Loc, Constructor);
9344 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009345 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009346
Douglas Gregor88d292c2010-05-13 16:44:06 +00009347 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009348 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009349 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009350 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009351 if (Destructor->isVirtual())
9352 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009353 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009354 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009355 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009356 if (!MethodDecl->isUsed(false)) {
9357 if (MethodDecl->isCopyAssignmentOperator())
9358 DefineImplicitCopyAssignment(Loc, MethodDecl);
9359 else
9360 DefineImplicitMoveAssignment(Loc, MethodDecl);
9361 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009362 } else if (MethodDecl->isVirtual())
9363 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009364 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009365 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009366 // Recursive functions should be marked when used from another function.
9367 if (CurContext == Function) return;
9368
Mike Stump11289f42009-09-09 15:08:12 +00009369 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009370 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009371 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009372 bool AlreadyInstantiated = false;
9373 if (FunctionTemplateSpecializationInfo *SpecInfo
9374 = Function->getTemplateSpecializationInfo()) {
9375 if (SpecInfo->getPointOfInstantiation().isInvalid())
9376 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009377 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009378 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009379 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009380 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009381 = Function->getMemberSpecializationInfo()) {
9382 if (MSInfo->getPointOfInstantiation().isInvalid())
9383 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009384 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009385 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009386 AlreadyInstantiated = true;
9387 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009388
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009389 if (!AlreadyInstantiated) {
9390 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9391 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9392 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9393 Loc));
9394 else
Chandler Carruth54080172010-08-25 08:44:16 +00009395 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009396 }
John McCall83779672011-02-19 02:53:41 +00009397 } else {
9398 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009399 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9400 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009401 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009402 MarkDeclarationReferenced(Loc, *i);
9403 }
John McCall83779672011-02-19 02:53:41 +00009404 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009405
John McCall83779672011-02-19 02:53:41 +00009406 // Keep track of used but undefined functions.
9407 if (!Function->isPure() && !Function->hasBody() &&
9408 Function->getLinkage() != ExternalLinkage) {
9409 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9410 if (old.isInvalid()) old = Loc;
9411 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009412
John McCall83779672011-02-19 02:53:41 +00009413 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009414 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009415 }
Mike Stump11289f42009-09-09 15:08:12 +00009416
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009417 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009418 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009419 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009420 Var->getInstantiatedFromStaticDataMember()) {
9421 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9422 assert(MSInfo && "Missing member specialization information?");
9423 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9424 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9425 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009426 // This is a modification of an existing AST node. Notify listeners.
9427 if (ASTMutationListener *L = getASTMutationListener())
9428 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009429 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009430 }
9431 }
Mike Stump11289f42009-09-09 15:08:12 +00009432
John McCall15dd4042011-02-21 19:25:48 +00009433 // Keep track of used but undefined variables. We make a hole in
9434 // the warning for static const data members with in-line
9435 // initializers.
John McCall83779672011-02-19 02:53:41 +00009436 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009437 && Var->getLinkage() != ExternalLinkage
9438 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009439 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9440 if (old.isInvalid()) old = Loc;
9441 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009442
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009443 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009444 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009445 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009446}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009447
Douglas Gregor5597ab42010-05-07 23:12:07 +00009448namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009449 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009450 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009451 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009452 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9453 Sema &S;
9454 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009455
Douglas Gregor5597ab42010-05-07 23:12:07 +00009456 public:
9457 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009458
Douglas Gregor5597ab42010-05-07 23:12:07 +00009459 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009460
9461 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9462 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009463 };
9464}
9465
Chandler Carruthaf80f662010-06-09 08:17:30 +00009466bool MarkReferencedDecls::TraverseTemplateArgument(
9467 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009468 if (Arg.getKind() == TemplateArgument::Declaration) {
9469 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9470 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009471
9472 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009473}
9474
Chandler Carruthaf80f662010-06-09 08:17:30 +00009475bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009476 if (ClassTemplateSpecializationDecl *Spec
9477 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9478 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009479 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009480 }
9481
Chandler Carruthc65667c2010-06-10 10:31:57 +00009482 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009483}
9484
9485void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9486 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009487 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009488}
9489
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009490namespace {
9491 /// \brief Helper class that marks all of the declarations referenced by
9492 /// potentially-evaluated subexpressions as "referenced".
9493 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9494 Sema &S;
9495
9496 public:
9497 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9498
9499 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9500
9501 void VisitDeclRefExpr(DeclRefExpr *E) {
9502 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9503 }
9504
9505 void VisitMemberExpr(MemberExpr *E) {
9506 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009507 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009508 }
9509
9510 void VisitCXXNewExpr(CXXNewExpr *E) {
9511 if (E->getConstructor())
9512 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9513 if (E->getOperatorNew())
9514 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9515 if (E->getOperatorDelete())
9516 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009517 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009518 }
9519
9520 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9521 if (E->getOperatorDelete())
9522 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009523 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9524 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9525 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9526 S.MarkDeclarationReferenced(E->getLocStart(),
9527 S.LookupDestructor(Record));
9528 }
9529
Douglas Gregor32b3de52010-09-11 23:32:50 +00009530 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009531 }
9532
9533 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9534 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009535 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009536 }
9537
9538 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9539 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9540 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009541
9542 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9543 Visit(E->getExpr());
9544 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009545 };
9546}
9547
9548/// \brief Mark any declarations that appear within this expression or any
9549/// potentially-evaluated subexpressions as "referenced".
9550void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9551 EvaluatedExprMarker(*this).Visit(E);
9552}
9553
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009554/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9555/// of the program being compiled.
9556///
9557/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009558/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009559/// possibility that the code will actually be executable. Code in sizeof()
9560/// expressions, code used only during overload resolution, etc., are not
9561/// potentially evaluated. This routine will suppress such diagnostics or,
9562/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009563/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009564/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009565///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009566/// This routine should be used for all diagnostics that describe the run-time
9567/// behavior of a program, such as passing a non-POD value through an ellipsis.
9568/// Failure to do so will likely result in spurious diagnostics or failures
9569/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009570bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009571 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009572 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009573 case Unevaluated:
9574 // The argument will never be evaluated, so don't complain.
9575 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009576
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009577 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009578 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009579 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009580 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009581 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009582 }
9583 else
9584 Diag(Loc, PD);
9585
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009586 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009587
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009588 case PotentiallyPotentiallyEvaluated:
9589 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9590 break;
9591 }
9592
9593 return false;
9594}
9595
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009596bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9597 CallExpr *CE, FunctionDecl *FD) {
9598 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9599 return false;
9600
9601 PartialDiagnostic Note =
9602 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9603 << FD->getDeclName() : PDiag();
9604 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009605
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009606 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009607 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009608 PDiag(diag::err_call_function_incomplete_return)
9609 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009610 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009611 << CE->getSourceRange(),
9612 std::make_pair(NoteLoc, Note)))
9613 return true;
9614
9615 return false;
9616}
9617
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009618// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009619// will prevent this condition from triggering, which is what we want.
9620void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9621 SourceLocation Loc;
9622
John McCall0506e4a2009-11-11 02:41:58 +00009623 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009624 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009625
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009626 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009627 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009628 return;
9629
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009630 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9631
John McCallb0e419e2009-11-12 00:06:05 +00009632 // Greylist some idioms by putting them into a warning subcategory.
9633 if (ObjCMessageExpr *ME
9634 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9635 Selector Sel = ME->getSelector();
9636
John McCallb0e419e2009-11-12 00:06:05 +00009637 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009638 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009639 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9640
9641 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009642 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009643 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9644 }
John McCall0506e4a2009-11-11 02:41:58 +00009645
John McCalld5707ab2009-10-12 21:59:07 +00009646 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009647 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009648 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009649 return;
9650
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009651 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009652 Loc = Op->getOperatorLoc();
9653 } else {
9654 // Not an assignment.
9655 return;
9656 }
9657
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009658 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009659
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009660 SourceLocation Open = E->getSourceRange().getBegin();
9661 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9662 Diag(Loc, diag::note_condition_assign_silence)
9663 << FixItHint::CreateInsertion(Open, "(")
9664 << FixItHint::CreateInsertion(Close, ")");
9665
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009666 if (IsOrAssign)
9667 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9668 << FixItHint::CreateReplacement(Loc, "!=");
9669 else
9670 Diag(Loc, diag::note_condition_assign_to_comparison)
9671 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009672}
9673
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009674/// \brief Redundant parentheses over an equality comparison can indicate
9675/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009676void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009677 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009678 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009679 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9680 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009681 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009682 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009683 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009684
Richard Trieuba63ce62011-09-09 01:45:06 +00009685 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009686
9687 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009688 if (opE->getOpcode() == BO_EQ &&
9689 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9690 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009691 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009692
Ted Kremenekae022092011-02-02 02:20:30 +00009693 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009694 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009695 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9696 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009697 Diag(Loc, diag::note_equality_comparison_to_assign)
9698 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009699 }
9700}
9701
John Wiegley01296292011-04-08 18:41:53 +00009702ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009703 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009704 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9705 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009706
John McCall0009fcc2011-04-26 20:42:42 +00009707 ExprResult result = CheckPlaceholderExpr(E);
9708 if (result.isInvalid()) return ExprError();
9709 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009710
John McCall0009fcc2011-04-26 20:42:42 +00009711 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009712 if (getLangOptions().CPlusPlus)
9713 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9714
John Wiegley01296292011-04-08 18:41:53 +00009715 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9716 if (ERes.isInvalid())
9717 return ExprError();
9718 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009719
9720 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009721 if (!T->isScalarType()) { // C99 6.8.4.1p1
9722 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9723 << T << E->getSourceRange();
9724 return ExprError();
9725 }
John McCalld5707ab2009-10-12 21:59:07 +00009726 }
9727
John Wiegley01296292011-04-08 18:41:53 +00009728 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009729}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009730
John McCalldadc5752010-08-24 06:29:42 +00009731ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009732 Expr *SubExpr) {
9733 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009734 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009735
Richard Trieuba63ce62011-09-09 01:45:06 +00009736 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009737}
John McCall36e7fe32010-10-12 00:20:44 +00009738
John McCall31996342011-04-07 08:22:57 +00009739namespace {
John McCall2979fe02011-04-12 00:42:48 +00009740 /// A visitor for rebuilding a call to an __unknown_any expression
9741 /// to have an appropriate type.
9742 struct RebuildUnknownAnyFunction
9743 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9744
9745 Sema &S;
9746
9747 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9748
9749 ExprResult VisitStmt(Stmt *S) {
9750 llvm_unreachable("unexpected statement!");
9751 return ExprError();
9752 }
9753
Richard Trieu10162ab2011-09-09 03:59:41 +00009754 ExprResult VisitExpr(Expr *E) {
9755 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9756 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009757 return ExprError();
9758 }
9759
9760 /// Rebuild an expression which simply semantically wraps another
9761 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009762 template <class T> ExprResult rebuildSugarExpr(T *E) {
9763 ExprResult SubResult = Visit(E->getSubExpr());
9764 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009765
Richard Trieu10162ab2011-09-09 03:59:41 +00009766 Expr *SubExpr = SubResult.take();
9767 E->setSubExpr(SubExpr);
9768 E->setType(SubExpr->getType());
9769 E->setValueKind(SubExpr->getValueKind());
9770 assert(E->getObjectKind() == OK_Ordinary);
9771 return E;
John McCall2979fe02011-04-12 00:42:48 +00009772 }
9773
Richard Trieu10162ab2011-09-09 03:59:41 +00009774 ExprResult VisitParenExpr(ParenExpr *E) {
9775 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009776 }
9777
Richard Trieu10162ab2011-09-09 03:59:41 +00009778 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9779 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009780 }
9781
Richard Trieu10162ab2011-09-09 03:59:41 +00009782 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9783 ExprResult SubResult = Visit(E->getSubExpr());
9784 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009785
Richard Trieu10162ab2011-09-09 03:59:41 +00009786 Expr *SubExpr = SubResult.take();
9787 E->setSubExpr(SubExpr);
9788 E->setType(S.Context.getPointerType(SubExpr->getType()));
9789 assert(E->getValueKind() == VK_RValue);
9790 assert(E->getObjectKind() == OK_Ordinary);
9791 return E;
John McCall2979fe02011-04-12 00:42:48 +00009792 }
9793
Richard Trieu10162ab2011-09-09 03:59:41 +00009794 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9795 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009796
Richard Trieu10162ab2011-09-09 03:59:41 +00009797 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009798
Richard Trieu10162ab2011-09-09 03:59:41 +00009799 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009800 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009801 !(isa<CXXMethodDecl>(VD) &&
9802 cast<CXXMethodDecl>(VD)->isInstance()))
9803 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009804
Richard Trieu10162ab2011-09-09 03:59:41 +00009805 return E;
John McCall2979fe02011-04-12 00:42:48 +00009806 }
9807
Richard Trieu10162ab2011-09-09 03:59:41 +00009808 ExprResult VisitMemberExpr(MemberExpr *E) {
9809 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009810 }
9811
Richard Trieu10162ab2011-09-09 03:59:41 +00009812 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9813 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009814 }
9815 };
9816}
9817
9818/// Given a function expression of unknown-any type, try to rebuild it
9819/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009820static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9821 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9822 if (Result.isInvalid()) return ExprError();
9823 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009824}
9825
9826namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009827 /// A visitor for rebuilding an expression of type __unknown_anytype
9828 /// into one which resolves the type directly on the referring
9829 /// expression. Strict preservation of the original source
9830 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009831 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009832 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009833
9834 Sema &S;
9835
9836 /// The current destination type.
9837 QualType DestType;
9838
Richard Trieu10162ab2011-09-09 03:59:41 +00009839 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9840 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009841
John McCall39439732011-04-09 22:50:59 +00009842 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009843 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009844 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009845 }
9846
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 ExprResult VisitExpr(Expr *E) {
9848 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9849 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009850 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009851 }
9852
Richard Trieu10162ab2011-09-09 03:59:41 +00009853 ExprResult VisitCallExpr(CallExpr *E);
9854 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009855
John McCall39439732011-04-09 22:50:59 +00009856 /// Rebuild an expression which simply semantically wraps another
9857 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009858 template <class T> ExprResult rebuildSugarExpr(T *E) {
9859 ExprResult SubResult = Visit(E->getSubExpr());
9860 if (SubResult.isInvalid()) return ExprError();
9861 Expr *SubExpr = SubResult.take();
9862 E->setSubExpr(SubExpr);
9863 E->setType(SubExpr->getType());
9864 E->setValueKind(SubExpr->getValueKind());
9865 assert(E->getObjectKind() == OK_Ordinary);
9866 return E;
John McCall39439732011-04-09 22:50:59 +00009867 }
John McCall31996342011-04-07 08:22:57 +00009868
Richard Trieu10162ab2011-09-09 03:59:41 +00009869 ExprResult VisitParenExpr(ParenExpr *E) {
9870 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009871 }
9872
Richard Trieu10162ab2011-09-09 03:59:41 +00009873 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9874 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009875 }
9876
Richard Trieu10162ab2011-09-09 03:59:41 +00009877 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9878 const PointerType *Ptr = DestType->getAs<PointerType>();
9879 if (!Ptr) {
9880 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9881 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009882 return ExprError();
9883 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009884 assert(E->getValueKind() == VK_RValue);
9885 assert(E->getObjectKind() == OK_Ordinary);
9886 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009887
9888 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009889 DestType = Ptr->getPointeeType();
9890 ExprResult SubResult = Visit(E->getSubExpr());
9891 if (SubResult.isInvalid()) return ExprError();
9892 E->setSubExpr(SubResult.take());
9893 return E;
John McCall2979fe02011-04-12 00:42:48 +00009894 }
9895
Richard Trieu10162ab2011-09-09 03:59:41 +00009896 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009897
Richard Trieu10162ab2011-09-09 03:59:41 +00009898 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009899
Richard Trieu10162ab2011-09-09 03:59:41 +00009900 ExprResult VisitMemberExpr(MemberExpr *E) {
9901 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009902 }
John McCall39439732011-04-09 22:50:59 +00009903
Richard Trieu10162ab2011-09-09 03:59:41 +00009904 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9905 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009906 }
9907 };
9908}
9909
John McCall2d2e8702011-04-11 07:02:50 +00009910/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009911ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9912 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009913
9914 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009915 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009916 FK_FunctionPointer,
9917 FK_BlockPointer
9918 };
9919
Richard Trieu10162ab2011-09-09 03:59:41 +00009920 FnKind Kind;
9921 QualType CalleeType = CalleeExpr->getType();
9922 if (CalleeType == S.Context.BoundMemberTy) {
9923 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9924 Kind = FK_MemberFunction;
9925 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9926 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9927 CalleeType = Ptr->getPointeeType();
9928 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009929 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009930 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9931 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009932 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009933 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009934
9935 // Verify that this is a legal result type of a function.
9936 if (DestType->isArrayType() || DestType->isFunctionType()) {
9937 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009938 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009939 diagID = diag::err_block_returning_array_function;
9940
Richard Trieu10162ab2011-09-09 03:59:41 +00009941 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009942 << DestType->isFunctionType() << DestType;
9943 return ExprError();
9944 }
9945
9946 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009947 E->setType(DestType.getNonLValueExprType(S.Context));
9948 E->setValueKind(Expr::getValueKindForType(DestType));
9949 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009950
9951 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009952 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009953 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009954 Proto->arg_type_begin(),
9955 Proto->getNumArgs(),
9956 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009957 else
9958 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009959 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009960
9961 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009962 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009963 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009964 // Nothing to do.
9965 break;
9966
9967 case FK_FunctionPointer:
9968 DestType = S.Context.getPointerType(DestType);
9969 break;
9970
9971 case FK_BlockPointer:
9972 DestType = S.Context.getBlockPointerType(DestType);
9973 break;
9974 }
9975
9976 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009977 ExprResult CalleeResult = Visit(CalleeExpr);
9978 if (!CalleeResult.isUsable()) return ExprError();
9979 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009980
9981 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009983}
9984
Richard Trieu10162ab2011-09-09 03:59:41 +00009985ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009986 // Verify that this is a legal result type of a call.
9987 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009988 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009989 << DestType->isFunctionType() << DestType;
9990 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009991 }
9992
John McCall3f4138c2011-07-13 17:56:40 +00009993 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009994 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9995 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9996 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009997 }
John McCall2979fe02011-04-12 00:42:48 +00009998
John McCall2d2e8702011-04-11 07:02:50 +00009999 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000010000 E->setType(DestType.getNonReferenceType());
10001 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010002
Richard Trieu10162ab2011-09-09 03:59:41 +000010003 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010004}
10005
Richard Trieu10162ab2011-09-09 03:59:41 +000010006ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010007 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +000010008 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10009 assert(E->getValueKind() == VK_RValue);
10010 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010011
Richard Trieu10162ab2011-09-09 03:59:41 +000010012 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010013
John McCall2d2e8702011-04-11 07:02:50 +000010014 // Rebuild the sub-expression as the pointee (function) type.
10015 DestType = DestType->castAs<PointerType>()->getPointeeType();
10016
Richard Trieu10162ab2011-09-09 03:59:41 +000010017 ExprResult Result = Visit(E->getSubExpr());
10018 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010019
Richard Trieu10162ab2011-09-09 03:59:41 +000010020 E->setSubExpr(Result.take());
10021 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010022}
10023
Richard Trieu10162ab2011-09-09 03:59:41 +000010024ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10025 ExprValueKind ValueKind = VK_LValue;
10026 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010027
10028 // We know how to make this work for certain kinds of decls:
10029
10030 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10032 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10033 DestType = Ptr->getPointeeType();
10034 ExprResult Result = resolveDecl(E, VD);
10035 if (Result.isInvalid()) return ExprError();
10036 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010037 CK_FunctionToPointerDecay, VK_RValue);
10038 }
10039
Richard Trieu10162ab2011-09-09 03:59:41 +000010040 if (!Type->isFunctionType()) {
10041 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10042 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010043 return ExprError();
10044 }
John McCall2d2e8702011-04-11 07:02:50 +000010045
Richard Trieu10162ab2011-09-09 03:59:41 +000010046 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10047 if (MD->isInstance()) {
10048 ValueKind = VK_RValue;
10049 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010050 }
10051
John McCall2d2e8702011-04-11 07:02:50 +000010052 // Function references aren't l-values in C.
10053 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010054 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010055
10056 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010057 } else if (isa<VarDecl>(VD)) {
10058 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10059 Type = RefTy->getPointeeType();
10060 } else if (Type->isFunctionType()) {
10061 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10062 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010063 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010064 }
10065
10066 // - nothing else
10067 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010068 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10069 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010070 return ExprError();
10071 }
10072
Richard Trieu10162ab2011-09-09 03:59:41 +000010073 VD->setType(DestType);
10074 E->setType(Type);
10075 E->setValueKind(ValueKind);
10076 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010077}
10078
John McCall31996342011-04-07 08:22:57 +000010079/// Check a cast of an unknown-any type. We intentionally only
10080/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010081ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10082 Expr *CastExpr, CastKind &CastKind,
10083 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010084 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010085 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010086 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010087
Richard Trieuba63ce62011-09-09 01:45:06 +000010088 CastExpr = result.take();
10089 VK = CastExpr->getValueKind();
10090 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010091
Richard Trieuba63ce62011-09-09 01:45:06 +000010092 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010093}
10094
Richard Trieuba63ce62011-09-09 01:45:06 +000010095static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10096 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010097 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010098 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010099 E = E->IgnoreParenImpCasts();
10100 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10101 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010102 diagID = diag::err_uncasted_call_of_unknown_any;
10103 } else {
John McCall31996342011-04-07 08:22:57 +000010104 break;
John McCall2d2e8702011-04-11 07:02:50 +000010105 }
John McCall31996342011-04-07 08:22:57 +000010106 }
10107
John McCall2d2e8702011-04-11 07:02:50 +000010108 SourceLocation loc;
10109 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010110 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010111 loc = ref->getLocation();
10112 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010113 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010114 loc = mem->getMemberLoc();
10115 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010116 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010117 diagID = diag::err_uncasted_call_of_unknown_any;
10118 loc = msg->getSelectorLoc();
10119 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010120 if (!d) {
10121 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10122 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10123 << orig->getSourceRange();
10124 return ExprError();
10125 }
John McCall2d2e8702011-04-11 07:02:50 +000010126 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010127 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10128 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010129 return ExprError();
10130 }
10131
10132 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010133
10134 // Never recoverable.
10135 return ExprError();
10136}
10137
John McCall36e7fe32010-10-12 00:20:44 +000010138/// Check for operands with placeholder types and complain if found.
10139/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010140ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010141 // Placeholder types are always *exactly* the appropriate builtin type.
10142 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010143
John McCall31996342011-04-07 08:22:57 +000010144 // Overloaded expressions.
10145 if (type == Context.OverloadTy)
10146 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010147 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010148 QualType(),
10149 diag::err_ovl_unresolvable);
10150
John McCall0009fcc2011-04-26 20:42:42 +000010151 // Bound member functions.
10152 if (type == Context.BoundMemberTy) {
10153 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10154 << E->getSourceRange();
10155 return ExprError();
10156 }
10157
John McCall31996342011-04-07 08:22:57 +000010158 // Expressions of unknown type.
10159 if (type == Context.UnknownAnyTy)
10160 return diagnoseUnknownAnyExpr(*this, E);
10161
10162 assert(!type->isPlaceholderType());
10163 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010164}
Richard Trieu2c850c02011-04-21 21:44:26 +000010165
Richard Trieuba63ce62011-09-09 01:45:06 +000010166bool Sema::CheckCaseExpression(Expr *E) {
10167 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010168 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010169 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10170 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010171 return false;
10172}