blob: eb5678e7f002a20978ffb63ead26146d3101183b [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,
3262 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003263 // Bail out early if calling a builtin with custom typechecking.
3264 // We don't need to do this in the
3265 if (FDecl)
3266 if (unsigned ID = FDecl->getBuiltinID())
3267 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3268 return false;
3269
Mike Stump4e1f26a2009-02-19 03:04:26 +00003270 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003271 // assignment, to the types of the corresponding parameter, ...
3272 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003273 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003274
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003275 // If too few arguments are available (and we don't have default
3276 // arguments for the remaining parameters), don't make the call.
3277 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003278 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3279 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003280 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003281 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003282
3283 // Emit the location of the prototype.
3284 if (FDecl && !FDecl->getBuiltinID())
3285 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3286 << FDecl;
3287
3288 return true;
3289 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003290 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003291 }
3292
3293 // If too many are passed and not variadic, error on the extras and drop
3294 // them.
3295 if (NumArgs > NumArgsInProto) {
3296 if (!Proto->isVariadic()) {
3297 Diag(Args[NumArgsInProto]->getLocStart(),
3298 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003299 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003300 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003301 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3302 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003303
3304 // Emit the location of the prototype.
3305 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003306 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3307 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003308
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003309 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003310 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003311 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003312 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003313 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003314 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003315 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003316 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3317 if (Fn->getType()->isBlockPointerType())
3318 CallType = VariadicBlock; // Block
3319 else if (isa<MemberExpr>(Fn))
3320 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003321 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003322 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003323 if (Invalid)
3324 return true;
3325 unsigned TotalNumArgs = AllArgs.size();
3326 for (unsigned i = 0; i < TotalNumArgs; ++i)
3327 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003328
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 return false;
3330}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003331
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003332bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3333 FunctionDecl *FDecl,
3334 const FunctionProtoType *Proto,
3335 unsigned FirstProtoArg,
3336 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003337 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003338 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003339 unsigned NumArgsInProto = Proto->getNumArgs();
3340 unsigned NumArgsToCheck = NumArgs;
3341 bool Invalid = false;
3342 if (NumArgs != NumArgsInProto)
3343 // Use default arguments for missing arguments
3344 NumArgsToCheck = NumArgsInProto;
3345 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003346 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003347 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003348 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003349
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003350 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003351 if (ArgIx < NumArgs) {
3352 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003353
Eli Friedman3164fb12009-03-22 22:00:50 +00003354 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3355 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003356 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003358 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003359
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003360 // Pass the argument
3361 ParmVarDecl *Param = 0;
3362 if (FDecl && i < FDecl->getNumParams())
3363 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003364
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003365 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003366 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003367 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3368 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003369 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003370 SourceLocation(),
3371 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003372 if (ArgE.isInvalid())
3373 return true;
3374
3375 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003376 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003377 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003378
John McCalldadc5752010-08-24 06:29:42 +00003379 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003380 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003381 if (ArgExpr.isInvalid())
3382 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003383
Anders Carlsson355933d2009-08-25 03:49:14 +00003384 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003385 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003386
3387 // Check for array bounds violations for each argument to the call. This
3388 // check only triggers warnings when the argument isn't a more complex Expr
3389 // with its own checking, such as a BinaryOperator.
3390 CheckArrayAccess(Arg);
3391
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003392 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003393 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003394
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003395 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003396 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003397
3398 // Assume that extern "C" functions with variadic arguments that
3399 // return __unknown_anytype aren't *really* variadic.
3400 if (Proto->getResultType() == Context.UnknownAnyTy &&
3401 FDecl && FDecl->isExternC()) {
3402 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3403 ExprResult arg;
3404 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3405 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3406 else
3407 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3408 Invalid |= arg.isInvalid();
3409 AllArgs.push_back(arg.take());
3410 }
3411
3412 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3413 } else {
3414 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003415 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3416 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003417 Invalid |= Arg.isInvalid();
3418 AllArgs.push_back(Arg.take());
3419 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003420 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003421
3422 // Check for array bounds violations.
3423 for (unsigned i = ArgIx; i != NumArgs; ++i)
3424 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003425 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003426 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003427}
3428
John McCall2979fe02011-04-12 00:42:48 +00003429/// Given a function expression of unknown-any type, try to rebuild it
3430/// to have a function type.
3431static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3432
Steve Naroff83895f72007-09-16 03:34:24 +00003433/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003434/// This provides the location of the left/right parens and a list of comma
3435/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003436ExprResult
John McCallb268a282010-08-23 23:25:46 +00003437Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003438 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003439 Expr *ExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003440 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003441
3442 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003443 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003444 if (Result.isInvalid()) return ExprError();
3445 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003446
Richard Trieuba63ce62011-09-09 01:45:06 +00003447 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003448
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003449 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003450 // If this is a pseudo-destructor expression, build the call immediately.
3451 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3452 if (NumArgs > 0) {
3453 // Pseudo-destructor calls should not have any arguments.
3454 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003455 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003456 SourceRange(Args[0]->getLocStart(),
3457 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregorad8a3362009-09-04 17:36:40 +00003459 NumArgs = 0;
3460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregorad8a3362009-09-04 17:36:40 +00003462 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003463 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003466 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003467 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003468 // FIXME: Will need to cache the results of name lookup (including ADL) in
3469 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003470 bool Dependent = false;
3471 if (Fn->isTypeDependent())
3472 Dependent = true;
3473 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3474 Dependent = true;
3475
Peter Collingbourne41f85462011-02-09 21:07:24 +00003476 if (Dependent) {
3477 if (ExecConfig) {
3478 return Owned(new (Context) CUDAKernelCallExpr(
3479 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3480 Context.DependentTy, VK_RValue, RParenLoc));
3481 } else {
3482 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3483 Context.DependentTy, VK_RValue,
3484 RParenLoc));
3485 }
3486 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003487
3488 // Determine whether this is a call to an object (C++ [over.call.object]).
3489 if (Fn->getType()->isRecordType())
3490 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003491 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003492
John McCall2979fe02011-04-12 00:42:48 +00003493 if (Fn->getType() == Context.UnknownAnyTy) {
3494 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3495 if (result.isInvalid()) return ExprError();
3496 Fn = result.take();
3497 }
3498
John McCall0009fcc2011-04-26 20:42:42 +00003499 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003500 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003501 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003502 }
John McCall0009fcc2011-04-26 20:42:42 +00003503 }
John McCall10eae182009-11-30 22:42:35 +00003504
John McCall0009fcc2011-04-26 20:42:42 +00003505 // Check for overloaded calls. This can happen even in C due to extensions.
3506 if (Fn->getType() == Context.OverloadTy) {
3507 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3508
3509 // We aren't supposed to apply this logic if there's an '&' involved.
3510 if (!find.IsAddressOfOperand) {
3511 OverloadExpr *ovl = find.Expression;
3512 if (isa<UnresolvedLookupExpr>(ovl)) {
3513 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3514 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3515 RParenLoc, ExecConfig);
3516 } else {
John McCall2d74de92009-12-01 22:10:20 +00003517 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003518 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003519 }
3520 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003521 }
3522
Douglas Gregore254f902009-02-04 00:32:51 +00003523 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003524
Eli Friedmane14b1992009-12-26 03:35:45 +00003525 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003526
John McCall57500772009-12-16 12:17:52 +00003527 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3529 if (UnOp->getOpcode() == UO_AddrOf)
3530 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3531
John McCall57500772009-12-16 12:17:52 +00003532 if (isa<DeclRefExpr>(NakedFn))
3533 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003534 else if (isa<MemberExpr>(NakedFn))
3535 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003536
Peter Collingbourne41f85462011-02-09 21:07:24 +00003537 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3538 ExecConfig);
3539}
3540
3541ExprResult
3542Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003543 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003544 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3545 if (!ConfigDecl)
3546 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3547 << "cudaConfigureCall");
3548 QualType ConfigQTy = ConfigDecl->getType();
3549
3550 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3551 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3552
Richard Trieuba63ce62011-09-09 01:45:06 +00003553 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003554}
3555
Tanya Lattner55808c12011-06-04 00:47:47 +00003556/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3557///
3558/// __builtin_astype( value, dst type )
3559///
Richard Trieuba63ce62011-09-09 01:45:06 +00003560ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003561 SourceLocation BuiltinLoc,
3562 SourceLocation RParenLoc) {
3563 ExprValueKind VK = VK_RValue;
3564 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003565 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3566 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003567 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3568 return ExprError(Diag(BuiltinLoc,
3569 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003570 << DstTy
3571 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003572 << E->getSourceRange());
3573 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003574 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003575}
3576
John McCall57500772009-12-16 12:17:52 +00003577/// BuildResolvedCallExpr - Build a call to a resolved expression,
3578/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003579/// unary-convert to an expression of function-pointer or
3580/// block-pointer type.
3581///
3582/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003583ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003584Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3585 SourceLocation LParenLoc,
3586 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003587 SourceLocation RParenLoc,
3588 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3590
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003591 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003592 ExprResult Result = UsualUnaryConversions(Fn);
3593 if (Result.isInvalid())
3594 return ExprError();
3595 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003596
Chris Lattner08464942007-12-28 05:29:59 +00003597 // Make the call expr early, before semantic checks. This guarantees cleanup
3598 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003599 CallExpr *TheCall;
3600 if (Config) {
3601 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3602 cast<CallExpr>(Config),
3603 Args, NumArgs,
3604 Context.BoolTy,
3605 VK_RValue,
3606 RParenLoc);
3607 } else {
3608 TheCall = new (Context) CallExpr(Context, Fn,
3609 Args, NumArgs,
3610 Context.BoolTy,
3611 VK_RValue,
3612 RParenLoc);
3613 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003614
John McCallbebede42011-02-26 05:39:39 +00003615 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3616
3617 // Bail out early if calling a builtin with custom typechecking.
3618 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3619 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3620
John McCall31996342011-04-07 08:22:57 +00003621 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003622 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003623 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003624 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3625 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003626 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003627 if (FuncT == 0)
3628 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3629 << Fn->getType() << Fn->getSourceRange());
3630 } else if (const BlockPointerType *BPT =
3631 Fn->getType()->getAs<BlockPointerType>()) {
3632 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3633 } else {
John McCall31996342011-04-07 08:22:57 +00003634 // Handle calls to expressions of unknown-any type.
3635 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003636 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003637 if (rewrite.isInvalid()) return ExprError();
3638 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003639 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003640 goto retry;
3641 }
3642
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003643 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3644 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003645 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003646
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003647 if (getLangOptions().CUDA) {
3648 if (Config) {
3649 // CUDA: Kernel calls must be to global functions
3650 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3651 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3652 << FDecl->getName() << Fn->getSourceRange());
3653
3654 // CUDA: Kernel function must have 'void' return type
3655 if (!FuncT->getResultType()->isVoidType())
3656 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3657 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003658 } else {
3659 // CUDA: Calls to global functions must be configured
3660 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3661 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3662 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003663 }
3664 }
3665
Eli Friedman3164fb12009-03-22 22:00:50 +00003666 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003667 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003668 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003669 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003670 return ExprError();
3671
Chris Lattner08464942007-12-28 05:29:59 +00003672 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003673 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003674 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003675
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003676 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003677 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003678 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003679 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003680 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003681 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003682
Douglas Gregord8e97de2009-04-02 15:37:10 +00003683 if (FDecl) {
3684 // Check if we have too few/too many template arguments, based
3685 // on our knowledge of the function definition.
3686 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003687 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003688 const FunctionProtoType *Proto
3689 = Def->getType()->getAs<FunctionProtoType>();
3690 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003691 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3692 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003693 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003694
3695 // If the function we're calling isn't a function prototype, but we have
3696 // a function prototype from a prior declaratiom, use that prototype.
3697 if (!FDecl->hasPrototype())
3698 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003699 }
3700
Steve Naroff0b661582007-08-28 23:30:39 +00003701 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003702 for (unsigned i = 0; i != NumArgs; i++) {
3703 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003704
3705 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003706 InitializedEntity Entity
3707 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003708 Proto->getArgType(i),
3709 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003710 ExprResult ArgE = PerformCopyInitialization(Entity,
3711 SourceLocation(),
3712 Owned(Arg));
3713 if (ArgE.isInvalid())
3714 return true;
3715
3716 Arg = ArgE.takeAs<Expr>();
3717
3718 } else {
John Wiegley01296292011-04-08 18:41:53 +00003719 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3720
3721 if (ArgE.isInvalid())
3722 return true;
3723
3724 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003725 }
3726
Douglas Gregor83025412010-10-26 05:45:40 +00003727 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3728 Arg->getType(),
3729 PDiag(diag::err_call_incomplete_argument)
3730 << Arg->getSourceRange()))
3731 return ExprError();
3732
Chris Lattner08464942007-12-28 05:29:59 +00003733 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003734 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003735 }
Chris Lattner08464942007-12-28 05:29:59 +00003736
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003737 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3738 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003739 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3740 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003741
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003742 // Check for sentinels
3743 if (NDecl)
3744 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003745
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003746 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003747 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003748 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003749 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003750
John McCallbebede42011-02-26 05:39:39 +00003751 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003752 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003753 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003754 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003755 return ExprError();
3756 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003757
John McCallb268a282010-08-23 23:25:46 +00003758 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003759}
3760
John McCalldadc5752010-08-24 06:29:42 +00003761ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003762Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003763 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003764 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003765 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003766 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003767
3768 TypeSourceInfo *TInfo;
3769 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3770 if (!TInfo)
3771 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3772
John McCallb268a282010-08-23 23:25:46 +00003773 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003774}
3775
John McCalldadc5752010-08-24 06:29:42 +00003776ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003777Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003778 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003779 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003780
Eli Friedman37a186d2008-05-20 05:22:08 +00003781 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003782 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3783 PDiag(diag::err_illegal_decl_array_incomplete_type)
3784 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003785 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003786 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003787 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003788 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003789 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003790 } else if (!literalType->isDependentType() &&
3791 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003792 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003793 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003794 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003795 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003796
Douglas Gregor85dabae2009-12-16 01:38:02 +00003797 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003798 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003799 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003800 = InitializationKind::CreateCStyleCast(LParenLoc,
3801 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003802 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003803 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003804 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003805 &literalType);
3806 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003807 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003808 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003809
Chris Lattner79413952008-12-04 23:50:19 +00003810 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003811 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003812 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003813 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003814 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003815
John McCall7decc9e2010-11-18 06:31:45 +00003816 // In C, compound literals are l-values for some reason.
3817 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3818
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003819 return MaybeBindToTemporary(
3820 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003821 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003822}
3823
John McCalldadc5752010-08-24 06:29:42 +00003824ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003825Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003826 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003827 unsigned NumInit = InitArgList.size();
3828 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003829
Steve Naroff30d242c2007-09-15 18:49:24 +00003830 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003831 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003832
Ted Kremenekac034612010-04-13 23:39:13 +00003833 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3834 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003835 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003836 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003837}
3838
John McCallcd78e802011-09-10 01:16:55 +00003839/// Do an explicit extend of the given block pointer if we're in ARC.
3840static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3841 assert(E.get()->getType()->isBlockPointerType());
3842 assert(E.get()->isRValue());
3843
3844 // Only do this in an r-value context.
3845 if (!S.getLangOptions().ObjCAutoRefCount) return;
3846
3847 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003848 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003849 /*base path*/ 0, VK_RValue);
3850 S.ExprNeedsCleanups = true;
3851}
3852
3853/// Prepare a conversion of the given expression to an ObjC object
3854/// pointer type.
3855CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3856 QualType type = E.get()->getType();
3857 if (type->isObjCObjectPointerType()) {
3858 return CK_BitCast;
3859 } else if (type->isBlockPointerType()) {
3860 maybeExtendBlockObject(*this, E);
3861 return CK_BlockPointerToObjCPointerCast;
3862 } else {
3863 assert(type->isPointerType());
3864 return CK_CPointerToObjCPointerCast;
3865 }
3866}
3867
John McCalld7646252010-11-14 08:17:51 +00003868/// Prepares for a scalar cast, performing all the necessary stages
3869/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003870static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003871 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3872 // Also, callers should have filtered out the invalid cases with
3873 // pointers. Everything else should be possible.
3874
John Wiegley01296292011-04-08 18:41:53 +00003875 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003876 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003877 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003878
John McCall9320b872011-09-09 05:25:32 +00003879 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003880 case Type::STK_MemberPointer:
3881 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003882
John McCall9320b872011-09-09 05:25:32 +00003883 case Type::STK_CPointer:
3884 case Type::STK_BlockPointer:
3885 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003886 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003887 case Type::STK_CPointer:
3888 return CK_BitCast;
3889 case Type::STK_BlockPointer:
3890 return (SrcKind == Type::STK_BlockPointer
3891 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3892 case Type::STK_ObjCObjectPointer:
3893 if (SrcKind == Type::STK_ObjCObjectPointer)
3894 return CK_BitCast;
3895 else if (SrcKind == Type::STK_CPointer)
3896 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003897 else {
3898 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003899 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003900 }
John McCall8cb679e2010-11-15 09:13:47 +00003901 case Type::STK_Bool:
3902 return CK_PointerToBoolean;
3903 case Type::STK_Integral:
3904 return CK_PointerToIntegral;
3905 case Type::STK_Floating:
3906 case Type::STK_FloatingComplex:
3907 case Type::STK_IntegralComplex:
3908 case Type::STK_MemberPointer:
3909 llvm_unreachable("illegal cast from pointer");
3910 }
3911 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003912
John McCall8cb679e2010-11-15 09:13:47 +00003913 case Type::STK_Bool: // casting from bool is like casting from an integer
3914 case Type::STK_Integral:
3915 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003916 case Type::STK_CPointer:
3917 case Type::STK_ObjCObjectPointer:
3918 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003919 if (Src.get()->isNullPointerConstant(S.Context,
3920 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003921 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003922 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003923 case Type::STK_Bool:
3924 return CK_IntegralToBoolean;
3925 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003926 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003927 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003928 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003929 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003930 Src = S.ImpCastExprToType(Src.take(),
3931 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003932 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003933 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003934 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003935 Src = S.ImpCastExprToType(Src.take(),
3936 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003937 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003938 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003939 case Type::STK_MemberPointer:
3940 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003941 }
3942 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003943
John McCall8cb679e2010-11-15 09:13:47 +00003944 case Type::STK_Floating:
3945 switch (DestTy->getScalarTypeKind()) {
3946 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003947 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003948 case Type::STK_Bool:
3949 return CK_FloatingToBoolean;
3950 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003951 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003952 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003953 Src = S.ImpCastExprToType(Src.take(),
3954 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003955 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003956 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003957 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003958 Src = S.ImpCastExprToType(Src.take(),
3959 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003960 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003961 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003962 case Type::STK_CPointer:
3963 case Type::STK_ObjCObjectPointer:
3964 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003965 llvm_unreachable("valid float->pointer cast?");
3966 case Type::STK_MemberPointer:
3967 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003968 }
3969 break;
3970
John McCall8cb679e2010-11-15 09:13:47 +00003971 case Type::STK_FloatingComplex:
3972 switch (DestTy->getScalarTypeKind()) {
3973 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003974 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003975 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003976 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003977 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003978 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003979 if (S.Context.hasSameType(ET, DestTy))
3980 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003981 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003982 return CK_FloatingCast;
3983 }
John McCall8cb679e2010-11-15 09:13:47 +00003984 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003985 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003986 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003987 Src = S.ImpCastExprToType(Src.take(),
3988 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003989 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003990 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00003991 case Type::STK_CPointer:
3992 case Type::STK_ObjCObjectPointer:
3993 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003994 llvm_unreachable("valid complex float->pointer cast?");
3995 case Type::STK_MemberPointer:
3996 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003997 }
3998 break;
3999
John McCall8cb679e2010-11-15 09:13:47 +00004000 case Type::STK_IntegralComplex:
4001 switch (DestTy->getScalarTypeKind()) {
4002 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004003 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004004 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004005 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004006 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004007 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004008 if (S.Context.hasSameType(ET, DestTy))
4009 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00004010 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004011 return CK_IntegralCast;
4012 }
John McCall8cb679e2010-11-15 09:13:47 +00004013 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004014 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004015 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00004016 Src = S.ImpCastExprToType(Src.take(),
4017 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004018 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004019 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004020 case Type::STK_CPointer:
4021 case Type::STK_ObjCObjectPointer:
4022 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004023 llvm_unreachable("valid complex int->pointer cast?");
4024 case Type::STK_MemberPointer:
4025 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004026 }
4027 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004028 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004029
John McCalld7646252010-11-14 08:17:51 +00004030 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004031}
4032
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004033/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004034ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4035 SourceRange TypeRange, QualType CastType,
4036 Expr *CastExpr, CastKind &Kind,
4037 ExprValueKind &VK, CXXCastPath &BasePath,
4038 bool FunctionalStyle) {
4039 if (CastExpr->getType() == Context.UnknownAnyTy)
4040 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4041 BasePath);
John McCall31996342011-04-07 08:22:57 +00004042
Sebastian Redl9f831db2009-07-25 15:41:38 +00004043 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004044 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004045 CastExpr->getLocEnd()),
4046 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004047 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004048
Richard Trieuba63ce62011-09-09 01:45:06 +00004049 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004050
John McCall7decc9e2010-11-18 06:31:45 +00004051 // We only support r-value casts in C.
4052 VK = VK_RValue;
4053
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004054 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4055 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004056 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004057 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004058 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004059 if (castExprRes.isInvalid())
4060 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004061 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004062
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004063 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004064 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004065 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004066 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004067
Richard Trieuba63ce62011-09-09 01:45:06 +00004068 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004069 if (castExprRes.isInvalid())
4070 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004071 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004072
Richard Trieuba63ce62011-09-09 01:45:06 +00004073 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004074 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004075 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004076
Richard Trieuba63ce62011-09-09 01:45:06 +00004077 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4078 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4079 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004080 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004081 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004082 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4083 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004084 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004085 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004086 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004087
Richard Trieuba63ce62011-09-09 01:45:06 +00004088 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004089 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004090 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004091 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004092 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004093 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004094 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004095 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004096 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004097 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4098 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004099 break;
4100 }
4101 }
John Wiegley01296292011-04-08 18:41:53 +00004102 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004103 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4104 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004105 return ExprError();
4106 }
John McCalle3027922010-08-25 11:45:40 +00004107 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004108 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004109 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004110
Anders Carlsson525b76b2009-10-16 02:48:28 +00004111 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004112 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4113 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004114 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004115 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004116
John McCalld7646252010-11-14 08:17:51 +00004117 // The type we're casting to is known to be a scalar or vector.
4118
4119 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004120 if (!CastExpr->getType()->isScalarType() &&
4121 !CastExpr->getType()->isVectorType()) {
4122 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004123 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004124 << CastExpr->getType() << 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
Richard Trieuba63ce62011-09-09 01:45:06 +00004128 if (CastType->isExtVectorType())
4129 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004130
Richard Trieuba63ce62011-09-09 01:45:06 +00004131 if (CastType->isVectorType()) {
4132 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004133 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004134 (CastExpr->getType()->isIntegerType() ||
4135 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004136 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004137 return Owned(CastExpr);
4138 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4139 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004140 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004141 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004143 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004144 if (CastExpr->getType()->isVectorType()) {
4145 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004146 return ExprError();
4147 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004148 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004149 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004150
John McCalld7646252010-11-14 08:17:51 +00004151 // The source and target types are both scalars, i.e.
4152 // - arithmetic types (fundamental, enum, and complex)
4153 // - all kinds of pointers
4154 // Note that member pointers were filtered out with C++, above.
4155
Richard Trieuba63ce62011-09-09 01:45:06 +00004156 if (isa<ObjCSelectorExpr>(CastExpr)) {
4157 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004158 return ExprError();
4159 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004160
John McCalld7646252010-11-14 08:17:51 +00004161 // If either type is a pointer, the other type has to be either an
4162 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004163 QualType CastExprType = CastExpr->getType();
4164 if (!CastType->isArithmeticType()) {
4165 if (!CastExprType->isIntegralType(Context) &&
4166 CastExprType->isArithmeticType()) {
4167 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004168 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004169 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004170 return ExprError();
4171 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004172 } else if (!CastExpr->getType()->isArithmeticType()) {
4173 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4174 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4175 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004176 return ExprError();
4177 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004178 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004179
John McCall31168b02011-06-15 23:02:42 +00004180 if (getLangOptions().ObjCAutoRefCount) {
4181 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004182 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4183 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004184
Richard Trieuba63ce62011-09-09 01:45:06 +00004185 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4186 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004187 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4188 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4189 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4190 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4191 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004192 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004193 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004194 << CastExprType << CastType << AA_Casting
4195 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004196
4197 return ExprError();
4198 }
4199 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004200 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004201 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4202 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004203 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004204 << CastExprType << CastType
4205 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004206 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004207 }
4208 }
4209
Richard Trieuba63ce62011-09-09 01:45:06 +00004210 castExprRes = Owned(CastExpr);
4211 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004212 if (castExprRes.isInvalid())
4213 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004214 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004215
John McCalld7646252010-11-14 08:17:51 +00004216 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004217 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004218
Richard Trieuba63ce62011-09-09 01:45:06 +00004219 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004220}
4221
Anders Carlsson525b76b2009-10-16 02:48:28 +00004222bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004223 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004224 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004225
Anders Carlssonde71adf2007-11-27 05:51:55 +00004226 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004227 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004228 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004229 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004230 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004231 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004232 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004233 } else
4234 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004235 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004236 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004237
John McCalle3027922010-08-25 11:45:40 +00004238 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004239 return false;
4240}
4241
John Wiegley01296292011-04-08 18:41:53 +00004242ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4243 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004244 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004245
Anders Carlsson43d70f82009-10-16 05:23:41 +00004246 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004247
Nate Begemanc8961a42009-06-27 22:05:55 +00004248 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4249 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004250 // In OpenCL, casts between vectors of different types are not allowed.
4251 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004252 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004253 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4254 || (getLangOptions().OpenCL &&
4255 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004256 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004257 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004258 return ExprError();
4259 }
John McCalle3027922010-08-25 11:45:40 +00004260 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004261 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004262 }
4263
Nate Begemanbd956c42009-06-28 02:36:38 +00004264 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004265 // conversion will take place first from scalar to elt type, and then
4266 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004267 if (SrcTy->isPointerType())
4268 return Diag(R.getBegin(),
4269 diag::err_invalid_conversion_between_vector_and_scalar)
4270 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004271
4272 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004273 ExprResult CastExprRes = Owned(CastExpr);
4274 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4275 if (CastExprRes.isInvalid())
4276 return ExprError();
4277 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004278
John McCalle3027922010-08-25 11:45:40 +00004279 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004280 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004281}
4282
John McCalldadc5752010-08-24 06:29:42 +00004283ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004284Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4285 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004286 SourceLocation RParenLoc, Expr *CastExpr) {
4287 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004288 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004289
Richard Trieuba63ce62011-09-09 01:45:06 +00004290 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004291 if (D.isInvalidType())
4292 return ExprError();
4293
4294 if (getLangOptions().CPlusPlus) {
4295 // Check that there are no default arguments (C++ only).
4296 CheckExtraCXXDefaultArguments(D);
4297 }
4298
John McCall42856de2011-10-01 05:17:03 +00004299 checkUnusedDeclAttributes(D);
4300
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004301 QualType castType = castTInfo->getType();
4302 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004303
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004304 bool isVectorLiteral = false;
4305
4306 // Check for an altivec or OpenCL literal,
4307 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004308 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4309 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004310 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4311 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004312 if (PLE && PLE->getNumExprs() == 0) {
4313 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4314 return ExprError();
4315 }
4316 if (PE || PLE->getNumExprs() == 1) {
4317 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4318 if (!E->getType()->isVectorType())
4319 isVectorLiteral = true;
4320 }
4321 else
4322 isVectorLiteral = true;
4323 }
4324
4325 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4326 // then handle it as such.
4327 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004328 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004329
Nate Begeman5ec4b312009-08-10 23:49:36 +00004330 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004331 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4332 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004333 if (isa<ParenListExpr>(CastExpr)) {
4334 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004335 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004336 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004337 }
John McCallebe54742010-01-15 18:56:44 +00004338
Richard Trieuba63ce62011-09-09 01:45:06 +00004339 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004340}
4341
John McCalldadc5752010-08-24 06:29:42 +00004342ExprResult
John McCallebe54742010-01-15 18:56:44 +00004343Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004344 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004345 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004346 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004347 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004348 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004349 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004350 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004351 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004352 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004353 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004354
Richard Trieucfc491d2011-08-02 04:35:43 +00004355 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004356 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004357 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004358}
4359
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004360ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4361 SourceLocation RParenLoc, Expr *E,
4362 TypeSourceInfo *TInfo) {
4363 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4364 "Expected paren or paren list expression");
4365
4366 Expr **exprs;
4367 unsigned numExprs;
4368 Expr *subExpr;
4369 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4370 exprs = PE->getExprs();
4371 numExprs = PE->getNumExprs();
4372 } else {
4373 subExpr = cast<ParenExpr>(E)->getSubExpr();
4374 exprs = &subExpr;
4375 numExprs = 1;
4376 }
4377
4378 QualType Ty = TInfo->getType();
4379 assert(Ty->isVectorType() && "Expected vector type");
4380
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004381 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004382 const VectorType *VTy = Ty->getAs<VectorType>();
4383 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4384
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004385 // '(...)' form of vector initialization in AltiVec: the number of
4386 // initializers must be one or must match the size of the vector.
4387 // If a single value is specified in the initializer then it will be
4388 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004389 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004390 // The number of initializers must be one or must match the size of the
4391 // vector. If a single value is specified in the initializer then it will
4392 // be replicated to all the components of the vector
4393 if (numExprs == 1) {
4394 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4395 ExprResult Literal = Owned(exprs[0]);
4396 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4397 PrepareScalarCast(*this, Literal, ElemTy));
4398 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4399 }
4400 else if (numExprs < numElems) {
4401 Diag(E->getExprLoc(),
4402 diag::err_incorrect_number_of_vector_initializers);
4403 return ExprError();
4404 }
4405 else
4406 for (unsigned i = 0, e = numExprs; i != e; ++i)
4407 initExprs.push_back(exprs[i]);
4408 }
Tanya Lattner83559382011-07-15 23:07:01 +00004409 else {
4410 // For OpenCL, when the number of initializers is a single value,
4411 // it will be replicated to all components of the vector.
4412 if (getLangOptions().OpenCL &&
4413 VTy->getVectorKind() == VectorType::GenericVector &&
4414 numExprs == 1) {
4415 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4416 ExprResult Literal = Owned(exprs[0]);
4417 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4418 PrepareScalarCast(*this, Literal, ElemTy));
4419 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4420 }
4421
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004422 for (unsigned i = 0, e = numExprs; i != e; ++i)
4423 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004424 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004425 // FIXME: This means that pretty-printing the final AST will produce curly
4426 // braces instead of the original commas.
4427 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4428 &initExprs[0],
4429 initExprs.size(), RParenLoc);
4430 initE->setType(Ty);
4431 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4432}
4433
Nate Begeman5ec4b312009-08-10 23:49:36 +00004434/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4435/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004436ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004437Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4438 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004439 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004440 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004441
John McCalldadc5752010-08-24 06:29:42 +00004442 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004443
Nate Begeman5ec4b312009-08-10 23:49:36 +00004444 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004445 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4446 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004447
John McCallb268a282010-08-23 23:25:46 +00004448 if (Result.isInvalid()) return ExprError();
4449
4450 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004451}
4452
John McCalldadc5752010-08-24 06:29:42 +00004453ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004454 SourceLocation R,
4455 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004456 unsigned nexprs = Val.size();
4457 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004458 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4459 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004460 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004461 expr = new (Context) ParenExpr(L, R, exprs[0]);
4462 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004463 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4464 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004465 return Owned(expr);
4466}
4467
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004468/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004469/// constant and the other is not a pointer. Returns true if a diagnostic is
4470/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004471bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004472 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004473 Expr *NullExpr = LHSExpr;
4474 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004475 Expr::NullPointerConstantKind NullKind =
4476 NullExpr->isNullPointerConstant(Context,
4477 Expr::NPC_ValueDependentIsNotNull);
4478
4479 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004480 NullExpr = RHSExpr;
4481 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004482 NullKind =
4483 NullExpr->isNullPointerConstant(Context,
4484 Expr::NPC_ValueDependentIsNotNull);
4485 }
4486
4487 if (NullKind == Expr::NPCK_NotNull)
4488 return false;
4489
4490 if (NullKind == Expr::NPCK_ZeroInteger) {
4491 // In this case, check to make sure that we got here from a "NULL"
4492 // string in the source code.
4493 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004494 SourceLocation loc = NullExpr->getExprLoc();
4495 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004496 return false;
4497 }
4498
4499 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4500 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4501 << NonPointerExpr->getType() << DiagType
4502 << NonPointerExpr->getSourceRange();
4503 return true;
4504}
4505
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004506/// \brief Return false if the condition expression is valid, true otherwise.
4507static bool checkCondition(Sema &S, Expr *Cond) {
4508 QualType CondTy = Cond->getType();
4509
4510 // C99 6.5.15p2
4511 if (CondTy->isScalarType()) return false;
4512
4513 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4514 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4515 return false;
4516
4517 // Emit the proper error message.
4518 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4519 diag::err_typecheck_cond_expect_scalar :
4520 diag::err_typecheck_cond_expect_scalar_or_vector)
4521 << CondTy;
4522 return true;
4523}
4524
4525/// \brief Return false if the two expressions can be converted to a vector,
4526/// true otherwise
4527static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4528 ExprResult &RHS,
4529 QualType CondTy) {
4530 // Both operands should be of scalar type.
4531 if (!LHS.get()->getType()->isScalarType()) {
4532 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4533 << CondTy;
4534 return true;
4535 }
4536 if (!RHS.get()->getType()->isScalarType()) {
4537 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4538 << CondTy;
4539 return true;
4540 }
4541
4542 // Implicity convert these scalars to the type of the condition.
4543 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4544 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4545 return false;
4546}
4547
4548/// \brief Handle when one or both operands are void type.
4549static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4550 ExprResult &RHS) {
4551 Expr *LHSExpr = LHS.get();
4552 Expr *RHSExpr = RHS.get();
4553
4554 if (!LHSExpr->getType()->isVoidType())
4555 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4556 << RHSExpr->getSourceRange();
4557 if (!RHSExpr->getType()->isVoidType())
4558 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4559 << LHSExpr->getSourceRange();
4560 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4561 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4562 return S.Context.VoidTy;
4563}
4564
4565/// \brief Return false if the NullExpr can be promoted to PointerTy,
4566/// true otherwise.
4567static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4568 QualType PointerTy) {
4569 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4570 !NullExpr.get()->isNullPointerConstant(S.Context,
4571 Expr::NPC_ValueDependentIsNull))
4572 return true;
4573
4574 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4575 return false;
4576}
4577
4578/// \brief Checks compatibility between two pointers and return the resulting
4579/// type.
4580static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4581 ExprResult &RHS,
4582 SourceLocation Loc) {
4583 QualType LHSTy = LHS.get()->getType();
4584 QualType RHSTy = RHS.get()->getType();
4585
4586 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4587 // Two identical pointers types are always compatible.
4588 return LHSTy;
4589 }
4590
4591 QualType lhptee, rhptee;
4592
4593 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004594 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4595 lhptee = LHSBTy->getPointeeType();
4596 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004597 } else {
John McCall9320b872011-09-09 05:25:32 +00004598 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4599 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004600 }
4601
4602 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4603 rhptee.getUnqualifiedType())) {
4604 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4605 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4606 << RHS.get()->getSourceRange();
4607 // In this situation, we assume void* type. No especially good
4608 // reason, but this is what gcc does, and we do have to pick
4609 // to get a consistent AST.
4610 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4611 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4612 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4613 return incompatTy;
4614 }
4615
4616 // The pointer types are compatible.
4617 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4618 // differently qualified versions of compatible types, the result type is
4619 // a pointer to an appropriately qualified version of the *composite*
4620 // type.
4621 // FIXME: Need to calculate the composite type.
4622 // FIXME: Need to add qualifiers
4623
4624 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4625 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4626 return LHSTy;
4627}
4628
4629/// \brief Return the resulting type when the operands are both block pointers.
4630static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4631 ExprResult &LHS,
4632 ExprResult &RHS,
4633 SourceLocation Loc) {
4634 QualType LHSTy = LHS.get()->getType();
4635 QualType RHSTy = RHS.get()->getType();
4636
4637 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4638 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4639 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4640 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4641 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4642 return destType;
4643 }
4644 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4645 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4646 << RHS.get()->getSourceRange();
4647 return QualType();
4648 }
4649
4650 // We have 2 block pointer types.
4651 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4652}
4653
4654/// \brief Return the resulting type when the operands are both pointers.
4655static QualType
4656checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4657 ExprResult &RHS,
4658 SourceLocation Loc) {
4659 // get the pointer types
4660 QualType LHSTy = LHS.get()->getType();
4661 QualType RHSTy = RHS.get()->getType();
4662
4663 // get the "pointed to" types
4664 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4665 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4666
4667 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4668 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4669 // Figure out necessary qualifiers (C99 6.5.15p6)
4670 QualType destPointee
4671 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4672 QualType destType = S.Context.getPointerType(destPointee);
4673 // Add qualifiers if necessary.
4674 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4675 // Promote to void*.
4676 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4677 return destType;
4678 }
4679 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4680 QualType destPointee
4681 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4682 QualType destType = S.Context.getPointerType(destPointee);
4683 // Add qualifiers if necessary.
4684 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4685 // Promote to void*.
4686 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4687 return destType;
4688 }
4689
4690 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4691}
4692
4693/// \brief Return false if the first expression is not an integer and the second
4694/// expression is not a pointer, true otherwise.
4695static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4696 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004697 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004698 if (!PointerExpr->getType()->isPointerType() ||
4699 !Int.get()->getType()->isIntegerType())
4700 return false;
4701
Richard Trieuba63ce62011-09-09 01:45:06 +00004702 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4703 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004704
4705 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4706 << Expr1->getType() << Expr2->getType()
4707 << Expr1->getSourceRange() << Expr2->getSourceRange();
4708 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4709 CK_IntegralToPointer);
4710 return true;
4711}
4712
Richard Trieud33e46e2011-09-06 20:06:39 +00004713/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4714/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004715/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004716QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4717 ExprResult &RHS, ExprValueKind &VK,
4718 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004719 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004720
Richard Trieud33e46e2011-09-06 20:06:39 +00004721 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4722 if (!LHSResult.isUsable()) return QualType();
4723 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004724
Richard Trieud33e46e2011-09-06 20:06:39 +00004725 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4726 if (!RHSResult.isUsable()) return QualType();
4727 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004728
Sebastian Redl1a99f442009-04-16 17:51:27 +00004729 // C++ is sufficiently different to merit its own checker.
4730 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004731 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004732
4733 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004734 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004735
John Wiegley01296292011-04-08 18:41:53 +00004736 Cond = UsualUnaryConversions(Cond.take());
4737 if (Cond.isInvalid())
4738 return QualType();
4739 LHS = UsualUnaryConversions(LHS.take());
4740 if (LHS.isInvalid())
4741 return QualType();
4742 RHS = UsualUnaryConversions(RHS.take());
4743 if (RHS.isInvalid())
4744 return QualType();
4745
4746 QualType CondTy = Cond.get()->getType();
4747 QualType LHSTy = LHS.get()->getType();
4748 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004749
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004750 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004751 if (checkCondition(*this, Cond.get()))
4752 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004753
Chris Lattnere2949f42008-01-06 22:42:25 +00004754 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004755 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004756 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004757
Nate Begemanabb5a732010-09-20 22:41:17 +00004758 // OpenCL: If the condition is a vector, and both operands are scalar,
4759 // attempt to implicity convert them to the vector type to act like the
4760 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004761 if (getLangOptions().OpenCL && CondTy->isVectorType())
4762 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004763 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004764
Chris Lattnere2949f42008-01-06 22:42:25 +00004765 // If both operands have arithmetic type, do the usual arithmetic conversions
4766 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004767 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4768 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004769 if (LHS.isInvalid() || RHS.isInvalid())
4770 return QualType();
4771 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004772 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004773
Chris Lattnere2949f42008-01-06 22:42:25 +00004774 // If both operands are the same structure or union type, the result is that
4775 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004776 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4777 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004778 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004779 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004780 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004781 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004782 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004783 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004784
Chris Lattnere2949f42008-01-06 22:42:25 +00004785 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004786 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004787 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004788 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004789 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004790
Steve Naroff039ad3c2008-01-08 01:11:38 +00004791 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4792 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004793 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4794 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004795
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004796 // All objective-c pointer type analysis is done here.
4797 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4798 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004799 if (LHS.isInvalid() || RHS.isInvalid())
4800 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004801 if (!compositeType.isNull())
4802 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004803
4804
Steve Naroff05efa972009-07-01 14:36:47 +00004805 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004806 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4807 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4808 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004809
Steve Naroff05efa972009-07-01 14:36:47 +00004810 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004811 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4812 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4813 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004814
John McCalle84af4e2010-11-13 01:35:44 +00004815 // GCC compatibility: soften pointer/integer mismatch. Note that
4816 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004817 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4818 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004819 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004820 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4821 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004822 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004823
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004824 // Emit a better diagnostic if one of the expressions is a null pointer
4825 // constant and the other is not a pointer type. In this case, the user most
4826 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004827 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004828 return QualType();
4829
Chris Lattnere2949f42008-01-06 22:42:25 +00004830 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004831 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004832 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4833 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004834 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004835}
4836
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004837/// FindCompositeObjCPointerType - Helper method to find composite type of
4838/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004839QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004840 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004841 QualType LHSTy = LHS.get()->getType();
4842 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004843
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004844 // Handle things like Class and struct objc_class*. Here we case the result
4845 // to the pseudo-builtin, because that will be implicitly cast back to the
4846 // redefinition type if an attempt is made to access its fields.
4847 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004848 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004849 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004850 return LHSTy;
4851 }
4852 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004853 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004854 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004855 return RHSTy;
4856 }
4857 // And the same for struct objc_object* / id
4858 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004859 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
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->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004864 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
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_selector* / SEL
4869 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004870 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004871 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004872 return LHSTy;
4873 }
4874 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004875 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004876 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004877 return RHSTy;
4878 }
4879 // Check constraints for Objective-C object pointers types.
4880 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004881
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004882 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4883 // Two identical object pointer types are always compatible.
4884 return LHSTy;
4885 }
John McCall9320b872011-09-09 05:25:32 +00004886 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4887 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004888 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004889
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004890 // If both operands are interfaces and either operand can be
4891 // assigned to the other, use that type as the composite
4892 // type. This allows
4893 // xxx ? (A*) a : (B*) b
4894 // where B is a subclass of A.
4895 //
4896 // Additionally, as for assignment, if either type is 'id'
4897 // allow silent coercion. Finally, if the types are
4898 // incompatible then make sure to use 'id' as the composite
4899 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004900
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004901 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4902 // It could return the composite type.
4903 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4904 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4905 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4906 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4907 } else if ((LHSTy->isObjCQualifiedIdType() ||
4908 RHSTy->isObjCQualifiedIdType()) &&
4909 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4910 // Need to handle "id<xx>" explicitly.
4911 // GCC allows qualified id and any Objective-C type to devolve to
4912 // id. Currently localizing to here until clear this should be
4913 // part of ObjCQualifiedIdTypesAreCompatible.
4914 compositeType = Context.getObjCIdType();
4915 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4916 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004917 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004918 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4919 ;
4920 else {
4921 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4922 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004923 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004924 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004925 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4926 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004927 return incompatTy;
4928 }
4929 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004930 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4931 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004932 return compositeType;
4933 }
4934 // Check Objective-C object pointer types and 'void *'
4935 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4936 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4937 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4938 QualType destPointee
4939 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4940 QualType destType = Context.getPointerType(destPointee);
4941 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004942 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004943 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004944 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004945 return destType;
4946 }
4947 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4948 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4949 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4950 QualType destPointee
4951 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4952 QualType destType = Context.getPointerType(destPointee);
4953 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004954 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004955 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004956 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004957 return destType;
4958 }
4959 return QualType();
4960}
4961
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004962/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004963/// ParenRange in parentheses.
4964static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004965 const PartialDiagnostic &Note,
4966 SourceRange ParenRange) {
4967 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4968 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4969 EndLoc.isValid()) {
4970 Self.Diag(Loc, Note)
4971 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4972 << FixItHint::CreateInsertion(EndLoc, ")");
4973 } else {
4974 // We can't display the parentheses, so just show the bare note.
4975 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004976 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004977}
4978
4979static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4980 return Opc >= BO_Mul && Opc <= BO_Shr;
4981}
4982
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004983/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4984/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004985/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4986/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004987static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004988 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004989 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4990 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004991 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004992 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004993
4994 // Built-in binary operator.
4995 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4996 if (IsArithmeticOp(OP->getOpcode())) {
4997 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004998 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004999 return true;
5000 }
5001 }
5002
5003 // Overloaded operator.
5004 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5005 if (Call->getNumArgs() != 2)
5006 return false;
5007
5008 // Make sure this is really a binary operator that is safe to pass into
5009 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5010 OverloadedOperatorKind OO = Call->getOperator();
5011 if (OO < OO_Plus || OO > OO_Arrow)
5012 return false;
5013
5014 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5015 if (IsArithmeticOp(OpKind)) {
5016 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005017 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005018 return true;
5019 }
5020 }
5021
5022 return false;
5023}
5024
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005025static bool IsLogicOp(BinaryOperatorKind Opc) {
5026 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5027}
5028
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005029/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5030/// or is a logical expression such as (x==y) which has int type, but is
5031/// commonly interpreted as boolean.
5032static bool ExprLooksBoolean(Expr *E) {
5033 E = E->IgnoreParenImpCasts();
5034
5035 if (E->getType()->isBooleanType())
5036 return true;
5037 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5038 return IsLogicOp(OP->getOpcode());
5039 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5040 return OP->getOpcode() == UO_LNot;
5041
5042 return false;
5043}
5044
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005045/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5046/// and binary operator are mixed in a way that suggests the programmer assumed
5047/// the conditional operator has higher precedence, for example:
5048/// "int x = a + someBinaryCondition ? 1 : 2".
5049static void DiagnoseConditionalPrecedence(Sema &Self,
5050 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005051 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005052 Expr *LHSExpr,
5053 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005054 BinaryOperatorKind CondOpcode;
5055 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005056
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005057 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005058 return;
5059 if (!ExprLooksBoolean(CondRHS))
5060 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005061
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005062 // The condition is an arithmetic binary expression, with a right-
5063 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005064
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005065 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005066 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005067 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005068
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005069 SuggestParentheses(Self, OpLoc,
5070 Self.PDiag(diag::note_precedence_conditional_silence)
5071 << BinaryOperator::getOpcodeStr(CondOpcode),
5072 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005073
5074 SuggestParentheses(Self, OpLoc,
5075 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005076 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005077}
5078
Steve Naroff83895f72007-09-16 03:34:24 +00005079/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005080/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005081ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005082 SourceLocation ColonLoc,
5083 Expr *CondExpr, Expr *LHSExpr,
5084 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005085 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5086 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005087 OpaqueValueExpr *opaqueValue = 0;
5088 Expr *commonExpr = 0;
5089 if (LHSExpr == 0) {
5090 commonExpr = CondExpr;
5091
5092 // We usually want to apply unary conversions *before* saving, except
5093 // in the special case of a C++ l-value conditional.
5094 if (!(getLangOptions().CPlusPlus
5095 && !commonExpr->isTypeDependent()
5096 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5097 && commonExpr->isGLValue()
5098 && commonExpr->isOrdinaryOrBitFieldObject()
5099 && RHSExpr->isOrdinaryOrBitFieldObject()
5100 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005101 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5102 if (commonRes.isInvalid())
5103 return ExprError();
5104 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005105 }
5106
5107 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5108 commonExpr->getType(),
5109 commonExpr->getValueKind(),
5110 commonExpr->getObjectKind());
5111 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005112 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005113
John McCall7decc9e2010-11-18 06:31:45 +00005114 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005115 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005116 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5117 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005118 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005119 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5120 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005121 return ExprError();
5122
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005123 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5124 RHS.get());
5125
John McCallc07a0c72011-02-17 10:25:35 +00005126 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005127 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5128 LHS.take(), ColonLoc,
5129 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005130
5131 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005132 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005133 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5134 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005135}
5136
John McCallaba90822011-01-31 23:13:11 +00005137// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005138// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005139// routine is it effectively iqnores the qualifiers on the top level pointee.
5140// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5141// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005142static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005143checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5144 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5145 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005146
Steve Naroff1f4d7272007-05-11 04:00:31 +00005147 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005148 const Type *lhptee, *rhptee;
5149 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005150 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5151 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
John McCallaba90822011-01-31 23:13:11 +00005153 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005154
5155 // C99 6.5.16.1p1: This following citation is common to constraints
5156 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5157 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005158 Qualifiers lq;
5159
John McCall31168b02011-06-15 23:02:42 +00005160 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5161 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5162 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5163 // Ignore lifetime for further calculation.
5164 lhq.removeObjCLifetime();
5165 rhq.removeObjCLifetime();
5166 }
5167
John McCall4fff8f62011-02-01 00:10:29 +00005168 if (!lhq.compatiblyIncludes(rhq)) {
5169 // Treat address-space mismatches as fatal. TODO: address subspaces
5170 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5171 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5172
John McCall31168b02011-06-15 23:02:42 +00005173 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005174 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005175 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5176 .compatiblyIncludes(
5177 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005178 && (lhptee->isVoidType() || rhptee->isVoidType()))
5179 ; // keep old
5180
John McCall31168b02011-06-15 23:02:42 +00005181 // Treat lifetime mismatches as fatal.
5182 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5183 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5184
John McCall4fff8f62011-02-01 00:10:29 +00005185 // For GCC compatibility, other qualifier mismatches are treated
5186 // as still compatible in C.
5187 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5188 }
Steve Naroff3f597292007-05-11 22:18:03 +00005189
Mike Stump4e1f26a2009-02-19 03:04:26 +00005190 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5191 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005192 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005193 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005194 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005195 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005196
Chris Lattner0a788432008-01-03 22:56:36 +00005197 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005198 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005199 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005200 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201
Chris Lattner0a788432008-01-03 22:56:36 +00005202 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005203 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005204 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005205
5206 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005207 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005208 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005209 }
John McCall4fff8f62011-02-01 00:10:29 +00005210
Mike Stump4e1f26a2009-02-19 03:04:26 +00005211 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005212 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005213 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5214 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005215 // Check if the pointee types are compatible ignoring the sign.
5216 // We explicitly check for char so that we catch "char" vs
5217 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005218 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005219 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005220 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005221 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005222
Chris Lattnerec3a1562009-10-17 20:33:28 +00005223 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005224 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005225 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005226 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005227
John McCall4fff8f62011-02-01 00:10:29 +00005228 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005229 // Types are compatible ignoring the sign. Qualifier incompatibility
5230 // takes priority over sign incompatibility because the sign
5231 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005232 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005233 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005234
John McCallaba90822011-01-31 23:13:11 +00005235 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005236 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005237
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005238 // If we are a multi-level pointer, it's possible that our issue is simply
5239 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5240 // the eventual target type is the same and the pointers have the same
5241 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005242 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005243 do {
John McCall4fff8f62011-02-01 00:10:29 +00005244 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5245 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005246 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005247
John McCall4fff8f62011-02-01 00:10:29 +00005248 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005249 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005250 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005251
Eli Friedman80160bd2009-03-22 23:59:44 +00005252 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005253 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005254 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005255 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005256}
5257
John McCallaba90822011-01-31 23:13:11 +00005258/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005259/// block pointer types are compatible or whether a block and normal pointer
5260/// are compatible. It is more restrict than comparing two function pointer
5261// types.
John McCallaba90822011-01-31 23:13:11 +00005262static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005263checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5264 QualType RHSType) {
5265 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5266 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005267
Steve Naroff081c7422008-09-04 15:10:53 +00005268 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005269
Steve Naroff081c7422008-09-04 15:10:53 +00005270 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005271 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5272 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005273
John McCallaba90822011-01-31 23:13:11 +00005274 // In C++, the types have to match exactly.
5275 if (S.getLangOptions().CPlusPlus)
5276 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005277
John McCallaba90822011-01-31 23:13:11 +00005278 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005279
Steve Naroff081c7422008-09-04 15:10:53 +00005280 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005281 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5282 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005283
Richard Trieua871b972011-09-06 20:21:22 +00005284 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005285 return Sema::IncompatibleBlockPointer;
5286
Steve Naroff081c7422008-09-04 15:10:53 +00005287 return ConvTy;
5288}
5289
John McCallaba90822011-01-31 23:13:11 +00005290/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005291/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005292static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005293checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5294 QualType RHSType) {
5295 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5296 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005297
Richard Trieua871b972011-09-06 20:21:22 +00005298 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005299 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005300 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5301 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005302 return Sema::IncompatiblePointer;
5303 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005304 }
Richard Trieua871b972011-09-06 20:21:22 +00005305 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005306 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5307 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005308 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005309 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005310 }
Richard Trieua871b972011-09-06 20:21:22 +00005311 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5312 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005313
John McCallaba90822011-01-31 23:13:11 +00005314 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5315 return Sema::CompatiblePointerDiscardsQualifiers;
5316
Richard Trieua871b972011-09-06 20:21:22 +00005317 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005318 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005319 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005320 return Sema::IncompatibleObjCQualifiedId;
5321 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005322}
5323
John McCall29600e12010-11-16 02:32:08 +00005324Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005325Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005326 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005327 // Fake up an opaque expression. We don't actually care about what
5328 // cast operations are required, so if CheckAssignmentConstraints
5329 // adds casts to this they'll be wasted, but fortunately that doesn't
5330 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005331 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5332 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005333 CastKind K = CK_Invalid;
5334
Richard Trieua871b972011-09-06 20:21:22 +00005335 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005336}
5337
Mike Stump4e1f26a2009-02-19 03:04:26 +00005338/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5339/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005340/// pointers. Here are some objectionable examples that GCC considers warnings:
5341///
5342/// int a, *pint;
5343/// short *pshort;
5344/// struct foo *pfoo;
5345///
5346/// pint = pshort; // warning: assignment from incompatible pointer type
5347/// a = pint; // warning: assignment makes integer from pointer without a cast
5348/// pint = a; // warning: assignment makes pointer from integer without a cast
5349/// pint = pfoo; // warning: assignment from incompatible pointer type
5350///
5351/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005352/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005353///
John McCall8cb679e2010-11-15 09:13:47 +00005354/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005355Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005356Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005357 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005358 QualType RHSType = RHS.get()->getType();
5359 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005360
Chris Lattnera52c2f22008-01-04 23:18:45 +00005361 // Get canonical types. We're not formatting these types, just comparing
5362 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005363 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5364 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005365
John McCalle5255932011-01-31 22:28:28 +00005366 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005367 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005368 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005369 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005370 }
5371
Douglas Gregor6b754842008-10-28 00:22:11 +00005372 // If the left-hand side is a reference type, then we are in a
5373 // (rare!) case where we've allowed the use of references in C,
5374 // e.g., as a parameter type in a built-in function. In this case,
5375 // just make sure that the type referenced is compatible with the
5376 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005377 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005378 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005379 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5380 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005381 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005382 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005383 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005384 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005385 }
John McCalle5255932011-01-31 22:28:28 +00005386
Nate Begemanbd956c42009-06-28 02:36:38 +00005387 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5388 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005389 if (LHSType->isExtVectorType()) {
5390 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005391 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005392 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005393 // CK_VectorSplat does T -> vector T, so first cast to the
5394 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005395 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5396 if (elType != RHSType) {
5397 Kind = PrepareScalarCast(*this, RHS, elType);
5398 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005399 }
5400 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005401 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005402 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005403 }
Mike Stump11289f42009-09-09 15:08:12 +00005404
John McCalle5255932011-01-31 22:28:28 +00005405 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005406 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5407 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005408 // Allow assignments of an AltiVec vector type to an equivalent GCC
5409 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005410 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005411 Kind = CK_BitCast;
5412 return Compatible;
5413 }
5414
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005415 // If we are allowing lax vector conversions, and LHS and RHS are both
5416 // vectors, the total size only needs to be the same. This is a bitcast;
5417 // no bits are changed but the result type is different.
5418 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005419 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005420 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005421 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005422 }
Chris Lattner881a2122008-01-04 23:32:24 +00005423 }
5424 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005425 }
Eli Friedman3360d892008-05-30 18:07:22 +00005426
John McCalle5255932011-01-31 22:28:28 +00005427 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005428 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5429 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5430 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005431 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005432 }
Eli Friedman3360d892008-05-30 18:07:22 +00005433
John McCalle5255932011-01-31 22:28:28 +00005434 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005435 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005436 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005437 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005438 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005439 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005441
John McCalle5255932011-01-31 22:28:28 +00005442 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005443 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005444 Kind = CK_IntegralToPointer; // FIXME: null?
5445 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005446 }
John McCalle5255932011-01-31 22:28:28 +00005447
5448 // C pointers are not compatible with ObjC object pointers,
5449 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005450 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005451 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005452 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005453 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005454 return Compatible;
5455 }
5456
5457 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005458 if (RHSType->isObjCClassType() &&
5459 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005460 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005461 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005462 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005463 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005464
John McCalle5255932011-01-31 22:28:28 +00005465 Kind = CK_BitCast;
5466 return IncompatiblePointer;
5467 }
5468
5469 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005470 if (RHSType->getAs<BlockPointerType>()) {
5471 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005472 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005473 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005474 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005475 }
John McCalle5255932011-01-31 22:28:28 +00005476
Steve Naroff081c7422008-09-04 15:10:53 +00005477 return Incompatible;
5478 }
5479
John McCalle5255932011-01-31 22:28:28 +00005480 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005481 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005482 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005483 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005484 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005485 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005486 }
5487
5488 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005489 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005490 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005491 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005492 }
5493
John McCalle5255932011-01-31 22:28:28 +00005494 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005495 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005496 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005497 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005498 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005499
John McCalle5255932011-01-31 22:28:28 +00005500 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005501 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005502 if (RHSPT->getPointeeType()->isVoidType()) {
5503 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005504 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005505 }
John McCall8cb679e2010-11-15 09:13:47 +00005506
Chris Lattnera52c2f22008-01-04 23:18:45 +00005507 return Incompatible;
5508 }
5509
John McCalle5255932011-01-31 22:28:28 +00005510 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005511 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005512 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005513 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005514 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005515 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005516 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005517 if (getLangOptions().ObjCAutoRefCount &&
5518 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005519 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005520 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005521 return result;
John McCalle5255932011-01-31 22:28:28 +00005522 }
5523
5524 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005525 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005526 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005527 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005528 }
5529
John McCalle5255932011-01-31 22:28:28 +00005530 // In general, C pointers are not compatible with ObjC object pointers,
5531 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005532 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005533 Kind = CK_CPointerToObjCPointerCast;
5534
John McCalle5255932011-01-31 22:28:28 +00005535 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005536 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005537 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005538 }
5539
5540 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005541 if (LHSType->isObjCClassType() &&
5542 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005543 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005544 return Compatible;
5545 }
5546
Steve Naroffaccc4882009-07-20 17:56:53 +00005547 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005548 }
John McCalle5255932011-01-31 22:28:28 +00005549
5550 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005551 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005552 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005553 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005554 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005555 }
5556
Steve Naroff7cae42b2009-07-10 23:34:53 +00005557 return Incompatible;
5558 }
John McCalle5255932011-01-31 22:28:28 +00005559
5560 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005561 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005562 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005563 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005564 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005565 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005566 }
Eli Friedman3360d892008-05-30 18:07:22 +00005567
John McCalle5255932011-01-31 22:28:28 +00005568 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005569 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005570 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005571 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005572 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005573
Chris Lattnera52c2f22008-01-04 23:18:45 +00005574 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005575 }
John McCalle5255932011-01-31 22:28:28 +00005576
5577 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005578 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005579 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005580 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005581 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005582 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005583 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005584
John McCalle5255932011-01-31 22:28:28 +00005585 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005586 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005587 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005589 }
5590
Steve Naroff7cae42b2009-07-10 23:34:53 +00005591 return Incompatible;
5592 }
Eli Friedman3360d892008-05-30 18:07:22 +00005593
John McCalle5255932011-01-31 22:28:28 +00005594 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005595 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5596 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005597 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005598 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005599 }
Bill Wendling216423b2007-05-30 06:30:29 +00005600 }
John McCalle5255932011-01-31 22:28:28 +00005601
Steve Naroff98cf3e92007-06-06 18:38:38 +00005602 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005603}
5604
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005605/// \brief Constructs a transparent union from an expression that is
5606/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005607static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5608 ExprResult &EResult, QualType UnionType,
5609 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005610 // Build an initializer list that designates the appropriate member
5611 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005612 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005613 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005614 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005615 SourceLocation());
5616 Initializer->setType(UnionType);
5617 Initializer->setInitializedFieldInUnion(Field);
5618
5619 // Build a compound literal constructing a value of the transparent
5620 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005621 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005622 EResult = S.Owned(
5623 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5624 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005625}
5626
5627Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005628Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005629 ExprResult &RHS) {
5630 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005631
Mike Stump11289f42009-09-09 15:08:12 +00005632 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005633 // transparent_union GCC extension.
5634 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005635 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005636 return Incompatible;
5637
5638 // The field to initialize within the transparent union.
5639 RecordDecl *UD = UT->getDecl();
5640 FieldDecl *InitField = 0;
5641 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005642 for (RecordDecl::field_iterator it = UD->field_begin(),
5643 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005644 it != itend; ++it) {
5645 if (it->getType()->isPointerType()) {
5646 // If the transparent union contains a pointer type, we allow:
5647 // 1) void pointer
5648 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005649 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005650 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005651 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005652 InitField = *it;
5653 break;
5654 }
Mike Stump11289f42009-09-09 15:08:12 +00005655
Richard Trieueb299142011-09-06 20:40:12 +00005656 if (RHS.get()->isNullPointerConstant(Context,
5657 Expr::NPC_ValueDependentIsNull)) {
5658 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5659 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005660 InitField = *it;
5661 break;
5662 }
5663 }
5664
John McCall8cb679e2010-11-15 09:13:47 +00005665 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005666 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005667 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005668 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005669 InitField = *it;
5670 break;
5671 }
5672 }
5673
5674 if (!InitField)
5675 return Incompatible;
5676
Richard Trieueb299142011-09-06 20:40:12 +00005677 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005678 return Compatible;
5679}
5680
Chris Lattner9bad62c2008-01-04 18:04:52 +00005681Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005682Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5683 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005684 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005685 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005686 // C++ 5.17p3: If the left operand is not of class type, the
5687 // expression is implicitly converted (C++ 4) to the
5688 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005689 ExprResult Res = PerformImplicitConversion(RHS.get(),
5690 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005691 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005692 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005693 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005694 Sema::AssignConvertType result = Compatible;
5695 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005696 !CheckObjCARCUnavailableWeakConversion(LHSType,
5697 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005698 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005699 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005700 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005701 }
5702
5703 // FIXME: Currently, we fall through and treat C++ classes like C
5704 // structures.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005705 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005706
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005707 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5708 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005709 if ((LHSType->isPointerType() ||
5710 LHSType->isObjCObjectPointerType() ||
5711 LHSType->isBlockPointerType())
5712 && RHS.get()->isNullPointerConstant(Context,
5713 Expr::NPC_ValueDependentIsNull)) {
5714 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005715 return Compatible;
5716 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005717
Chris Lattnere6dcd502007-10-16 02:55:40 +00005718 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005719 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005720 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005721 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005722 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005723 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005724 if (!LHSType->isReferenceType()) {
5725 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5726 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005727 return Incompatible;
5728 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005729
John McCall8cb679e2010-11-15 09:13:47 +00005730 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005731 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005732 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005733
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005734 // C99 6.5.16.1p2: The value of the right operand is converted to the
5735 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005736 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5737 // so that we can use references in built-in functions even in C.
5738 // The getNonReferenceType() call makes sure that the resulting expression
5739 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005740 if (result != Incompatible && RHS.get()->getType() != LHSType)
5741 RHS = ImpCastExprToType(RHS.take(),
5742 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005743 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005744}
5745
Richard Trieueb299142011-09-06 20:40:12 +00005746QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5747 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005748 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005749 << LHS.get()->getType() << RHS.get()->getType()
5750 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005751 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005752}
5753
Richard Trieu859d23f2011-09-06 21:01:04 +00005754QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005755 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005756 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005757 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005758 QualType LHSType =
5759 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5760 QualType RHSType =
5761 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005762
Nate Begeman191a6b12008-07-14 18:02:46 +00005763 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005764 if (LHSType == RHSType)
5765 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005766
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005767 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005768 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5769 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5770 if (LHSType->isExtVectorType()) {
5771 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5772 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005773 }
5774
Richard Trieuba63ce62011-09-09 01:45:06 +00005775 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005776 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5777 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005778 }
5779
Eli Friedman1408bc92011-06-23 18:10:35 +00005780 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005782 // If we are allowing lax vector conversions, and LHS and RHS are both
5783 // vectors, the total size only needs to be the same. This is a
5784 // bitcast; no bits are changed but the result type is different.
5785 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005786 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5787 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005788 }
5789
Nate Begemanbd956c42009-06-28 02:36:38 +00005790 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5791 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5792 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005793 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005794 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005795 std::swap(RHS, LHS);
5796 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005797 }
Mike Stump11289f42009-09-09 15:08:12 +00005798
Nate Begeman886448d2009-06-28 19:12:57 +00005799 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005800 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005801 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005802 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5803 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005804 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005805 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005806 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005807 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5808 if (swapped) std::swap(RHS, LHS);
5809 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005810 }
5811 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005812 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5813 RHSType->isRealFloatingType()) {
5814 int order = Context.getFloatingTypeOrder(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_FloatingCast);
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 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005822 }
5823 }
Mike Stump11289f42009-09-09 15:08:12 +00005824
Nate Begeman886448d2009-06-28 19:12:57 +00005825 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005826 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005827 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005828 << LHS.get()->getType() << RHS.get()->getType()
5829 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005830 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005831}
5832
Richard Trieuf8916e12011-09-16 00:53:10 +00005833// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5834// expression. These are mainly cases where the null pointer is used as an
5835// integer instead of a pointer.
5836static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5837 SourceLocation Loc, bool IsCompare) {
5838 // The canonical way to check for a GNU null is with isNullPointerConstant,
5839 // but we use a bit of a hack here for speed; this is a relatively
5840 // hot path, and isNullPointerConstant is slow.
5841 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5842 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5843
5844 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5845
5846 // Avoid analyzing cases where the result will either be invalid (and
5847 // diagnosed as such) or entirely valid and not something to warn about.
5848 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5849 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5850 return;
5851
5852 // Comparison operations would not make sense with a null pointer no matter
5853 // what the other expression is.
5854 if (!IsCompare) {
5855 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5856 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5857 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5858 return;
5859 }
5860
5861 // The rest of the operations only make sense with a null pointer
5862 // if the other expression is a pointer.
5863 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5864 NonNullType->canDecayToPointerType())
5865 return;
5866
5867 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5868 << LHSNull /* LHS is NULL */ << NonNullType
5869 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5870}
5871
Richard Trieu859d23f2011-09-06 21:01:04 +00005872QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005873 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005874 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005875 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5876
Richard Trieu859d23f2011-09-06 21:01:04 +00005877 if (LHS.get()->getType()->isVectorType() ||
5878 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005879 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005880
Richard Trieuba63ce62011-09-09 01:45:06 +00005881 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005882 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005883 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005884
Richard Trieu859d23f2011-09-06 21:01:04 +00005885 if (!LHS.get()->getType()->isArithmeticType() ||
5886 !RHS.get()->getType()->isArithmeticType())
5887 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005888
Chris Lattnerfaa54172010-01-12 21:23:57 +00005889 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005890 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005891 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005892 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005893 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5894 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005895
Chris Lattnerfaa54172010-01-12 21:23:57 +00005896 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005897}
5898
Chris Lattnerfaa54172010-01-12 21:23:57 +00005899QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005900 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005901 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5902
Richard Trieu859d23f2011-09-06 21:01:04 +00005903 if (LHS.get()->getType()->isVectorType() ||
5904 RHS.get()->getType()->isVectorType()) {
5905 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5906 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005907 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005908 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005909 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005910
Richard Trieuba63ce62011-09-09 01:45:06 +00005911 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005912 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005913 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005914
Richard Trieu859d23f2011-09-06 21:01:04 +00005915 if (!LHS.get()->getType()->isIntegerType() ||
5916 !RHS.get()->getType()->isIntegerType())
5917 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005918
Chris Lattnerfaa54172010-01-12 21:23:57 +00005919 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005920 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005921 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005922 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5923 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005924
Chris Lattnerfaa54172010-01-12 21:23:57 +00005925 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005926}
5927
Chandler Carruthc9332212011-06-27 08:02:19 +00005928/// \brief Diagnose invalid arithmetic on two void pointers.
5929static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005930 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005931 S.Diag(Loc, S.getLangOptions().CPlusPlus
5932 ? diag::err_typecheck_pointer_arith_void_type
5933 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005934 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5935 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005936}
5937
5938/// \brief Diagnose invalid arithmetic on a void pointer.
5939static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5940 Expr *Pointer) {
5941 S.Diag(Loc, S.getLangOptions().CPlusPlus
5942 ? diag::err_typecheck_pointer_arith_void_type
5943 : diag::ext_gnu_void_ptr)
5944 << 0 /* one pointer */ << Pointer->getSourceRange();
5945}
5946
5947/// \brief Diagnose invalid arithmetic on two function pointers.
5948static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5949 Expr *LHS, Expr *RHS) {
5950 assert(LHS->getType()->isAnyPointerType());
5951 assert(RHS->getType()->isAnyPointerType());
5952 S.Diag(Loc, S.getLangOptions().CPlusPlus
5953 ? diag::err_typecheck_pointer_arith_function_type
5954 : diag::ext_gnu_ptr_func_arith)
5955 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5956 // We only show the second type if it differs from the first.
5957 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5958 RHS->getType())
5959 << RHS->getType()->getPointeeType()
5960 << LHS->getSourceRange() << RHS->getSourceRange();
5961}
5962
5963/// \brief Diagnose invalid arithmetic on a function pointer.
5964static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5965 Expr *Pointer) {
5966 assert(Pointer->getType()->isAnyPointerType());
5967 S.Diag(Loc, S.getLangOptions().CPlusPlus
5968 ? diag::err_typecheck_pointer_arith_function_type
5969 : diag::ext_gnu_ptr_func_arith)
5970 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5971 << 0 /* one pointer, so only one type */
5972 << Pointer->getSourceRange();
5973}
5974
Richard Trieu993f3ab2011-09-12 18:08:02 +00005975/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005976///
5977/// \returns True if pointer has incomplete type
5978static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5979 Expr *Operand) {
5980 if ((Operand->getType()->isPointerType() &&
5981 !Operand->getType()->isDependentType()) ||
5982 Operand->getType()->isObjCObjectPointerType()) {
5983 QualType PointeeTy = Operand->getType()->getPointeeType();
5984 if (S.RequireCompleteType(
5985 Loc, PointeeTy,
5986 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5987 << PointeeTy << Operand->getSourceRange()))
5988 return true;
5989 }
5990 return false;
5991}
5992
Chandler Carruthc9332212011-06-27 08:02:19 +00005993/// \brief Check the validity of an arithmetic pointer operand.
5994///
5995/// If the operand has pointer type, this code will check for pointer types
5996/// which are invalid in arithmetic operations. These will be diagnosed
5997/// appropriately, including whether or not the use is supported as an
5998/// extension.
5999///
6000/// \returns True when the operand is valid to use (even if as an extension).
6001static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6002 Expr *Operand) {
6003 if (!Operand->getType()->isAnyPointerType()) return true;
6004
6005 QualType PointeeTy = Operand->getType()->getPointeeType();
6006 if (PointeeTy->isVoidType()) {
6007 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6008 return !S.getLangOptions().CPlusPlus;
6009 }
6010 if (PointeeTy->isFunctionType()) {
6011 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6012 return !S.getLangOptions().CPlusPlus;
6013 }
6014
Richard Trieuaba22802011-09-02 02:15:37 +00006015 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006016
6017 return true;
6018}
6019
6020/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6021/// operands.
6022///
6023/// This routine will diagnose any invalid arithmetic on pointer operands much
6024/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6025/// for emitting a single diagnostic even for operations where both LHS and RHS
6026/// are (potentially problematic) pointers.
6027///
6028/// \returns True when the operand is valid to use (even if as an extension).
6029static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006030 Expr *LHSExpr, Expr *RHSExpr) {
6031 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6032 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006033 if (!isLHSPointer && !isRHSPointer) return true;
6034
6035 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006036 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6037 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006038
6039 // Check for arithmetic on pointers to incomplete types.
6040 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6041 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6042 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006043 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6044 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6045 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006046
6047 return !S.getLangOptions().CPlusPlus;
6048 }
6049
6050 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6051 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6052 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006053 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6054 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6055 RHSExpr);
6056 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006057
6058 return !S.getLangOptions().CPlusPlus;
6059 }
6060
Richard Trieu4ae7e972011-09-06 21:13:51 +00006061 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6062 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006063
Chandler Carruthc9332212011-06-27 08:02:19 +00006064 return true;
6065}
6066
Richard Trieub10c6312011-09-01 22:53:23 +00006067/// \brief Check bad cases where we step over interface counts.
6068static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6069 SourceLocation OpLoc,
6070 Expr *Op) {
6071 assert(Op->getType()->isAnyPointerType());
6072 QualType PointeeTy = Op->getType()->getPointeeType();
6073 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6074 return true;
6075
6076 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6077 << PointeeTy << Op->getSourceRange();
6078 return false;
6079}
6080
Richard Trieu993f3ab2011-09-12 18:08:02 +00006081/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006082static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006083 Expr *LHSExpr, Expr *RHSExpr) {
6084 assert(LHSExpr->getType()->isAnyPointerType());
6085 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006086 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006087 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6088 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006089}
6090
Chris Lattnerfaa54172010-01-12 21:23:57 +00006091QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006092 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006093 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6094
Richard Trieu4ae7e972011-09-06 21:13:51 +00006095 if (LHS.get()->getType()->isVectorType() ||
6096 RHS.get()->getType()->isVectorType()) {
6097 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006098 if (CompLHSTy) *CompLHSTy = compType;
6099 return compType;
6100 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006101
Richard Trieu4ae7e972011-09-06 21:13:51 +00006102 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6103 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006104 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006105
Steve Naroffe4718892007-04-27 18:30:00 +00006106 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006107 if (LHS.get()->getType()->isArithmeticType() &&
6108 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006109 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006110 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006111 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006112
Eli Friedman8e122982008-05-18 18:08:51 +00006113 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006114 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006115 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006116 std::swap(PExp, IExp);
6117
Richard Trieub420bca2011-09-12 18:37:54 +00006118 if (!PExp->getType()->isAnyPointerType())
6119 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006120
Richard Trieub420bca2011-09-12 18:37:54 +00006121 if (!IExp->getType()->isIntegerType())
6122 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006123
Richard Trieub420bca2011-09-12 18:37:54 +00006124 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6125 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006126
Richard Trieub420bca2011-09-12 18:37:54 +00006127 // Diagnose bad cases where we step over interface counts.
6128 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6129 return QualType();
6130
6131 // Check array bounds for pointer arithemtic
6132 CheckArrayAccess(PExp, IExp);
6133
6134 if (CompLHSTy) {
6135 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6136 if (LHSTy.isNull()) {
6137 LHSTy = LHS.get()->getType();
6138 if (LHSTy->isPromotableIntegerType())
6139 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006140 }
Richard Trieub420bca2011-09-12 18:37:54 +00006141 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006142 }
6143
Richard Trieub420bca2011-09-12 18:37:54 +00006144 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006145}
6146
Chris Lattner2a3569b2008-04-07 05:30:13 +00006147// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006148QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006149 SourceLocation Loc,
6150 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006151 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6152
Richard Trieu4ae7e972011-09-06 21:13:51 +00006153 if (LHS.get()->getType()->isVectorType() ||
6154 RHS.get()->getType()->isVectorType()) {
6155 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006156 if (CompLHSTy) *CompLHSTy = compType;
6157 return compType;
6158 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006159
Richard Trieu4ae7e972011-09-06 21:13:51 +00006160 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6161 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006162 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006163
Chris Lattner4d62f422007-12-09 21:53:25 +00006164 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006165
Chris Lattner4d62f422007-12-09 21:53:25 +00006166 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006167 if (LHS.get()->getType()->isArithmeticType() &&
6168 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006169 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006170 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006171 }
Mike Stump11289f42009-09-09 15:08:12 +00006172
Chris Lattner4d62f422007-12-09 21:53:25 +00006173 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006174 if (LHS.get()->getType()->isAnyPointerType()) {
6175 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006176
Chris Lattner12bdebb2009-04-24 23:50:08 +00006177 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006178 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006179 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006180
Chris Lattner4d62f422007-12-09 21:53:25 +00006181 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006182 if (RHS.get()->getType()->isIntegerType()) {
6183 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006184 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006185
Richard Trieu4ae7e972011-09-06 21:13:51 +00006186 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006187 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6188 OK_Ordinary, IExpr->getExprLoc());
6189 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006190 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006191
Richard Trieu4ae7e972011-09-06 21:13:51 +00006192 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6193 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006194 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006195
Chris Lattner4d62f422007-12-09 21:53:25 +00006196 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006197 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006198 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006199 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006200
Eli Friedman168fe152009-05-16 13:54:38 +00006201 if (getLangOptions().CPlusPlus) {
6202 // Pointee types must be the same: C++ [expr.add]
6203 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006204 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006205 }
6206 } else {
6207 // Pointee types must be compatible C99 6.5.6p3
6208 if (!Context.typesAreCompatible(
6209 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6210 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006211 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006212 return QualType();
6213 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006214 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006215
Chandler Carruthc9332212011-06-27 08:02:19 +00006216 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006217 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006218 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006219
Richard Trieu4ae7e972011-09-06 21:13:51 +00006220 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006221 return Context.getPointerDiffType();
6222 }
6223 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006224
Richard Trieu4ae7e972011-09-06 21:13:51 +00006225 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006226}
6227
Douglas Gregor0bf31402010-10-08 23:50:27 +00006228static bool isScopedEnumerationType(QualType T) {
6229 if (const EnumType *ET = dyn_cast<EnumType>(T))
6230 return ET->getDecl()->isScoped();
6231 return false;
6232}
6233
Richard Trieue4a19fb2011-09-06 21:21:28 +00006234static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006235 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006236 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006237 llvm::APSInt Right;
6238 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006239 if (RHS.get()->isValueDependent() ||
6240 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006241 return;
6242
6243 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006244 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006245 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006246 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006247 return;
6248 }
6249 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006250 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006251 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006252 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006253 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006254 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006255 return;
6256 }
6257 if (Opc != BO_Shl)
6258 return;
6259
6260 // When left shifting an ICE which is signed, we can check for overflow which
6261 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6262 // integers have defined behavior modulo one more than the maximum value
6263 // representable in the result type, so never warn for those.
6264 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006265 if (LHS.get()->isValueDependent() ||
6266 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6267 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006268 return;
6269 llvm::APInt ResultBits =
6270 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6271 if (LeftBits.uge(ResultBits))
6272 return;
6273 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6274 Result = Result.shl(Right);
6275
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006276 // Print the bit representation of the signed integer as an unsigned
6277 // hexadecimal number.
6278 llvm::SmallString<40> HexResult;
6279 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6280
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006281 // If we are only missing a sign bit, this is less likely to result in actual
6282 // bugs -- if the result is cast back to an unsigned type, it will have the
6283 // expected value. Thus we place this behind a different warning that can be
6284 // turned off separately if needed.
6285 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006286 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006287 << HexResult.str() << LHSType
6288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006289 return;
6290 }
6291
6292 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006293 << HexResult.str() << Result.getMinSignedBits() << LHSType
6294 << Left.getBitWidth() << LHS.get()->getSourceRange()
6295 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006296}
6297
Chris Lattner2a3569b2008-04-07 05:30:13 +00006298// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006299QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006300 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006301 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006302 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6303
Chris Lattner5c11c412007-12-12 05:47:28 +00006304 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006305 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6306 !RHS.get()->getType()->hasIntegerRepresentation())
6307 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006308
Douglas Gregor0bf31402010-10-08 23:50:27 +00006309 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6310 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006311 if (isScopedEnumerationType(LHS.get()->getType()) ||
6312 isScopedEnumerationType(RHS.get()->getType())) {
6313 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006314 }
6315
Nate Begemane46ee9a2009-10-25 02:26:48 +00006316 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006317 if (LHS.get()->getType()->isVectorType() ||
6318 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006319 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006320
Chris Lattner5c11c412007-12-12 05:47:28 +00006321 // Shifts don't perform usual arithmetic conversions, they just do integer
6322 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006323
John McCall57cdd882010-12-16 19:28:59 +00006324 // For the LHS, do usual unary conversions, but then reset them away
6325 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006326 ExprResult OldLHS = LHS;
6327 LHS = UsualUnaryConversions(LHS.take());
6328 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006329 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006330 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006331 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006332
6333 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006334 RHS = UsualUnaryConversions(RHS.take());
6335 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006336 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006337
Ryan Flynnf53fab82009-08-07 16:20:20 +00006338 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006339 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006340
Chris Lattner5c11c412007-12-12 05:47:28 +00006341 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006342 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006343}
6344
Chandler Carruth17773fc2010-07-10 12:30:03 +00006345static bool IsWithinTemplateSpecialization(Decl *D) {
6346 if (DeclContext *DC = D->getDeclContext()) {
6347 if (isa<ClassTemplateSpecializationDecl>(DC))
6348 return true;
6349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6350 return FD->isFunctionTemplateSpecialization();
6351 }
6352 return false;
6353}
6354
Richard Trieueea56f72011-09-02 03:48:46 +00006355/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006356static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6357 ExprResult &RHS) {
6358 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6359 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006360
6361 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6362 if (!LHSEnumType)
6363 return;
6364 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6365 if (!RHSEnumType)
6366 return;
6367
6368 // Ignore anonymous enums.
6369 if (!LHSEnumType->getDecl()->getIdentifier())
6370 return;
6371 if (!RHSEnumType->getDecl()->getIdentifier())
6372 return;
6373
6374 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6375 return;
6376
6377 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6378 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006380}
6381
Richard Trieudd82a5c2011-09-02 02:55:45 +00006382/// \brief Diagnose bad pointer comparisons.
6383static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006384 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006385 bool IsError) {
6386 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006387 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006388 << LHS.get()->getType() << RHS.get()->getType()
6389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006390}
6391
6392/// \brief Returns false if the pointers are converted to a composite type,
6393/// true otherwise.
6394static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006395 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006396 // C++ [expr.rel]p2:
6397 // [...] Pointer conversions (4.10) and qualification
6398 // conversions (4.4) are performed on pointer operands (or on
6399 // a pointer operand and a null pointer constant) to bring
6400 // them to their composite pointer type. [...]
6401 //
6402 // C++ [expr.eq]p1 uses the same notion for (in)equality
6403 // comparisons of pointers.
6404
6405 // C++ [expr.eq]p2:
6406 // In addition, pointers to members can be compared, or a pointer to
6407 // member and a null pointer constant. Pointer to member conversions
6408 // (4.11) and qualification conversions (4.4) are performed to bring
6409 // them to a common type. If one operand is a null pointer constant,
6410 // the common type is the type of the other operand. Otherwise, the
6411 // common type is a pointer to member type similar (4.4) to the type
6412 // of one of the operands, with a cv-qualification signature (4.4)
6413 // that is the union of the cv-qualification signatures of the operand
6414 // types.
6415
Richard Trieu1762d7c2011-09-06 21:27:33 +00006416 QualType LHSType = LHS.get()->getType();
6417 QualType RHSType = RHS.get()->getType();
6418 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6419 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006420
6421 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006422 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006423 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006424 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006425 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006426 return true;
6427 }
6428
6429 if (NonStandardCompositeType)
6430 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006431 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6432 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006433
Richard Trieu1762d7c2011-09-06 21:27:33 +00006434 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6435 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006436 return false;
6437}
6438
6439static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006440 ExprResult &LHS,
6441 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006442 bool IsError) {
6443 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6444 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006445 << LHS.get()->getType() << RHS.get()->getType()
6446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006447}
6448
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006449// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006450QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006451 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006452 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006453 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6454
John McCalle3027922010-08-25 11:45:40 +00006455 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006456
Chris Lattner9a152e22009-12-05 05:40:13 +00006457 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006458 if (LHS.get()->getType()->isVectorType() ||
6459 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006460 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006461
Richard Trieub80728f2011-09-06 21:43:51 +00006462 QualType LHSType = LHS.get()->getType();
6463 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006464
Richard Trieub80728f2011-09-06 21:43:51 +00006465 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6466 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006467
Richard Trieub80728f2011-09-06 21:43:51 +00006468 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006469
Richard Trieub80728f2011-09-06 21:43:51 +00006470 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006471 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006472 !LHS.get()->getLocStart().isMacroID() &&
6473 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006474 // For non-floating point types, check for self-comparisons of the form
6475 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6476 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006477 //
6478 // NOTE: Don't warn about comparison expressions resulting from macro
6479 // expansion. Also don't warn about comparisons which are only self
6480 // comparisons within a template specialization. The warnings should catch
6481 // obvious cases in the definition of the template anyways. The idea is to
6482 // warn when the typed comparison operator will always evaluate to the same
6483 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006484 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006485 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006486 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006487 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006488 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006489 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006490 << (Opc == BO_EQ
6491 || Opc == BO_LE
6492 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006493 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006494 !DRL->getDecl()->getType()->isReferenceType() &&
6495 !DRR->getDecl()->getType()->isReferenceType()) {
6496 // what is it always going to eval to?
6497 char always_evals_to;
6498 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006499 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006500 always_evals_to = 0; // false
6501 break;
John McCalle3027922010-08-25 11:45:40 +00006502 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006503 always_evals_to = 1; // true
6504 break;
6505 default:
6506 // best we can say is 'a constant'
6507 always_evals_to = 2; // e.g. array1 <= array2
6508 break;
6509 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006510 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006511 << 1 // array
6512 << always_evals_to);
6513 }
6514 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006515 }
Mike Stump11289f42009-09-09 15:08:12 +00006516
Chris Lattner222b8bd2009-03-08 19:39:53 +00006517 if (isa<CastExpr>(LHSStripped))
6518 LHSStripped = LHSStripped->IgnoreParenCasts();
6519 if (isa<CastExpr>(RHSStripped))
6520 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006521
Chris Lattner222b8bd2009-03-08 19:39:53 +00006522 // Warn about comparisons against a string constant (unless the other
6523 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006524 Expr *literalString = 0;
6525 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006526 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006527 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006528 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006529 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006530 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006531 } else if ((isa<StringLiteral>(RHSStripped) ||
6532 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006533 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006534 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006535 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006536 literalStringStripped = RHSStripped;
6537 }
6538
6539 if (literalString) {
6540 std::string resultComparison;
6541 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006542 case BO_LT: resultComparison = ") < 0"; break;
6543 case BO_GT: resultComparison = ") > 0"; break;
6544 case BO_LE: resultComparison = ") <= 0"; break;
6545 case BO_GE: resultComparison = ") >= 0"; break;
6546 case BO_EQ: resultComparison = ") == 0"; break;
6547 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006548 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006549 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006550
Ted Kremenek3427fac2011-02-23 01:52:04 +00006551 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006552 PDiag(diag::warn_stringcompare)
6553 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006554 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006555 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006556 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006557
Douglas Gregorec170db2010-06-08 19:50:34 +00006558 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006559 if (LHS.get()->getType()->isArithmeticType() &&
6560 RHS.get()->getType()->isArithmeticType()) {
6561 UsualArithmeticConversions(LHS, RHS);
6562 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006563 return QualType();
6564 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006565 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006566 LHS = UsualUnaryConversions(LHS.take());
6567 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006568 return QualType();
6569
Richard Trieub80728f2011-09-06 21:43:51 +00006570 RHS = UsualUnaryConversions(RHS.take());
6571 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006572 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006573 }
6574
Richard Trieub80728f2011-09-06 21:43:51 +00006575 LHSType = LHS.get()->getType();
6576 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006577
Douglas Gregorca63811b2008-11-19 03:25:36 +00006578 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006579 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006580
Richard Trieuba63ce62011-09-09 01:45:06 +00006581 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006582 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006583 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006584 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006585 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006586 if (LHSType->hasFloatingRepresentation())
6587 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006588
Richard Trieub80728f2011-09-06 21:43:51 +00006589 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006590 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006591 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006592
Richard Trieub80728f2011-09-06 21:43:51 +00006593 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006594 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006595 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006596 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006597
Douglas Gregorf267edd2010-06-15 21:38:40 +00006598 // All of the following pointer-related warnings are GCC extensions, except
6599 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006600 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006601 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006602 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006603 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006604 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006605
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006606 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006607 if (LCanPointeeTy == RCanPointeeTy)
6608 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006609 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006610 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6611 // Valid unless comparison between non-null pointer and function pointer
6612 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006613 // In a SFINAE context, we treat this as a hard error to maintain
6614 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006615 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6616 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006617 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006618 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006619
6620 if (isSFINAEContext())
6621 return QualType();
6622
Richard Trieub80728f2011-09-06 21:43:51 +00006623 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006624 return ResultTy;
6625 }
6626 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006627
Richard Trieub80728f2011-09-06 21:43:51 +00006628 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006629 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006630 else
6631 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006632 }
Eli Friedman16c209612009-08-23 00:27:47 +00006633 // C99 6.5.9p2 and C99 6.5.8p2
6634 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6635 RCanPointeeTy.getUnqualifiedType())) {
6636 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006637 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006638 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006639 << LHSType << RHSType << LHS.get()->getSourceRange()
6640 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006641 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006642 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006643 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6644 // Valid unless comparison between non-null pointer and function pointer
6645 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006646 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006647 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006648 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006649 } else {
6650 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006651 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006652 }
John McCall7684dde2011-03-11 04:25:25 +00006653 if (LCanPointeeTy != RCanPointeeTy) {
6654 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006655 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006656 else
Richard Trieub80728f2011-09-06 21:43:51 +00006657 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006658 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006659 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006660 }
Mike Stump11289f42009-09-09 15:08:12 +00006661
Sebastian Redl576fd422009-05-10 18:38:11 +00006662 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006663 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006664 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006665 return ResultTy;
6666
Mike Stump11289f42009-09-09 15:08:12 +00006667 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006668 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006669 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006670 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006671 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006672 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6673 RHS = ImpCastExprToType(RHS.take(), LHSType,
6674 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006675 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006676 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006677 return ResultTy;
6678 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006679 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006680 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006681 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006682 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6683 LHS = ImpCastExprToType(LHS.take(), RHSType,
6684 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006685 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006686 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006687 return ResultTy;
6688 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006689
6690 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006691 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006692 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6693 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006694 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006695 else
6696 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006697 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006698
6699 // Handle scoped enumeration types specifically, since they don't promote
6700 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006701 if (LHS.get()->getType()->isEnumeralType() &&
6702 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6703 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006704 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006705 }
Mike Stump11289f42009-09-09 15:08:12 +00006706
Steve Naroff081c7422008-09-04 15:10:53 +00006707 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006708 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006709 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006710 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6711 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006712
Steve Naroff081c7422008-09-04 15:10:53 +00006713 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006714 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006715 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006716 << LHSType << RHSType << LHS.get()->getSourceRange()
6717 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006718 }
Richard Trieub80728f2011-09-06 21:43:51 +00006719 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006720 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006721 }
John Wiegley01296292011-04-08 18:41:53 +00006722
Steve Naroffe18f94c2008-09-28 01:11:11 +00006723 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006724 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006725 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6726 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006727 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006728 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006729 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006730 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006731 ->getPointeeType()->isVoidType())))
6732 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006733 << LHSType << RHSType << LHS.get()->getSourceRange()
6734 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006735 }
John McCall7684dde2011-03-11 04:25:25 +00006736 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006737 LHS = ImpCastExprToType(LHS.take(), RHSType,
6738 RHSType->isPointerType() ? CK_BitCast
6739 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006740 else
John McCall9320b872011-09-09 05:25:32 +00006741 RHS = ImpCastExprToType(RHS.take(), LHSType,
6742 LHSType->isPointerType() ? CK_BitCast
6743 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006744 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006745 }
Steve Naroff081c7422008-09-04 15:10:53 +00006746
Richard Trieub80728f2011-09-06 21:43:51 +00006747 if (LHSType->isObjCObjectPointerType() ||
6748 RHSType->isObjCObjectPointerType()) {
6749 const PointerType *LPT = LHSType->getAs<PointerType>();
6750 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006751 if (LPT || RPT) {
6752 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6753 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006754
Steve Naroff753567f2008-11-17 19:49:16 +00006755 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006756 !Context.typesAreCompatible(LHSType, RHSType)) {
6757 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006758 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006759 }
John McCall7684dde2011-03-11 04:25:25 +00006760 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006761 LHS = ImpCastExprToType(LHS.take(), RHSType,
6762 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006763 else
John McCall9320b872011-09-09 05:25:32 +00006764 RHS = ImpCastExprToType(RHS.take(), LHSType,
6765 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006766 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006767 }
Richard Trieub80728f2011-09-06 21:43:51 +00006768 if (LHSType->isObjCObjectPointerType() &&
6769 RHSType->isObjCObjectPointerType()) {
6770 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6771 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006772 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006773 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006774 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006775 else
Richard Trieub80728f2011-09-06 21:43:51 +00006776 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006777 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006778 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006779 }
Richard Trieub80728f2011-09-06 21:43:51 +00006780 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6781 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006782 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006783 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006784 if ((LHSIsNull && LHSType->isIntegerType()) ||
6785 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006786 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006787 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006788 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006789 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006790 else if (getLangOptions().CPlusPlus) {
6791 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6792 isError = true;
6793 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006794 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006795
Chris Lattnerd99bd522009-08-23 00:03:44 +00006796 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006797 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006798 << LHSType << RHSType << LHS.get()->getSourceRange()
6799 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006800 if (isError)
6801 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006802 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006803
Richard Trieub80728f2011-09-06 21:43:51 +00006804 if (LHSType->isIntegerType())
6805 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006806 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006807 else
Richard Trieub80728f2011-09-06 21:43:51 +00006808 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006809 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006810 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006811 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006812
Steve Naroff4b191572008-09-04 16:56:14 +00006813 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006814 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006815 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6816 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006817 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006818 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006819 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006820 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6821 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006822 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006823 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006824
Richard Trieub80728f2011-09-06 21:43:51 +00006825 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006826}
6827
Nate Begeman191a6b12008-07-14 18:02:46 +00006828/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006829/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006830/// like a scalar comparison, a vector comparison produces a vector of integer
6831/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006832QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006833 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006834 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006835 // Check to make sure we're operating on vectors of the same type and width,
6836 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006837 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006838 if (vType.isNull())
6839 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006840
Richard Trieubcce2f72011-09-07 01:19:57 +00006841 QualType LHSType = LHS.get()->getType();
6842 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006843
Anton Yartsev530deb92011-03-27 15:36:07 +00006844 // If AltiVec, the comparison results in a numeric type, i.e.
6845 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006846 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006847 return Context.getLogicalOperationType();
6848
Nate Begeman191a6b12008-07-14 18:02:46 +00006849 // For non-floating point types, check for self-comparisons of the form
6850 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6851 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006852 if (!LHSType->hasFloatingRepresentation()) {
6853 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6854 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006855 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006856 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006857 PDiag(diag::warn_comparison_always)
6858 << 0 // self-
6859 << 2 // "a constant"
6860 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006861 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006862
Nate Begeman191a6b12008-07-14 18:02:46 +00006863 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006864 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006865 assert (RHSType->hasFloatingRepresentation());
6866 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006867 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006868
Nate Begeman191a6b12008-07-14 18:02:46 +00006869 // Return the type for the comparison, which is the same as vector type for
6870 // integer vectors, or an integer type of identical size and number of
6871 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006872 if (LHSType->hasIntegerRepresentation())
6873 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006874
Richard Trieubcce2f72011-09-07 01:19:57 +00006875 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006876 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006877 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006878 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006879 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006880 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6881
Mike Stump4e1f26a2009-02-19 03:04:26 +00006882 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006883 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006884 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6885}
6886
Steve Naroff218bc2b2007-05-04 21:54:46 +00006887inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006888 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006889 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6890
Richard Trieubcce2f72011-09-07 01:19:57 +00006891 if (LHS.get()->getType()->isVectorType() ||
6892 RHS.get()->getType()->isVectorType()) {
6893 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6894 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006895 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006896
Richard Trieubcce2f72011-09-07 01:19:57 +00006897 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006898 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006899
Richard Trieubcce2f72011-09-07 01:19:57 +00006900 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6901 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006902 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006903 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006904 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006905 LHS = LHSResult.take();
6906 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006907
Richard Trieubcce2f72011-09-07 01:19:57 +00006908 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6909 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006910 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006911 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006912}
6913
Steve Naroff218bc2b2007-05-04 21:54:46 +00006914inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006915 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006916
6917 // Diagnose cases where the user write a logical and/or but probably meant a
6918 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6919 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006920 if (LHS.get()->getType()->isIntegerType() &&
6921 !LHS.get()->getType()->isBooleanType() &&
6922 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006923 // Don't warn in macros or template instantiations.
6924 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006925 // If the RHS can be constant folded, and if it constant folds to something
6926 // that isn't 0 or 1 (which indicate a potential logical operation that
6927 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006928 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006929 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006930 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6931 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006932 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6933 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006934 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006935 << (Opc == BO_LAnd ? "&&" : "||");
6936 // Suggest replacing the logical operator with the bitwise version
6937 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6938 << (Opc == BO_LAnd ? "&" : "|")
6939 << FixItHint::CreateReplacement(SourceRange(
6940 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6941 getLangOptions())),
6942 Opc == BO_LAnd ? "&" : "|");
6943 if (Opc == BO_LAnd)
6944 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6945 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6946 << FixItHint::CreateRemoval(
6947 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006948 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006949 0, getSourceManager(),
6950 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006951 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006952 }
Chris Lattner938533d2010-07-24 01:10:11 +00006953 }
Chris Lattner8406c512010-07-13 19:41:32 +00006954
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006955 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006956 LHS = UsualUnaryConversions(LHS.take());
6957 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006958 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006959
Richard Trieubcce2f72011-09-07 01:19:57 +00006960 RHS = UsualUnaryConversions(RHS.take());
6961 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006962 return QualType();
6963
Richard Trieubcce2f72011-09-07 01:19:57 +00006964 if (!LHS.get()->getType()->isScalarType() ||
6965 !RHS.get()->getType()->isScalarType())
6966 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006967
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006968 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006969 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006970
John McCall4a2429a2010-06-04 00:29:51 +00006971 // The following is safe because we only use this method for
6972 // non-overloadable operands.
6973
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006974 // C++ [expr.log.and]p1
6975 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006976 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006977 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6978 if (LHSRes.isInvalid())
6979 return InvalidOperands(Loc, LHS, RHS);
6980 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006981
Richard Trieubcce2f72011-09-07 01:19:57 +00006982 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6983 if (RHSRes.isInvalid())
6984 return InvalidOperands(Loc, LHS, RHS);
6985 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006986
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006987 // C++ [expr.log.and]p2
6988 // C++ [expr.log.or]p2
6989 // The result is a bool.
6990 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006991}
6992
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006993/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6994/// is a read-only property; return true if so. A readonly property expression
6995/// depends on various declarations and thus must be treated specially.
6996///
Mike Stump11289f42009-09-09 15:08:12 +00006997static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006998 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6999 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007000 if (PropExpr->isImplicitProperty()) return false;
7001
7002 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7003 QualType BaseType = PropExpr->isSuperReceiver() ?
7004 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007005 PropExpr->getBase()->getType();
7006
John McCallb7bd14f2010-12-02 01:19:52 +00007007 if (const ObjCObjectPointerType *OPT =
7008 BaseType->getAsObjCInterfacePointerType())
7009 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7010 if (S.isPropertyReadonly(PDecl, IFace))
7011 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007012 }
7013 return false;
7014}
7015
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007016static bool IsConstProperty(Expr *E, Sema &S) {
7017 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7018 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7019 if (PropExpr->isImplicitProperty()) return false;
7020
7021 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7022 QualType T = PDecl->getType();
7023 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007024 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007025 CanQualType CT = S.Context.getCanonicalType(T);
7026 return CT.isConstQualified();
7027 }
7028 return false;
7029}
7030
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007031static bool IsReadonlyMessage(Expr *E, Sema &S) {
7032 if (E->getStmtClass() != Expr::MemberExprClass)
7033 return false;
7034 const MemberExpr *ME = cast<MemberExpr>(E);
7035 NamedDecl *Member = ME->getMemberDecl();
7036 if (isa<FieldDecl>(Member)) {
7037 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7038 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7039 return false;
7040 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7041 }
7042 return false;
7043}
7044
Chris Lattner30bd3272008-11-18 01:22:49 +00007045/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7046/// emit an error and return true. If so, return false.
7047static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007048 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007049 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007050 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007051 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7052 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007053 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7054 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007055 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7056 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007057 if (IsLV == Expr::MLV_Valid)
7058 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007059
Chris Lattner30bd3272008-11-18 01:22:49 +00007060 unsigned Diag = 0;
7061 bool NeedType = false;
7062 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007063 case Expr::MLV_ConstQualified:
7064 Diag = diag::err_typecheck_assign_const;
7065
John McCalld4631322011-06-17 06:42:21 +00007066 // In ARC, use some specialized diagnostics for occasions where we
7067 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007068 if (S.getLangOptions().ObjCAutoRefCount) {
7069 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7070 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7071 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7072
John McCalld4631322011-06-17 06:42:21 +00007073 // Use the normal diagnostic if it's pseudo-__strong but the
7074 // user actually wrote 'const'.
7075 if (var->isARCPseudoStrong() &&
7076 (!var->getTypeSourceInfo() ||
7077 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7078 // There are two pseudo-strong cases:
7079 // - self
John McCall31168b02011-06-15 23:02:42 +00007080 ObjCMethodDecl *method = S.getCurMethodDecl();
7081 if (method && var == method->getSelfDecl())
7082 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007083
7084 // - fast enumeration variables
7085 else
John McCall31168b02011-06-15 23:02:42 +00007086 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007087
John McCall31168b02011-06-15 23:02:42 +00007088 SourceRange Assign;
7089 if (Loc != OrigLoc)
7090 Assign = SourceRange(OrigLoc, OrigLoc);
7091 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7092 // We need to preserve the AST regardless, so migration tool
7093 // can do its job.
7094 return false;
7095 }
7096 }
7097 }
7098
7099 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007100 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007101 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7102 NeedType = true;
7103 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007104 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007105 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7106 NeedType = true;
7107 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007108 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007109 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7110 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007111 case Expr::MLV_Valid:
7112 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007113 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007114 case Expr::MLV_MemberFunction:
7115 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007116 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7117 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007118 case Expr::MLV_IncompleteType:
7119 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007120 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007121 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007122 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007123 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007124 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7125 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007126 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007127 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7128 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007129 case Expr::MLV_ReadonlyProperty:
7130 Diag = diag::error_readonly_property_assignment;
7131 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007132 case Expr::MLV_NoSetterProperty:
7133 Diag = diag::error_nosetter_property_assignment;
7134 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007135 case Expr::MLV_InvalidMessageExpression:
7136 Diag = diag::error_readonly_message_assignment;
7137 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007138 case Expr::MLV_SubObjCPropertySetting:
7139 Diag = diag::error_no_subobject_property_setting;
7140 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007141 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007142
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007143 SourceRange Assign;
7144 if (Loc != OrigLoc)
7145 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007146 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007147 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007148 else
Mike Stump11289f42009-09-09 15:08:12 +00007149 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007150 return true;
7151}
7152
7153
7154
7155// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007156QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007157 SourceLocation Loc,
7158 QualType CompoundType) {
7159 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007160 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007161 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007162
Richard Trieuda4f43a62011-09-07 01:33:52 +00007163 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007164 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7165 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007166 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007167 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007168 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007169 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007170 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7171 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007172 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7173 if (LHSResult.isInvalid())
7174 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007175 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007176 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007177 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007178 if (RHS.isInvalid())
7179 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007180 // Special case of NSObject attributes on c-style pointer types.
7181 if (ConvTy == IncompatiblePointer &&
7182 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007183 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007184 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007185 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007186 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007187
John McCall7decc9e2010-11-18 06:31:45 +00007188 if (ConvTy == Compatible &&
7189 getLangOptions().ObjCNonFragileABI &&
7190 LHSType->isObjCObjectType())
7191 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7192 << LHSType;
7193
Chris Lattnerea714382008-08-21 18:04:13 +00007194 // If the RHS is a unary plus or minus, check to see if they = and + are
7195 // right next to each other. If so, the user may have typo'd "x =+ 4"
7196 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007197 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007198 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7199 RHSCheck = ICE->getSubExpr();
7200 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007201 if ((UO->getOpcode() == UO_Plus ||
7202 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007203 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007204 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007205 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007206 // And there is a space or other character before the subexpr of the
7207 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007208 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007209 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007210 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007211 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007212 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007213 }
Chris Lattnerea714382008-08-21 18:04:13 +00007214 }
John McCall31168b02011-06-15 23:02:42 +00007215
7216 if (ConvTy == Compatible) {
7217 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007218 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007219 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007220 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007221 }
Chris Lattnerea714382008-08-21 18:04:13 +00007222 } else {
7223 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007224 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007225 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007226
Chris Lattner326f7572008-11-18 01:30:42 +00007227 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007228 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007229 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007230
Richard Trieuda4f43a62011-09-07 01:33:52 +00007231 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007232
Steve Naroff98cf3e92007-06-06 18:38:38 +00007233 // C99 6.5.16p3: The type of an assignment expression is the type of the
7234 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007235 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007236 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7237 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007238 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007239 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007240 return (getLangOptions().CPlusPlus
7241 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007242}
7243
Chris Lattner326f7572008-11-18 01:30:42 +00007244// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007245static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007246 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007247 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007248
John McCall3aef3d82011-04-10 19:13:55 +00007249 LHS = S.CheckPlaceholderExpr(LHS.take());
7250 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007251 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007252 return QualType();
7253
John McCall73d36182010-10-12 07:14:40 +00007254 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7255 // operands, but not unary promotions.
7256 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007257
John McCall34376a62010-12-04 03:47:34 +00007258 // So we treat the LHS as a ignored value, and in C++ we allow the
7259 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007260 LHS = S.IgnoredValueConversions(LHS.take());
7261 if (LHS.isInvalid())
7262 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007263
7264 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007265 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7266 if (RHS.isInvalid())
7267 return QualType();
7268 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007269 S.RequireCompleteType(Loc, RHS.get()->getType(),
7270 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007271 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007272
John Wiegley01296292011-04-08 18:41:53 +00007273 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007274}
7275
Steve Naroff7a5af782007-07-13 16:58:59 +00007276/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7277/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007278static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7279 ExprValueKind &VK,
7280 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007281 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007282 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007283 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007284
Chris Lattner6b0cf142008-11-21 07:05:48 +00007285 QualType ResType = Op->getType();
7286 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007287
John McCall4bc41ae2010-11-18 19:01:18 +00007288 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007289 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007290 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007291 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007292 return QualType();
7293 }
7294 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007295 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007296 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007297 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007298 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007299 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007300 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007301 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007302
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007303 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007304 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007305 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007306 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007307 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007308 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007309 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007310 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007311 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007312 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007313 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007314 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007315 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7316 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007317 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007318 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007319 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007320 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007321 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007322 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007323 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007324 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007325 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007326 // In C++, a prefix increment is the same type as the operand. Otherwise
7327 // (in C or with postfix), the increment is the unqualified type of the
7328 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007329 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007330 VK = VK_LValue;
7331 return ResType;
7332 } else {
7333 VK = VK_RValue;
7334 return ResType.getUnqualifiedType();
7335 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007336}
7337
John Wiegley01296292011-04-08 18:41:53 +00007338ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007339 assert(E->getValueKind() == VK_LValue &&
7340 E->getObjectKind() == OK_ObjCProperty);
7341 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7342
Douglas Gregor33823722011-06-11 01:09:30 +00007343 QualType T = E->getType();
7344 QualType ReceiverType;
7345 if (PRE->isObjectReceiver())
7346 ReceiverType = PRE->getBase()->getType();
7347 else if (PRE->isSuperReceiver())
7348 ReceiverType = PRE->getSuperReceiverType();
7349 else
7350 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7351
John McCall34376a62010-12-04 03:47:34 +00007352 ExprValueKind VK = VK_RValue;
7353 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007354 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007355 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007356 T = getMessageSendResultType(ReceiverType, GetterMethod,
7357 PRE->isClassReceiver(),
7358 PRE->isSuperReceiver());
7359 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007360 }
7361 else {
7362 Diag(PRE->getLocation(), diag::err_getter_not_found)
7363 << PRE->getBase()->getType();
7364 }
John McCall34376a62010-12-04 03:47:34 +00007365 }
Douglas Gregor33823722011-06-11 01:09:30 +00007366
7367 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007368 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007369
7370 ExprResult Result = MaybeBindToTemporary(E);
7371 if (!Result.isInvalid())
7372 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007373
7374 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007375}
7376
Richard Trieucfc491d2011-08-02 04:35:43 +00007377void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7378 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007379 assert(LHS.get()->getValueKind() == VK_LValue &&
7380 LHS.get()->getObjectKind() == OK_ObjCProperty);
7381 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007382
John McCall31168b02011-06-15 23:02:42 +00007383 bool Consumed = false;
7384
John Wiegley01296292011-04-08 18:41:53 +00007385 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007386 // If using property-dot syntax notation for assignment, and there is a
7387 // setter, RHS expression is being passed to the setter argument. So,
7388 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007389 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007390 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7391 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007392 Consumed = (getLangOptions().ObjCAutoRefCount &&
7393 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007394
7395 // Otherwise, if the getter returns an l-value, just call that.
7396 } else {
John Wiegley01296292011-04-08 18:41:53 +00007397 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007398 ExprValueKind VK = Expr::getValueKindForType(Result);
7399 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007400 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7401 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007402 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007403 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007404 }
John McCall31168b02011-06-15 23:02:42 +00007405 } else if (getLangOptions().ObjCAutoRefCount) {
7406 const ObjCMethodDecl *setter
7407 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7408 if (setter) {
7409 ObjCMethodDecl::param_iterator P = setter->param_begin();
7410 LHSTy = (*P)->getType();
7411 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7412 }
John McCall34376a62010-12-04 03:47:34 +00007413 }
7414
John McCall31168b02011-06-15 23:02:42 +00007415 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7416 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007417 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007418 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007419 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007420 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007421 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007422 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7423 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7424 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007425 }
7426}
7427
7428
Anders Carlsson806700f2008-02-01 07:15:58 +00007429/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007430/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007431/// where the declaration is needed for type checking. We only need to
7432/// handle cases when the expression references a function designator
7433/// or is an lvalue. Here are some examples:
7434/// - &(x) => x
7435/// - &*****f => f for f a function designator.
7436/// - &s.xx => s
7437/// - &s.zz[1].yy -> s, if zz is an array
7438/// - *(x + 1) -> x, if x is an array
7439/// - &"123"[2] -> 0
7440/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007441static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007442 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007443 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007444 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007445 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007446 // If this is an arrow operator, the address is an offset from
7447 // the base's value, so the object the base refers to is
7448 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007449 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007450 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007451 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007452 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007453 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007454 // FIXME: This code shouldn't be necessary! We should catch the implicit
7455 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007456 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7457 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7458 if (ICE->getSubExpr()->getType()->isArrayType())
7459 return getPrimaryDecl(ICE->getSubExpr());
7460 }
7461 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007462 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007463 case Stmt::UnaryOperatorClass: {
7464 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007465
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007466 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007467 case UO_Real:
7468 case UO_Imag:
7469 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007470 return getPrimaryDecl(UO->getSubExpr());
7471 default:
7472 return 0;
7473 }
7474 }
Steve Naroff47500512007-04-19 23:00:49 +00007475 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007476 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007477 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007478 // If the result of an implicit cast is an l-value, we care about
7479 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007480 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007481 default:
7482 return 0;
7483 }
7484}
7485
Richard Trieu5f376f62011-09-07 21:46:33 +00007486namespace {
7487 enum {
7488 AO_Bit_Field = 0,
7489 AO_Vector_Element = 1,
7490 AO_Property_Expansion = 2,
7491 AO_Register_Variable = 3,
7492 AO_No_Error = 4
7493 };
7494}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007495/// \brief Diagnose invalid operand for address of operations.
7496///
7497/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007498static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7499 Expr *E, unsigned Type) {
7500 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7501}
7502
Steve Naroff47500512007-04-19 23:00:49 +00007503/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007504/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007505/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007506/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007507/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007508/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007509/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007510static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7511 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007512 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007513 return S.Context.DependentTy;
7514 if (OrigOp->getType() == S.Context.OverloadTy)
7515 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007516 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7517 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007518 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7519 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7520 << OrigOp->getSourceRange();
7521 return QualType();
7522 }
John McCall8d08b9b2010-08-27 09:08:28 +00007523
John McCall2979fe02011-04-12 00:42:48 +00007524 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007525
John McCall8d08b9b2010-08-27 09:08:28 +00007526 // Make sure to ignore parentheses in subsequent checks
7527 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007528
John McCall4bc41ae2010-11-18 19:01:18 +00007529 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007530 // Implement C99-only parts of addressof rules.
7531 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007532 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007533 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7534 // (assuming the deref expression is valid).
7535 return uOp->getSubExpr()->getType();
7536 }
7537 // Technically, there should be a check for array subscript
7538 // expressions here, but the result of one is always an lvalue anyway.
7539 }
John McCallf3a88602011-02-03 08:15:49 +00007540 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007541 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007542 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007543
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007544 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007545 bool sfinae = S.isSFINAEContext();
7546 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7547 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007548 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007549 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007550 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007551 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007552 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007553 } else if (lval == Expr::LV_MemberFunction) {
7554 // If it's an instance method, make a member pointer.
7555 // The expression must have exactly the form &A::foo.
7556
7557 // If the underlying expression isn't a decl ref, give up.
7558 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007559 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007560 << OrigOp->getSourceRange();
7561 return QualType();
7562 }
7563 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7564 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7565
7566 // The id-expression was parenthesized.
7567 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007568 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007569 << OrigOp->getSourceRange();
7570
7571 // The method was named without a qualifier.
7572 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007573 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007574 << op->getSourceRange();
7575 }
7576
John McCall4bc41ae2010-11-18 19:01:18 +00007577 return S.Context.getMemberPointerType(op->getType(),
7578 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007579 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007580 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007581 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007582 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007583 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007584 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007585 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007586 return QualType();
7587 }
John McCall086a4642010-11-24 05:12:34 +00007588 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007589 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007590 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007591 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007592 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007593 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007594 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007595 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007596 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007597 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007598 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007599 // with the register storage-class specifier.
7600 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007601 // in C++ it is not error to take address of a register
7602 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007603 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007604 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007605 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007606 }
John McCalld14a8642009-11-21 08:51:07 +00007607 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007608 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007609 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007610 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007611 // Could be a pointer to member, though, if there is an explicit
7612 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007613 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007614 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007615 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007616 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007617 S.Diag(OpLoc,
7618 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007619 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007620 return QualType();
7621 }
Mike Stump11289f42009-09-09 15:08:12 +00007622
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007623 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7624 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007625 return S.Context.getMemberPointerType(op->getType(),
7626 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007627 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007628 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007629 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007630 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007631 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007632
Richard Trieu5f376f62011-09-07 21:46:33 +00007633 if (AddressOfError != AO_No_Error) {
7634 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7635 return QualType();
7636 }
7637
Eli Friedmance7f9002009-05-16 23:27:50 +00007638 if (lval == Expr::LV_IncompleteVoidType) {
7639 // Taking the address of a void variable is technically illegal, but we
7640 // allow it in cases which are otherwise valid.
7641 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007642 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007643 }
7644
Steve Naroff47500512007-04-19 23:00:49 +00007645 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007646 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007647 return S.Context.getObjCObjectPointerType(op->getType());
7648 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007649}
7650
Chris Lattner9156f1b2010-07-05 19:17:26 +00007651/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007652static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7653 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007654 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007655 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007656
John Wiegley01296292011-04-08 18:41:53 +00007657 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7658 if (ConvResult.isInvalid())
7659 return QualType();
7660 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007661 QualType OpTy = Op->getType();
7662 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007663
7664 if (isa<CXXReinterpretCastExpr>(Op)) {
7665 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7666 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7667 Op->getSourceRange());
7668 }
7669
Chris Lattner9156f1b2010-07-05 19:17:26 +00007670 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7671 // is an incomplete type or void. It would be possible to warn about
7672 // dereferencing a void pointer, but it's completely well-defined, and such a
7673 // warning is unlikely to catch any mistakes.
7674 if (const PointerType *PT = OpTy->getAs<PointerType>())
7675 Result = PT->getPointeeType();
7676 else if (const ObjCObjectPointerType *OPT =
7677 OpTy->getAs<ObjCObjectPointerType>())
7678 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007679 else {
John McCall3aef3d82011-04-10 19:13:55 +00007680 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007681 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007682 if (PR.take() != Op)
7683 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007684 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007685
Chris Lattner9156f1b2010-07-05 19:17:26 +00007686 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007687 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007688 << OpTy << Op->getSourceRange();
7689 return QualType();
7690 }
John McCall4bc41ae2010-11-18 19:01:18 +00007691
7692 // Dereferences are usually l-values...
7693 VK = VK_LValue;
7694
7695 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007696 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007697 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007698
7699 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007700}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007701
John McCalle3027922010-08-25 11:45:40 +00007702static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007703 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007704 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007705 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007706 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007707 case tok::periodstar: Opc = BO_PtrMemD; break;
7708 case tok::arrowstar: Opc = BO_PtrMemI; break;
7709 case tok::star: Opc = BO_Mul; break;
7710 case tok::slash: Opc = BO_Div; break;
7711 case tok::percent: Opc = BO_Rem; break;
7712 case tok::plus: Opc = BO_Add; break;
7713 case tok::minus: Opc = BO_Sub; break;
7714 case tok::lessless: Opc = BO_Shl; break;
7715 case tok::greatergreater: Opc = BO_Shr; break;
7716 case tok::lessequal: Opc = BO_LE; break;
7717 case tok::less: Opc = BO_LT; break;
7718 case tok::greaterequal: Opc = BO_GE; break;
7719 case tok::greater: Opc = BO_GT; break;
7720 case tok::exclaimequal: Opc = BO_NE; break;
7721 case tok::equalequal: Opc = BO_EQ; break;
7722 case tok::amp: Opc = BO_And; break;
7723 case tok::caret: Opc = BO_Xor; break;
7724 case tok::pipe: Opc = BO_Or; break;
7725 case tok::ampamp: Opc = BO_LAnd; break;
7726 case tok::pipepipe: Opc = BO_LOr; break;
7727 case tok::equal: Opc = BO_Assign; break;
7728 case tok::starequal: Opc = BO_MulAssign; break;
7729 case tok::slashequal: Opc = BO_DivAssign; break;
7730 case tok::percentequal: Opc = BO_RemAssign; break;
7731 case tok::plusequal: Opc = BO_AddAssign; break;
7732 case tok::minusequal: Opc = BO_SubAssign; break;
7733 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7734 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7735 case tok::ampequal: Opc = BO_AndAssign; break;
7736 case tok::caretequal: Opc = BO_XorAssign; break;
7737 case tok::pipeequal: Opc = BO_OrAssign; break;
7738 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007739 }
7740 return Opc;
7741}
7742
John McCalle3027922010-08-25 11:45:40 +00007743static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007744 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007745 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007746 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007747 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007748 case tok::plusplus: Opc = UO_PreInc; break;
7749 case tok::minusminus: Opc = UO_PreDec; break;
7750 case tok::amp: Opc = UO_AddrOf; break;
7751 case tok::star: Opc = UO_Deref; break;
7752 case tok::plus: Opc = UO_Plus; break;
7753 case tok::minus: Opc = UO_Minus; break;
7754 case tok::tilde: Opc = UO_Not; break;
7755 case tok::exclaim: Opc = UO_LNot; break;
7756 case tok::kw___real: Opc = UO_Real; break;
7757 case tok::kw___imag: Opc = UO_Imag; break;
7758 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007759 }
7760 return Opc;
7761}
7762
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007763/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7764/// This warning is only emitted for builtin assignment operations. It is also
7765/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007766static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007767 SourceLocation OpLoc) {
7768 if (!S.ActiveTemplateInstantiations.empty())
7769 return;
7770 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7771 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007772 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7773 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7774 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7775 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7776 if (!LHSDeclRef || !RHSDeclRef ||
7777 LHSDeclRef->getLocation().isMacroID() ||
7778 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007779 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007780 const ValueDecl *LHSDecl =
7781 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7782 const ValueDecl *RHSDecl =
7783 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7784 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007785 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007786 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007787 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007788 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007789 if (RefTy->getPointeeType().isVolatileQualified())
7790 return;
7791
7792 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007793 << LHSDeclRef->getType()
7794 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007795}
7796
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007797/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7798/// operator @p Opc at location @c TokLoc. This routine only supports
7799/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007800ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007801 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007802 Expr *LHSExpr, Expr *RHSExpr) {
7803 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007804 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007805 // The following two variables are used for compound assignment operators
7806 QualType CompLHSTy; // Type of LHS after promotions for computation
7807 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007808 ExprValueKind VK = VK_RValue;
7809 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007810
Douglas Gregor1beec452011-03-12 01:48:56 +00007811 // Check if a 'foo<int>' involved in a binary op, identifies a single
7812 // function unambiguously (i.e. an lvalue ala 13.4)
7813 // But since an assignment can trigger target based overload, exclude it in
7814 // our blind search. i.e:
7815 // template<class T> void f(); template<class T, class U> void f(U);
7816 // f<int> == 0; // resolve f<int> blindly
7817 // void (*p)(int); p = f<int>; // resolve f<int> using target
7818 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007819 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007820 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007821 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007822
Richard Trieu4a287fb2011-09-07 01:49:20 +00007823 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007824 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007825 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007826 }
7827
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007828 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007829 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007830 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007831 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007832 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7833 VK = LHS.get()->getValueKind();
7834 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007835 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007836 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007837 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007838 break;
John McCalle3027922010-08-25 11:45:40 +00007839 case BO_PtrMemD:
7840 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007841 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007842 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007843 break;
John McCalle3027922010-08-25 11:45:40 +00007844 case BO_Mul:
7845 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007846 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007847 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007848 break;
John McCalle3027922010-08-25 11:45:40 +00007849 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007850 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007851 break;
John McCalle3027922010-08-25 11:45:40 +00007852 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007853 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007854 break;
John McCalle3027922010-08-25 11:45:40 +00007855 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007856 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007857 break;
John McCalle3027922010-08-25 11:45:40 +00007858 case BO_Shl:
7859 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007860 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007861 break;
John McCalle3027922010-08-25 11:45:40 +00007862 case BO_LE:
7863 case BO_LT:
7864 case BO_GE:
7865 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007866 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007867 break;
John McCalle3027922010-08-25 11:45:40 +00007868 case BO_EQ:
7869 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007870 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007871 break;
John McCalle3027922010-08-25 11:45:40 +00007872 case BO_And:
7873 case BO_Xor:
7874 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007875 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007876 break;
John McCalle3027922010-08-25 11:45:40 +00007877 case BO_LAnd:
7878 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007879 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007880 break;
John McCalle3027922010-08-25 11:45:40 +00007881 case BO_MulAssign:
7882 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007883 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007884 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007885 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007886 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7887 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007888 break;
John McCalle3027922010-08-25 11:45:40 +00007889 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007891 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007892 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7893 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007894 break;
John McCalle3027922010-08-25 11:45:40 +00007895 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007896 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7897 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_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007901 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007904 break;
John McCalle3027922010-08-25 11:45:40 +00007905 case BO_ShlAssign:
7906 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007907 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007908 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007909 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7910 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007911 break;
John McCalle3027922010-08-25 11:45:40 +00007912 case BO_AndAssign:
7913 case BO_XorAssign:
7914 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007915 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007916 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007917 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7918 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007919 break;
John McCalle3027922010-08-25 11:45:40 +00007920 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007921 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7922 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7923 VK = RHS.get()->getValueKind();
7924 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007925 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007926 break;
7927 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007928 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007929 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007930
7931 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 CheckArrayAccess(LHS.get());
7933 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007934
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007935 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007936 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007937 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007938 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007939 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007940 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007941 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007942 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007943 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007944 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007945 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007946}
7947
Sebastian Redl44615072009-10-27 12:10:02 +00007948/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7949/// operators are mixed in a way that suggests that the programmer forgot that
7950/// comparison operators have higher precedence. The most typical example of
7951/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007952static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007953 SourceLocation OpLoc, Expr *LHSExpr,
7954 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007955 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007956 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7957 RHSopc = static_cast<BinOp::Opcode>(-1);
7958 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7959 LHSopc = BO->getOpcode();
7960 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7961 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007962
7963 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007964 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007965 return;
7966
7967 // Bitwise operations are sometimes used as eager logical ops.
7968 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007969 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7970 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007971 return;
7972
Richard Trieu4a287fb2011-09-07 01:49:20 +00007973 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7974 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007975 if (!isLeftComp && !isRightComp) return;
7976
Richard Trieu4a287fb2011-09-07 01:49:20 +00007977 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7978 OpLoc)
7979 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7980 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7981 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007982 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007983 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7984 RHSExpr->getLocEnd())
7985 : SourceRange(LHSExpr->getLocStart(),
7986 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007987
7988 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7989 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7990 SuggestParentheses(Self, OpLoc,
7991 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007992 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007993 SuggestParentheses(Self, OpLoc,
7994 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7995 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007996}
7997
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007998/// \brief It accepts a '&' expr that is inside a '|' one.
7999/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8000/// in parentheses.
8001static void
8002EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8003 BinaryOperator *Bop) {
8004 assert(Bop->getOpcode() == BO_And);
8005 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8006 << Bop->getSourceRange() << OpLoc;
8007 SuggestParentheses(Self, Bop->getOperatorLoc(),
8008 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8009 Bop->getSourceRange());
8010}
8011
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008012/// \brief It accepts a '&&' expr that is inside a '||' one.
8013/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8014/// in parentheses.
8015static void
8016EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008017 BinaryOperator *Bop) {
8018 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008019 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8020 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008021 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008022 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008023 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008024}
8025
8026/// \brief Returns true if the given expression can be evaluated as a constant
8027/// 'true'.
8028static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8029 bool Res;
8030 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8031}
8032
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008033/// \brief Returns true if the given expression can be evaluated as a constant
8034/// 'false'.
8035static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8036 bool Res;
8037 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8038}
8039
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008040/// \brief Look for '&&' in the left hand of a '||' expr.
8041static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008042 Expr *LHSExpr, Expr *RHSExpr) {
8043 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008044 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008045 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008046 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008047 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008048 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8049 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8050 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8051 } else if (Bop->getOpcode() == BO_LOr) {
8052 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8053 // If it's "a || b && 1 || c" we didn't warn earlier for
8054 // "a || b && 1", but warn now.
8055 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8056 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8057 }
8058 }
8059 }
8060}
8061
8062/// \brief Look for '&&' in the right hand of a '||' expr.
8063static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008064 Expr *LHSExpr, Expr *RHSExpr) {
8065 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008066 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008067 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008068 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008069 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008070 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8071 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8072 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008073 }
8074 }
8075}
8076
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008077/// \brief Look for '&' in the left or right hand of a '|' expr.
8078static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8079 Expr *OrArg) {
8080 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8081 if (Bop->getOpcode() == BO_And)
8082 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8083 }
8084}
8085
Sebastian Redl43028242009-10-26 15:24:15 +00008086/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008087/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008088static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008089 SourceLocation OpLoc, Expr *LHSExpr,
8090 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008091 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008092 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008093 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008094
8095 // Diagnose "arg1 & arg2 | arg3"
8096 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008097 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8098 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008099 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008100
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008101 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8102 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008103 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008104 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8105 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008106 }
Sebastian Redl43028242009-10-26 15:24:15 +00008107}
8108
Steve Naroff218bc2b2007-05-04 21:54:46 +00008109// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008110ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008111 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008112 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008113 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008114 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8115 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008116
Sebastian Redl43028242009-10-26 15:24:15 +00008117 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008118 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008119
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008120 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008121}
8122
John McCalldadc5752010-08-24 06:29:42 +00008123ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008124 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008125 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008126 if (getLangOptions().CPlusPlus) {
8127 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008128
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008129 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008130 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008131 } else if (Opc == BO_Assign &&
8132 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008133 UseBuiltinOperator = true;
8134 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008135 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8136 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008137 }
8138
8139 if (!UseBuiltinOperator) {
8140 // Find all of the overloaded operators visible from this
8141 // point. We perform both an operator-name lookup from the local
8142 // scope and an argument-dependent lookup based on the types of
8143 // the arguments.
8144 UnresolvedSet<16> Functions;
8145 OverloadedOperatorKind OverOp
8146 = BinaryOperator::getOverloadedOperator(Opc);
8147 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008148 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8149 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008150
8151 // Build the (potentially-overloaded, potentially-dependent)
8152 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008153 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008154 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008155 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008156
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008157 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008158 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008159}
8160
John McCalldadc5752010-08-24 06:29:42 +00008161ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008162 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008163 Expr *InputExpr) {
8164 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008165 ExprValueKind VK = VK_RValue;
8166 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008167 QualType resultType;
8168 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008169 case UO_PreInc:
8170 case UO_PreDec:
8171 case UO_PostInc:
8172 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008173 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008174 Opc == UO_PreInc ||
8175 Opc == UO_PostInc,
8176 Opc == UO_PreInc ||
8177 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008178 break;
John McCalle3027922010-08-25 11:45:40 +00008179 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008180 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008181 break;
John McCall31996342011-04-07 08:22:57 +00008182 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008183 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008184 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008185 Input = move(resolved);
8186 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8187 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008188 break;
John McCall31996342011-04-07 08:22:57 +00008189 }
John McCalle3027922010-08-25 11:45:40 +00008190 case UO_Plus:
8191 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008192 Input = UsualUnaryConversions(Input.take());
8193 if (Input.isInvalid()) return ExprError();
8194 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008195 if (resultType->isDependentType())
8196 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008197 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8198 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008199 break;
8200 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8201 resultType->isEnumeralType())
8202 break;
8203 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008204 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008205 resultType->isPointerType())
8206 break;
John McCall36226622010-10-12 02:09:17 +00008207 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008208 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008209 if (Input.isInvalid()) return ExprError();
8210 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008211 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008212
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008213 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008214 << resultType << Input.get()->getSourceRange());
8215
John McCalle3027922010-08-25 11:45:40 +00008216 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008217 Input = UsualUnaryConversions(Input.take());
8218 if (Input.isInvalid()) return ExprError();
8219 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008220 if (resultType->isDependentType())
8221 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008222 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8223 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8224 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008225 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008226 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008227 else if (resultType->hasIntegerRepresentation())
8228 break;
8229 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008230 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008231 if (Input.isInvalid()) return ExprError();
8232 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008233 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008234 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008235 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008236 }
Steve Naroff35d85152007-05-07 00:24:15 +00008237 break;
John Wiegley01296292011-04-08 18:41:53 +00008238
John McCalle3027922010-08-25 11:45:40 +00008239 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008240 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008241 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8242 if (Input.isInvalid()) return ExprError();
8243 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008244 if (resultType->isDependentType())
8245 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008246 if (resultType->isScalarType()) {
8247 // C99 6.5.3.3p1: ok, fallthrough;
8248 if (Context.getLangOptions().CPlusPlus) {
8249 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8250 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008251 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8252 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008253 }
John McCall36226622010-10-12 02:09:17 +00008254 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008255 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008256 if (Input.isInvalid()) return ExprError();
8257 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008258 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008259 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008260 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008261 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008262
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008263 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008264 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008265 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008266 break;
John McCalle3027922010-08-25 11:45:40 +00008267 case UO_Real:
8268 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008269 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008270 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008271 if (Input.isInvalid()) return ExprError();
8272 if (Input.get()->getValueKind() != VK_RValue &&
8273 Input.get()->getObjectKind() == OK_Ordinary)
8274 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008275 break;
John McCalle3027922010-08-25 11:45:40 +00008276 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008277 resultType = Input.get()->getType();
8278 VK = Input.get()->getValueKind();
8279 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008280 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008281 }
John Wiegley01296292011-04-08 18:41:53 +00008282 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008283 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008284
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008285 // Check for array bounds violations in the operand of the UnaryOperator,
8286 // except for the '*' and '&' operators that have to be handled specially
8287 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8288 // that are explicitly defined as valid by the standard).
8289 if (Opc != UO_AddrOf && Opc != UO_Deref)
8290 CheckArrayAccess(Input.get());
8291
John Wiegley01296292011-04-08 18:41:53 +00008292 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008293 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008294}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008295
John McCalldadc5752010-08-24 06:29:42 +00008296ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008297 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008298 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008299 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008300 // Find all of the overloaded operators visible from this
8301 // point. We perform both an operator-name lookup from the local
8302 // scope and an argument-dependent lookup based on the types of
8303 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008304 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008305 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008306 if (S && OverOp != OO_None)
8307 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8308 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008309
John McCallb268a282010-08-23 23:25:46 +00008310 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008311 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008312
John McCallb268a282010-08-23 23:25:46 +00008313 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008314}
8315
Douglas Gregor5287f092009-11-05 00:51:44 +00008316// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008317ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008318 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008319 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008320}
8321
Steve Naroff66356bd2007-09-16 14:56:35 +00008322/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008323ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008324 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008325 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008326 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008327 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008328 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008329}
8330
John McCall31168b02011-06-15 23:02:42 +00008331/// Given the last statement in a statement-expression, check whether
8332/// the result is a producing expression (like a call to an
8333/// ns_returns_retained function) and, if so, rebuild it to hoist the
8334/// release out of the full-expression. Otherwise, return null.
8335/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008336static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008337 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008338 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008339 if (!cleanups) return 0;
8340
8341 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008342 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008343 return 0;
8344
8345 // Splice out the cast. This shouldn't modify any interesting
8346 // features of the statement.
8347 Expr *producer = cast->getSubExpr();
8348 assert(producer->getType() == cast->getType());
8349 assert(producer->getValueKind() == cast->getValueKind());
8350 cleanups->setSubExpr(producer);
8351 return cleanups;
8352}
8353
John McCalldadc5752010-08-24 06:29:42 +00008354ExprResult
John McCallb268a282010-08-23 23:25:46 +00008355Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008356 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008357 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8358 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8359
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008360 bool isFileScope
8361 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008362 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008363 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008364
Chris Lattner366727f2007-07-24 16:58:17 +00008365 // FIXME: there are a variety of strange constraints to enforce here, for
8366 // example, it is not possible to goto into a stmt expression apparently.
8367 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008368
Chris Lattner366727f2007-07-24 16:58:17 +00008369 // If there are sub stmts in the compound stmt, take the type of the last one
8370 // as the type of the stmtexpr.
8371 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008372 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008373 if (!Compound->body_empty()) {
8374 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008375 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008376 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008377 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8378 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008379 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008380 }
John McCall31168b02011-06-15 23:02:42 +00008381
John Wiegley01296292011-04-08 18:41:53 +00008382 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008383 // Do function/array conversion on the last expression, but not
8384 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008385 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8386 if (LastExpr.isInvalid())
8387 return ExprError();
8388 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008389
John Wiegley01296292011-04-08 18:41:53 +00008390 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008391 // In ARC, if the final expression ends in a consume, splice
8392 // the consume out and bind it later. In the alternate case
8393 // (when dealing with a retainable type), the result
8394 // initialization will create a produce. In both cases the
8395 // result will be +1, and we'll need to balance that out with
8396 // a bind.
8397 if (Expr *rebuiltLastStmt
8398 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8399 LastExpr = rebuiltLastStmt;
8400 } else {
8401 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008402 InitializedEntity::InitializeResult(LPLoc,
8403 Ty,
8404 false),
8405 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008406 LastExpr);
8407 }
8408
John Wiegley01296292011-04-08 18:41:53 +00008409 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008410 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008411 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008412 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008413 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008414 else
John Wiegley01296292011-04-08 18:41:53 +00008415 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008416 StmtExprMayBindToTemp = true;
8417 }
8418 }
8419 }
Chris Lattner944d3062008-07-26 19:51:01 +00008420 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008421
Eli Friedmanba961a92009-03-23 00:24:07 +00008422 // FIXME: Check that expression type is complete/non-abstract; statement
8423 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008424 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8425 if (StmtExprMayBindToTemp)
8426 return MaybeBindToTemporary(ResStmtExpr);
8427 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008428}
Steve Naroff78864672007-08-01 22:05:33 +00008429
John McCalldadc5752010-08-24 06:29:42 +00008430ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008431 TypeSourceInfo *TInfo,
8432 OffsetOfComponent *CompPtr,
8433 unsigned NumComponents,
8434 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008435 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008436 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008437 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008438
Chris Lattnerf17bd422007-08-30 17:45:32 +00008439 // We must have at least one component that refers to the type, and the first
8440 // one is known to be a field designator. Verify that the ArgTy represents
8441 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008442 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008443 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8444 << ArgTy << TypeRange);
8445
8446 // Type must be complete per C99 7.17p3 because a declaring a variable
8447 // with an incomplete type would be ill-formed.
8448 if (!Dependent
8449 && RequireCompleteType(BuiltinLoc, ArgTy,
8450 PDiag(diag::err_offsetof_incomplete_type)
8451 << TypeRange))
8452 return ExprError();
8453
Chris Lattner78502cf2007-08-31 21:49:13 +00008454 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8455 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008456 // FIXME: This diagnostic isn't actually visible because the location is in
8457 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008458 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008459 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8460 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008461
8462 bool DidWarnAboutNonPOD = false;
8463 QualType CurrentType = ArgTy;
8464 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008465 SmallVector<OffsetOfNode, 4> Comps;
8466 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008467 for (unsigned i = 0; i != NumComponents; ++i) {
8468 const OffsetOfComponent &OC = CompPtr[i];
8469 if (OC.isBrackets) {
8470 // Offset of an array sub-field. TODO: Should we allow vector elements?
8471 if (!CurrentType->isDependentType()) {
8472 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8473 if(!AT)
8474 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8475 << CurrentType);
8476 CurrentType = AT->getElementType();
8477 } else
8478 CurrentType = Context.DependentTy;
8479
8480 // The expression must be an integral expression.
8481 // FIXME: An integral constant expression?
8482 Expr *Idx = static_cast<Expr*>(OC.U.E);
8483 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8484 !Idx->getType()->isIntegerType())
8485 return ExprError(Diag(Idx->getLocStart(),
8486 diag::err_typecheck_subscript_not_integer)
8487 << Idx->getSourceRange());
8488
8489 // Record this array index.
8490 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8491 Exprs.push_back(Idx);
8492 continue;
8493 }
8494
8495 // Offset of a field.
8496 if (CurrentType->isDependentType()) {
8497 // We have the offset of a field, but we can't look into the dependent
8498 // type. Just record the identifier of the field.
8499 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8500 CurrentType = Context.DependentTy;
8501 continue;
8502 }
8503
8504 // We need to have a complete type to look into.
8505 if (RequireCompleteType(OC.LocStart, CurrentType,
8506 diag::err_offsetof_incomplete_type))
8507 return ExprError();
8508
8509 // Look for the designated field.
8510 const RecordType *RC = CurrentType->getAs<RecordType>();
8511 if (!RC)
8512 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8513 << CurrentType);
8514 RecordDecl *RD = RC->getDecl();
8515
8516 // C++ [lib.support.types]p5:
8517 // The macro offsetof accepts a restricted set of type arguments in this
8518 // International Standard. type shall be a POD structure or a POD union
8519 // (clause 9).
8520 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8521 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008522 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008523 PDiag(diag::warn_offsetof_non_pod_type)
8524 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8525 << CurrentType))
8526 DidWarnAboutNonPOD = true;
8527 }
8528
8529 // Look for the field.
8530 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8531 LookupQualifiedName(R, RD);
8532 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008533 IndirectFieldDecl *IndirectMemberDecl = 0;
8534 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008535 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008536 MemberDecl = IndirectMemberDecl->getAnonField();
8537 }
8538
Douglas Gregor882211c2010-04-28 22:16:22 +00008539 if (!MemberDecl)
8540 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8541 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8542 OC.LocEnd));
8543
Douglas Gregor10982ea2010-04-28 22:36:06 +00008544 // C99 7.17p3:
8545 // (If the specified member is a bit-field, the behavior is undefined.)
8546 //
8547 // We diagnose this as an error.
8548 if (MemberDecl->getBitWidth()) {
8549 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8550 << MemberDecl->getDeclName()
8551 << SourceRange(BuiltinLoc, RParenLoc);
8552 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8553 return ExprError();
8554 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008555
8556 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008557 if (IndirectMemberDecl)
8558 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008559
Douglas Gregord1702062010-04-29 00:18:15 +00008560 // If the member was found in a base class, introduce OffsetOfNodes for
8561 // the base class indirections.
8562 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8563 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008564 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008565 CXXBasePath &Path = Paths.front();
8566 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8567 B != BEnd; ++B)
8568 Comps.push_back(OffsetOfNode(B->Base));
8569 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008570
Francois Pichet783dd6e2010-11-21 06:08:52 +00008571 if (IndirectMemberDecl) {
8572 for (IndirectFieldDecl::chain_iterator FI =
8573 IndirectMemberDecl->chain_begin(),
8574 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8575 assert(isa<FieldDecl>(*FI));
8576 Comps.push_back(OffsetOfNode(OC.LocStart,
8577 cast<FieldDecl>(*FI), OC.LocEnd));
8578 }
8579 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008580 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008581
Douglas Gregor882211c2010-04-28 22:16:22 +00008582 CurrentType = MemberDecl->getType().getNonReferenceType();
8583 }
8584
8585 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8586 TInfo, Comps.data(), Comps.size(),
8587 Exprs.data(), Exprs.size(), RParenLoc));
8588}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008589
John McCalldadc5752010-08-24 06:29:42 +00008590ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008591 SourceLocation BuiltinLoc,
8592 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008593 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008594 OffsetOfComponent *CompPtr,
8595 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008596 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008597
Douglas Gregor882211c2010-04-28 22:16:22 +00008598 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008599 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008600 if (ArgTy.isNull())
8601 return ExprError();
8602
Eli Friedman06dcfd92010-08-05 10:15:45 +00008603 if (!ArgTInfo)
8604 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8605
8606 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008607 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008608}
8609
8610
John McCalldadc5752010-08-24 06:29:42 +00008611ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008612 Expr *CondExpr,
8613 Expr *LHSExpr, Expr *RHSExpr,
8614 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008615 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8616
John McCall7decc9e2010-11-18 06:31:45 +00008617 ExprValueKind VK = VK_RValue;
8618 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008619 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008620 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008621 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008622 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008623 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008624 } else {
8625 // The conditional expression is required to be a constant expression.
8626 llvm::APSInt condEval(32);
8627 SourceLocation ExpLoc;
8628 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008629 return ExprError(Diag(ExpLoc,
8630 diag::err_typecheck_choose_expr_requires_constant)
8631 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008632
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008633 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008634 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8635
8636 resType = ActiveExpr->getType();
8637 ValueDependent = ActiveExpr->isValueDependent();
8638 VK = ActiveExpr->getValueKind();
8639 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008640 }
8641
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008642 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008643 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008644 resType->isDependentType(),
8645 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008646}
8647
Steve Naroffc540d662008-09-03 18:15:37 +00008648//===----------------------------------------------------------------------===//
8649// Clang Extensions.
8650//===----------------------------------------------------------------------===//
8651
8652/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008653void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008654 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008655 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008656 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008657 if (CurScope)
8658 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008659 else
8660 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008661}
8662
Mike Stump82f071f2009-02-04 22:31:32 +00008663void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008664 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008665 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008666 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008667
John McCall8cb7bdf2010-06-04 23:28:52 +00008668 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008669 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008670
John McCall3882ace2011-01-05 12:14:39 +00008671 // GetTypeForDeclarator always produces a function type for a block
8672 // literal signature. Furthermore, it is always a FunctionProtoType
8673 // unless the function was written with a typedef.
8674 assert(T->isFunctionType() &&
8675 "GetTypeForDeclarator made a non-function block signature");
8676
8677 // Look for an explicit signature in that function type.
8678 FunctionProtoTypeLoc ExplicitSignature;
8679
8680 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8681 if (isa<FunctionProtoTypeLoc>(tmp)) {
8682 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8683
8684 // Check whether that explicit signature was synthesized by
8685 // GetTypeForDeclarator. If so, don't save that as part of the
8686 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008687 if (ExplicitSignature.getLocalRangeBegin() ==
8688 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008689 // This would be much cheaper if we stored TypeLocs instead of
8690 // TypeSourceInfos.
8691 TypeLoc Result = ExplicitSignature.getResultLoc();
8692 unsigned Size = Result.getFullDataSize();
8693 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8694 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8695
8696 ExplicitSignature = FunctionProtoTypeLoc();
8697 }
John McCalla3ccba02010-06-04 11:21:44 +00008698 }
Mike Stump11289f42009-09-09 15:08:12 +00008699
John McCall3882ace2011-01-05 12:14:39 +00008700 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8701 CurBlock->FunctionType = T;
8702
8703 const FunctionType *Fn = T->getAs<FunctionType>();
8704 QualType RetTy = Fn->getResultType();
8705 bool isVariadic =
8706 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8707
John McCall8e346702010-06-04 19:02:56 +00008708 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008709
John McCalla3ccba02010-06-04 11:21:44 +00008710 // Don't allow returning a objc interface by value.
8711 if (RetTy->isObjCObjectType()) {
8712 Diag(ParamInfo.getSourceRange().getBegin(),
8713 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8714 return;
8715 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008716
John McCalla3ccba02010-06-04 11:21:44 +00008717 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008718 // return type. TODO: what should we do with declarators like:
8719 // ^ * { ... }
8720 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008721 if (RetTy != Context.DependentTy)
8722 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008723
John McCalla3ccba02010-06-04 11:21:44 +00008724 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008725 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008726 if (ExplicitSignature) {
8727 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8728 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008729 if (Param->getIdentifier() == 0 &&
8730 !Param->isImplicit() &&
8731 !Param->isInvalidDecl() &&
8732 !getLangOptions().CPlusPlus)
8733 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008734 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008735 }
John McCalla3ccba02010-06-04 11:21:44 +00008736
8737 // Fake up parameter variables if we have a typedef, like
8738 // ^ fntype { ... }
8739 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8740 for (FunctionProtoType::arg_type_iterator
8741 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8742 ParmVarDecl *Param =
8743 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8744 ParamInfo.getSourceRange().getBegin(),
8745 *I);
John McCall8e346702010-06-04 19:02:56 +00008746 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008747 }
Steve Naroffc540d662008-09-03 18:15:37 +00008748 }
John McCalla3ccba02010-06-04 11:21:44 +00008749
John McCall8e346702010-06-04 19:02:56 +00008750 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008751 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008752 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008753 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8754 CurBlock->TheDecl->param_end(),
8755 /*CheckParameterNames=*/false);
8756 }
8757
John McCalla3ccba02010-06-04 11:21:44 +00008758 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008759 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008760
John McCall8e346702010-06-04 19:02:56 +00008761 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008762 Diag(ParamInfo.getAttributes()->getLoc(),
8763 diag::warn_attribute_sentinel_not_variadic) << 1;
8764 // FIXME: remove the attribute.
8765 }
8766
8767 // Put the parameter variables in scope. We can bail out immediately
8768 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008769 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008770 return;
8771
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008772 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008773 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8774 (*AI)->setOwningFunction(CurBlock->TheDecl);
8775
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008776 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008777 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008778 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008779
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008780 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008781 }
John McCallf7b2fb52010-01-22 00:28:27 +00008782 }
Steve Naroffc540d662008-09-03 18:15:37 +00008783}
8784
8785/// ActOnBlockError - If there is an error parsing a block, this callback
8786/// is invoked to pop the information about the block from the action impl.
8787void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008788 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008789 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008790 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008791}
8792
8793/// ActOnBlockStmtExpr - This is called when the body of a block statement
8794/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008795ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008796 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008797 // If blocks are disabled, emit an error.
8798 if (!LangOpts.Blocks)
8799 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008800
Douglas Gregor9a28e842010-03-01 23:15:13 +00008801 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008802
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008803 PopDeclContext();
8804
Steve Naroffc540d662008-09-03 18:15:37 +00008805 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008806 if (!BSI->ReturnType.isNull())
8807 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008808
Mike Stump3bf1ab42009-07-28 22:04:01 +00008809 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008810 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008811
John McCallc63de662011-02-02 13:00:07 +00008812 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008813 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8814 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008815
John McCall8e346702010-06-04 19:02:56 +00008816 // If the user wrote a function type in some form, try to use that.
8817 if (!BSI->FunctionType.isNull()) {
8818 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8819
8820 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8821 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8822
8823 // Turn protoless block types into nullary block types.
8824 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008825 FunctionProtoType::ExtProtoInfo EPI;
8826 EPI.ExtInfo = Ext;
8827 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008828
8829 // Otherwise, if we don't need to change anything about the function type,
8830 // preserve its sugar structure.
8831 } else if (FTy->getResultType() == RetTy &&
8832 (!NoReturn || FTy->getNoReturnAttr())) {
8833 BlockTy = BSI->FunctionType;
8834
8835 // Otherwise, make the minimal modifications to the function type.
8836 } else {
8837 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008838 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8839 EPI.TypeQuals = 0; // FIXME: silently?
8840 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008841 BlockTy = Context.getFunctionType(RetTy,
8842 FPT->arg_type_begin(),
8843 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008844 EPI);
John McCall8e346702010-06-04 19:02:56 +00008845 }
8846
8847 // If we don't have a function type, just build one from nothing.
8848 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008849 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008850 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008851 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008853
John McCall8e346702010-06-04 19:02:56 +00008854 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8855 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008856 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008857
Chris Lattner45542ea2009-04-19 05:28:12 +00008858 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008859 if (getCurFunction()->NeedsScopeChecking() &&
8860 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008861 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008862
Chris Lattner60f84492011-02-17 23:58:47 +00008863 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008864
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008865 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8866 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8867 const VarDecl *variable = ci->getVariable();
8868 QualType T = variable->getType();
8869 QualType::DestructionKind destructKind = T.isDestructedType();
8870 if (destructKind != QualType::DK_none)
8871 getCurFunction()->setHasBranchProtectedScope();
8872 }
8873
Douglas Gregor49695f02011-09-06 20:46:03 +00008874 computeNRVO(Body, getCurBlock());
8875
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008876 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8877 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8878 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8879
Douglas Gregor9a28e842010-03-01 23:15:13 +00008880 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008881}
8882
John McCalldadc5752010-08-24 06:29:42 +00008883ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008884 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008885 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008886 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008887 GetTypeFromParser(Ty, &TInfo);
8888 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008889}
8890
John McCalldadc5752010-08-24 06:29:42 +00008891ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008892 Expr *E, TypeSourceInfo *TInfo,
8893 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008894 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008895
Eli Friedman121ba0c2008-08-09 23:32:40 +00008896 // Get the va_list type
8897 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008898 if (VaListType->isArrayType()) {
8899 // Deal with implicit array decay; for example, on x86-64,
8900 // va_list is an array, but it's supposed to decay to
8901 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008902 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008903 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008904 ExprResult Result = UsualUnaryConversions(E);
8905 if (Result.isInvalid())
8906 return ExprError();
8907 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008908 } else {
8909 // Otherwise, the va_list argument must be an l-value because
8910 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008911 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008912 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008913 return ExprError();
8914 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008915
Douglas Gregorad3150c2009-05-19 23:10:31 +00008916 if (!E->isTypeDependent() &&
8917 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008918 return ExprError(Diag(E->getLocStart(),
8919 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008920 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008922
David Majnemerc75d1a12011-06-14 05:17:32 +00008923 if (!TInfo->getType()->isDependentType()) {
8924 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8925 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8926 << TInfo->getTypeLoc().getSourceRange()))
8927 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008928
David Majnemerc75d1a12011-06-14 05:17:32 +00008929 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8930 TInfo->getType(),
8931 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8932 << TInfo->getTypeLoc().getSourceRange()))
8933 return ExprError();
8934
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008935 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008936 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008937 TInfo->getType()->isObjCLifetimeType()
8938 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8939 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008940 << TInfo->getType()
8941 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008942 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008943
8944 // Check for va_arg where arguments of the given type will be promoted
8945 // (i.e. this va_arg is guaranteed to have undefined behavior).
8946 QualType PromoteType;
8947 if (TInfo->getType()->isPromotableIntegerType()) {
8948 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8949 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8950 PromoteType = QualType();
8951 }
8952 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8953 PromoteType = Context.DoubleTy;
8954 if (!PromoteType.isNull())
8955 Diag(TInfo->getTypeLoc().getBeginLoc(),
8956 diag::warn_second_parameter_to_va_arg_never_compatible)
8957 << TInfo->getType()
8958 << PromoteType
8959 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008960 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008961
Abramo Bagnara27db2392010-08-10 10:06:15 +00008962 QualType T = TInfo->getType().getNonLValueExprType(Context);
8963 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008964}
8965
John McCalldadc5752010-08-24 06:29:42 +00008966ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008967 // The type of __null will be int or long, depending on the size of
8968 // pointers on the target.
8969 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008970 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8971 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008972 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008973 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008974 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008975 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008976 Ty = Context.LongLongTy;
8977 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008978 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008979 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008980
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008981 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008982}
8983
Alexis Huntc46382e2010-04-28 23:02:27 +00008984static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008985 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008986 if (!SemaRef.getLangOptions().ObjC1)
8987 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008988
Anders Carlssonace5d072009-11-10 04:46:30 +00008989 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8990 if (!PT)
8991 return;
8992
8993 // Check if the destination is of type 'id'.
8994 if (!PT->isObjCIdType()) {
8995 // Check if the destination is the 'NSString' interface.
8996 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8997 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8998 return;
8999 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009000
Anders Carlssonace5d072009-11-10 04:46:30 +00009001 // Strip off any parens and casts.
9002 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00009003 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009004 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009005
Douglas Gregora771f462010-03-31 17:46:05 +00009006 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009007}
9008
Chris Lattner9bad62c2008-01-04 18:04:52 +00009009bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9010 SourceLocation Loc,
9011 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009012 Expr *SrcExpr, AssignmentAction Action,
9013 bool *Complained) {
9014 if (Complained)
9015 *Complained = false;
9016
Chris Lattner9bad62c2008-01-04 18:04:52 +00009017 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009018 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009019 bool isInvalid = false;
9020 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009021 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009022 ConversionFixItGenerator ConvHints;
9023 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009024
Chris Lattner9bad62c2008-01-04 18:04:52 +00009025 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00009026 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009027 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009028 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009029 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009030 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9031 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009032 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009033 case IntToPointer:
9034 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009035 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9036 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009037 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009038 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009039 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009040 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009041 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9042 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009043 if (Hint.isNull() && !CheckInferredResultType) {
9044 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9045 }
9046 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009047 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009048 case IncompatiblePointerSign:
9049 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9050 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009051 case FunctionVoidPointer:
9052 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9053 break;
John McCall4fff8f62011-02-01 00:10:29 +00009054 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009055 // Perform array-to-pointer decay if necessary.
9056 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9057
John McCall4fff8f62011-02-01 00:10:29 +00009058 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9059 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9060 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9061 DiagKind = diag::err_typecheck_incompatible_address_space;
9062 break;
John McCall31168b02011-06-15 23:02:42 +00009063
9064
9065 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009066 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009067 break;
John McCall4fff8f62011-02-01 00:10:29 +00009068 }
9069
9070 llvm_unreachable("unknown error case for discarding qualifiers!");
9071 // fallthrough
9072 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009073 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009074 // If the qualifiers lost were because we were applying the
9075 // (deprecated) C++ conversion from a string literal to a char*
9076 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9077 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009078 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009079 // bit of refactoring (so that the second argument is an
9080 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009081 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009082 // C++ semantics.
9083 if (getLangOptions().CPlusPlus &&
9084 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9085 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009086 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9087 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009088 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009089 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009090 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009091 case IntToBlockPointer:
9092 DiagKind = diag::err_int_to_block_pointer;
9093 break;
9094 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009095 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009096 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009097 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009098 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009099 // it can give a more specific diagnostic.
9100 DiagKind = diag::warn_incompatible_qualified_id;
9101 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009102 case IncompatibleVectors:
9103 DiagKind = diag::warn_incompatible_vectors;
9104 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009105 case IncompatibleObjCWeakRef:
9106 DiagKind = diag::err_arc_weak_unavailable_assign;
9107 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009108 case Incompatible:
9109 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009110 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9111 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009112 isInvalid = true;
9113 break;
9114 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009115
Douglas Gregorc68e1402010-04-09 00:35:39 +00009116 QualType FirstType, SecondType;
9117 switch (Action) {
9118 case AA_Assigning:
9119 case AA_Initializing:
9120 // The destination type comes first.
9121 FirstType = DstType;
9122 SecondType = SrcType;
9123 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009124
Douglas Gregorc68e1402010-04-09 00:35:39 +00009125 case AA_Returning:
9126 case AA_Passing:
9127 case AA_Converting:
9128 case AA_Sending:
9129 case AA_Casting:
9130 // The source type comes first.
9131 FirstType = SrcType;
9132 SecondType = DstType;
9133 break;
9134 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009135
Anna Zaks3b402712011-07-28 19:51:27 +00009136 PartialDiagnostic FDiag = PDiag(DiagKind);
9137 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9138
9139 // If we can fix the conversion, suggest the FixIts.
9140 assert(ConvHints.isNull() || Hint.isNull());
9141 if (!ConvHints.isNull()) {
9142 for (llvm::SmallVector<FixItHint, 1>::iterator
9143 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9144 HI != HE; ++HI)
9145 FDiag << *HI;
9146 } else {
9147 FDiag << Hint;
9148 }
9149 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9150
9151 Diag(Loc, FDiag);
9152
Douglas Gregor33823722011-06-11 01:09:30 +00009153 if (CheckInferredResultType)
9154 EmitRelatedResultTypeNote(SrcExpr);
9155
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009156 if (Complained)
9157 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009158 return isInvalid;
9159}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009160
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009161bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009162 llvm::APSInt ICEResult;
9163 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9164 if (Result)
9165 *Result = ICEResult;
9166 return false;
9167 }
9168
Anders Carlssone54e8a12008-11-30 19:50:32 +00009169 Expr::EvalResult EvalResult;
9170
Mike Stump4e1f26a2009-02-19 03:04:26 +00009171 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009172 EvalResult.HasSideEffects) {
9173 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9174
9175 if (EvalResult.Diag) {
9176 // We only show the note if it's not the usual "invalid subexpression"
9177 // or if it's actually in a subexpression.
9178 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9179 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9180 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9181 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009182
Anders Carlssone54e8a12008-11-30 19:50:32 +00009183 return true;
9184 }
9185
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009186 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9187 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009188
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009189 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009190 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009191 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009192 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009193
Anders Carlssone54e8a12008-11-30 19:50:32 +00009194 if (Result)
9195 *Result = EvalResult.Val.getInt();
9196 return false;
9197}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009198
Douglas Gregorff790f12009-11-26 00:44:06 +00009199void
Mike Stump11289f42009-09-09 15:08:12 +00009200Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009201 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009202 ExpressionEvaluationContextRecord(NewContext,
9203 ExprTemporaries.size(),
9204 ExprNeedsCleanups));
9205 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009206}
9207
Richard Trieucfc491d2011-08-02 04:35:43 +00009208void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009209 // Pop the current expression evaluation context off the stack.
9210 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9211 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009212
Douglas Gregorfab31f42009-12-12 07:57:52 +00009213 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9214 if (Rec.PotentiallyReferenced) {
9215 // Mark any remaining declarations in the current position of the stack
9216 // as "referenced". If they were not meant to be referenced, semantic
9217 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009218 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009219 I = Rec.PotentiallyReferenced->begin(),
9220 IEnd = Rec.PotentiallyReferenced->end();
9221 I != IEnd; ++I)
9222 MarkDeclarationReferenced(I->first, I->second);
9223 }
9224
9225 if (Rec.PotentiallyDiagnosed) {
9226 // Emit any pending diagnostics.
9227 for (PotentiallyEmittedDiagnostics::iterator
9228 I = Rec.PotentiallyDiagnosed->begin(),
9229 IEnd = Rec.PotentiallyDiagnosed->end();
9230 I != IEnd; ++I)
9231 Diag(I->first, I->second);
9232 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009233 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009234
9235 // When are coming out of an unevaluated context, clear out any
9236 // temporaries that we may have created as part of the evaluation of
9237 // the expression in that context: they aren't relevant because they
9238 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009239 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009240 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9241 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009242 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9243
9244 // Otherwise, merge the contexts together.
9245 } else {
9246 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9247 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009248
9249 // Destroy the popped expression evaluation record.
9250 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009251}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009252
John McCall31168b02011-06-15 23:02:42 +00009253void Sema::DiscardCleanupsInEvaluationContext() {
9254 ExprTemporaries.erase(
9255 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9256 ExprTemporaries.end());
9257 ExprNeedsCleanups = false;
9258}
9259
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009260/// \brief Note that the given declaration was referenced in the source code.
9261///
9262/// This routine should be invoke whenever a given declaration is referenced
9263/// in the source code, and where that reference occurred. If this declaration
9264/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9265/// C99 6.9p3), then the declaration will be marked as used.
9266///
9267/// \param Loc the location where the declaration was referenced.
9268///
9269/// \param D the declaration that has been referenced by the source code.
9270void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9271 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009272
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009273 D->setReferenced();
9274
Douglas Gregorebada0772010-06-17 23:14:26 +00009275 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009276 return;
Mike Stump11289f42009-09-09 15:08:12 +00009277
Richard Trieucfc491d2011-08-02 04:35:43 +00009278 // Mark a parameter or variable declaration "used", regardless of whether
9279 // we're in a template or not. The reason for this is that unevaluated
9280 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9281 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009282 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009283 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009284 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009285 return;
9286 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009287
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009288 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9289 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009290
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009291 // Do not mark anything as "used" within a dependent context; wait for
9292 // an instantiation.
9293 if (CurContext->isDependentContext())
9294 return;
Mike Stump11289f42009-09-09 15:08:12 +00009295
Douglas Gregorff790f12009-11-26 00:44:06 +00009296 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009297 case Unevaluated:
9298 // We are in an expression that is not potentially evaluated; do nothing.
9299 return;
Mike Stump11289f42009-09-09 15:08:12 +00009300
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009301 case PotentiallyEvaluated:
9302 // We are in a potentially-evaluated expression, so this declaration is
9303 // "used"; handle this below.
9304 break;
Mike Stump11289f42009-09-09 15:08:12 +00009305
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009306 case PotentiallyPotentiallyEvaluated:
9307 // We are in an expression that may be potentially evaluated; queue this
9308 // declaration reference until we know whether the expression is
9309 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009310 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009311 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009312
9313 case PotentiallyEvaluatedIfUsed:
9314 // Referenced declarations will only be used if the construct in the
9315 // containing expression is used.
9316 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009317 }
Mike Stump11289f42009-09-09 15:08:12 +00009318
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009319 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009320 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009321 if (Constructor->isDefaulted()) {
9322 if (Constructor->isDefaultConstructor()) {
9323 if (Constructor->isTrivial())
9324 return;
9325 if (!Constructor->isUsed(false))
9326 DefineImplicitDefaultConstructor(Loc, Constructor);
9327 } else if (Constructor->isCopyConstructor()) {
9328 if (!Constructor->isUsed(false))
9329 DefineImplicitCopyConstructor(Loc, Constructor);
9330 } else if (Constructor->isMoveConstructor()) {
9331 if (!Constructor->isUsed(false))
9332 DefineImplicitMoveConstructor(Loc, Constructor);
9333 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009334 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009335
Douglas Gregor88d292c2010-05-13 16:44:06 +00009336 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009337 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009338 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009339 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009340 if (Destructor->isVirtual())
9341 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009342 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009343 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009344 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009345 if (!MethodDecl->isUsed(false)) {
9346 if (MethodDecl->isCopyAssignmentOperator())
9347 DefineImplicitCopyAssignment(Loc, MethodDecl);
9348 else
9349 DefineImplicitMoveAssignment(Loc, MethodDecl);
9350 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009351 } else if (MethodDecl->isVirtual())
9352 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009353 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009354 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009355 // Recursive functions should be marked when used from another function.
9356 if (CurContext == Function) return;
9357
Mike Stump11289f42009-09-09 15:08:12 +00009358 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009359 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009360 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009361 bool AlreadyInstantiated = false;
9362 if (FunctionTemplateSpecializationInfo *SpecInfo
9363 = Function->getTemplateSpecializationInfo()) {
9364 if (SpecInfo->getPointOfInstantiation().isInvalid())
9365 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009366 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009367 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009368 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009369 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009370 = Function->getMemberSpecializationInfo()) {
9371 if (MSInfo->getPointOfInstantiation().isInvalid())
9372 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009373 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009374 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009375 AlreadyInstantiated = true;
9376 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009377
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009378 if (!AlreadyInstantiated) {
9379 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9380 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9381 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9382 Loc));
9383 else
Chandler Carruth54080172010-08-25 08:44:16 +00009384 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009385 }
John McCall83779672011-02-19 02:53:41 +00009386 } else {
9387 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009388 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9389 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009390 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009391 MarkDeclarationReferenced(Loc, *i);
9392 }
John McCall83779672011-02-19 02:53:41 +00009393 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009394
John McCall83779672011-02-19 02:53:41 +00009395 // Keep track of used but undefined functions.
9396 if (!Function->isPure() && !Function->hasBody() &&
9397 Function->getLinkage() != ExternalLinkage) {
9398 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9399 if (old.isInvalid()) old = Loc;
9400 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009401
John McCall83779672011-02-19 02:53:41 +00009402 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009403 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009404 }
Mike Stump11289f42009-09-09 15:08:12 +00009405
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009406 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009407 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009408 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009409 Var->getInstantiatedFromStaticDataMember()) {
9410 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9411 assert(MSInfo && "Missing member specialization information?");
9412 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9413 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9414 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009415 // This is a modification of an existing AST node. Notify listeners.
9416 if (ASTMutationListener *L = getASTMutationListener())
9417 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009418 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009419 }
9420 }
Mike Stump11289f42009-09-09 15:08:12 +00009421
John McCall15dd4042011-02-21 19:25:48 +00009422 // Keep track of used but undefined variables. We make a hole in
9423 // the warning for static const data members with in-line
9424 // initializers.
John McCall83779672011-02-19 02:53:41 +00009425 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009426 && Var->getLinkage() != ExternalLinkage
9427 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009428 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9429 if (old.isInvalid()) old = Loc;
9430 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009431
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009432 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009433 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009434 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009435}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009436
Douglas Gregor5597ab42010-05-07 23:12:07 +00009437namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009438 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009439 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009440 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009441 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9442 Sema &S;
9443 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009444
Douglas Gregor5597ab42010-05-07 23:12:07 +00009445 public:
9446 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009447
Douglas Gregor5597ab42010-05-07 23:12:07 +00009448 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009449
9450 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9451 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009452 };
9453}
9454
Chandler Carruthaf80f662010-06-09 08:17:30 +00009455bool MarkReferencedDecls::TraverseTemplateArgument(
9456 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009457 if (Arg.getKind() == TemplateArgument::Declaration) {
9458 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9459 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009460
9461 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009462}
9463
Chandler Carruthaf80f662010-06-09 08:17:30 +00009464bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009465 if (ClassTemplateSpecializationDecl *Spec
9466 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9467 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009468 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009469 }
9470
Chandler Carruthc65667c2010-06-10 10:31:57 +00009471 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009472}
9473
9474void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9475 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009476 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009477}
9478
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009479namespace {
9480 /// \brief Helper class that marks all of the declarations referenced by
9481 /// potentially-evaluated subexpressions as "referenced".
9482 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9483 Sema &S;
9484
9485 public:
9486 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9487
9488 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9489
9490 void VisitDeclRefExpr(DeclRefExpr *E) {
9491 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9492 }
9493
9494 void VisitMemberExpr(MemberExpr *E) {
9495 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009496 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009497 }
9498
9499 void VisitCXXNewExpr(CXXNewExpr *E) {
9500 if (E->getConstructor())
9501 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9502 if (E->getOperatorNew())
9503 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9504 if (E->getOperatorDelete())
9505 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009506 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009507 }
9508
9509 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9510 if (E->getOperatorDelete())
9511 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009512 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9513 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9514 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9515 S.MarkDeclarationReferenced(E->getLocStart(),
9516 S.LookupDestructor(Record));
9517 }
9518
Douglas Gregor32b3de52010-09-11 23:32:50 +00009519 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009520 }
9521
9522 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9523 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009524 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009525 }
9526
9527 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9528 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9529 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009530
9531 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9532 Visit(E->getExpr());
9533 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009534 };
9535}
9536
9537/// \brief Mark any declarations that appear within this expression or any
9538/// potentially-evaluated subexpressions as "referenced".
9539void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9540 EvaluatedExprMarker(*this).Visit(E);
9541}
9542
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009543/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9544/// of the program being compiled.
9545///
9546/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009547/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009548/// possibility that the code will actually be executable. Code in sizeof()
9549/// expressions, code used only during overload resolution, etc., are not
9550/// potentially evaluated. This routine will suppress such diagnostics or,
9551/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009552/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009553/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009554///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009555/// This routine should be used for all diagnostics that describe the run-time
9556/// behavior of a program, such as passing a non-POD value through an ellipsis.
9557/// Failure to do so will likely result in spurious diagnostics or failures
9558/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009559bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009560 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009561 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009562 case Unevaluated:
9563 // The argument will never be evaluated, so don't complain.
9564 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009565
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009566 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009567 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009568 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009569 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009570 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009571 }
9572 else
9573 Diag(Loc, PD);
9574
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009575 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009576
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009577 case PotentiallyPotentiallyEvaluated:
9578 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9579 break;
9580 }
9581
9582 return false;
9583}
9584
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009585bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9586 CallExpr *CE, FunctionDecl *FD) {
9587 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9588 return false;
9589
9590 PartialDiagnostic Note =
9591 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9592 << FD->getDeclName() : PDiag();
9593 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009594
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009595 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009596 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009597 PDiag(diag::err_call_function_incomplete_return)
9598 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009599 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009600 << CE->getSourceRange(),
9601 std::make_pair(NoteLoc, Note)))
9602 return true;
9603
9604 return false;
9605}
9606
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009607// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009608// will prevent this condition from triggering, which is what we want.
9609void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9610 SourceLocation Loc;
9611
John McCall0506e4a2009-11-11 02:41:58 +00009612 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009613 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009614
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009615 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009616 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009617 return;
9618
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009619 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9620
John McCallb0e419e2009-11-12 00:06:05 +00009621 // Greylist some idioms by putting them into a warning subcategory.
9622 if (ObjCMessageExpr *ME
9623 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9624 Selector Sel = ME->getSelector();
9625
John McCallb0e419e2009-11-12 00:06:05 +00009626 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009627 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009628 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9629
9630 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009631 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009632 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9633 }
John McCall0506e4a2009-11-11 02:41:58 +00009634
John McCalld5707ab2009-10-12 21:59:07 +00009635 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009636 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009637 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009638 return;
9639
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009640 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009641 Loc = Op->getOperatorLoc();
9642 } else {
9643 // Not an assignment.
9644 return;
9645 }
9646
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009647 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009648
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009649 SourceLocation Open = E->getSourceRange().getBegin();
9650 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9651 Diag(Loc, diag::note_condition_assign_silence)
9652 << FixItHint::CreateInsertion(Open, "(")
9653 << FixItHint::CreateInsertion(Close, ")");
9654
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009655 if (IsOrAssign)
9656 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9657 << FixItHint::CreateReplacement(Loc, "!=");
9658 else
9659 Diag(Loc, diag::note_condition_assign_to_comparison)
9660 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009661}
9662
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009663/// \brief Redundant parentheses over an equality comparison can indicate
9664/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009665void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009666 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009667 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009668 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9669 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009670 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009671 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009672 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009673
Richard Trieuba63ce62011-09-09 01:45:06 +00009674 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009675
9676 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009677 if (opE->getOpcode() == BO_EQ &&
9678 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9679 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009680 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009681
Ted Kremenekae022092011-02-02 02:20:30 +00009682 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009683 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009684 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9685 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009686 Diag(Loc, diag::note_equality_comparison_to_assign)
9687 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009688 }
9689}
9690
John Wiegley01296292011-04-08 18:41:53 +00009691ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009692 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009693 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9694 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009695
John McCall0009fcc2011-04-26 20:42:42 +00009696 ExprResult result = CheckPlaceholderExpr(E);
9697 if (result.isInvalid()) return ExprError();
9698 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009699
John McCall0009fcc2011-04-26 20:42:42 +00009700 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009701 if (getLangOptions().CPlusPlus)
9702 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9703
John Wiegley01296292011-04-08 18:41:53 +00009704 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9705 if (ERes.isInvalid())
9706 return ExprError();
9707 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009708
9709 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009710 if (!T->isScalarType()) { // C99 6.8.4.1p1
9711 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9712 << T << E->getSourceRange();
9713 return ExprError();
9714 }
John McCalld5707ab2009-10-12 21:59:07 +00009715 }
9716
John Wiegley01296292011-04-08 18:41:53 +00009717 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009718}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009719
John McCalldadc5752010-08-24 06:29:42 +00009720ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009721 Expr *SubExpr) {
9722 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009723 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009724
Richard Trieuba63ce62011-09-09 01:45:06 +00009725 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009726}
John McCall36e7fe32010-10-12 00:20:44 +00009727
John McCall31996342011-04-07 08:22:57 +00009728namespace {
John McCall2979fe02011-04-12 00:42:48 +00009729 /// A visitor for rebuilding a call to an __unknown_any expression
9730 /// to have an appropriate type.
9731 struct RebuildUnknownAnyFunction
9732 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9733
9734 Sema &S;
9735
9736 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9737
9738 ExprResult VisitStmt(Stmt *S) {
9739 llvm_unreachable("unexpected statement!");
9740 return ExprError();
9741 }
9742
Richard Trieu10162ab2011-09-09 03:59:41 +00009743 ExprResult VisitExpr(Expr *E) {
9744 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9745 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009746 return ExprError();
9747 }
9748
9749 /// Rebuild an expression which simply semantically wraps another
9750 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009751 template <class T> ExprResult rebuildSugarExpr(T *E) {
9752 ExprResult SubResult = Visit(E->getSubExpr());
9753 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009754
Richard Trieu10162ab2011-09-09 03:59:41 +00009755 Expr *SubExpr = SubResult.take();
9756 E->setSubExpr(SubExpr);
9757 E->setType(SubExpr->getType());
9758 E->setValueKind(SubExpr->getValueKind());
9759 assert(E->getObjectKind() == OK_Ordinary);
9760 return E;
John McCall2979fe02011-04-12 00:42:48 +00009761 }
9762
Richard Trieu10162ab2011-09-09 03:59:41 +00009763 ExprResult VisitParenExpr(ParenExpr *E) {
9764 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009765 }
9766
Richard Trieu10162ab2011-09-09 03:59:41 +00009767 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9768 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009769 }
9770
Richard Trieu10162ab2011-09-09 03:59:41 +00009771 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9772 ExprResult SubResult = Visit(E->getSubExpr());
9773 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009774
Richard Trieu10162ab2011-09-09 03:59:41 +00009775 Expr *SubExpr = SubResult.take();
9776 E->setSubExpr(SubExpr);
9777 E->setType(S.Context.getPointerType(SubExpr->getType()));
9778 assert(E->getValueKind() == VK_RValue);
9779 assert(E->getObjectKind() == OK_Ordinary);
9780 return E;
John McCall2979fe02011-04-12 00:42:48 +00009781 }
9782
Richard Trieu10162ab2011-09-09 03:59:41 +00009783 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9784 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009785
Richard Trieu10162ab2011-09-09 03:59:41 +00009786 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009787
Richard Trieu10162ab2011-09-09 03:59:41 +00009788 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009789 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009790 !(isa<CXXMethodDecl>(VD) &&
9791 cast<CXXMethodDecl>(VD)->isInstance()))
9792 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009793
Richard Trieu10162ab2011-09-09 03:59:41 +00009794 return E;
John McCall2979fe02011-04-12 00:42:48 +00009795 }
9796
Richard Trieu10162ab2011-09-09 03:59:41 +00009797 ExprResult VisitMemberExpr(MemberExpr *E) {
9798 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009799 }
9800
Richard Trieu10162ab2011-09-09 03:59:41 +00009801 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9802 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009803 }
9804 };
9805}
9806
9807/// Given a function expression of unknown-any type, try to rebuild it
9808/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009809static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9810 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9811 if (Result.isInvalid()) return ExprError();
9812 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009813}
9814
9815namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009816 /// A visitor for rebuilding an expression of type __unknown_anytype
9817 /// into one which resolves the type directly on the referring
9818 /// expression. Strict preservation of the original source
9819 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009820 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009821 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009822
9823 Sema &S;
9824
9825 /// The current destination type.
9826 QualType DestType;
9827
Richard Trieu10162ab2011-09-09 03:59:41 +00009828 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9829 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009830
John McCall39439732011-04-09 22:50:59 +00009831 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009832 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009833 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009834 }
9835
Richard Trieu10162ab2011-09-09 03:59:41 +00009836 ExprResult VisitExpr(Expr *E) {
9837 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9838 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009839 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009840 }
9841
Richard Trieu10162ab2011-09-09 03:59:41 +00009842 ExprResult VisitCallExpr(CallExpr *E);
9843 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009844
John McCall39439732011-04-09 22:50:59 +00009845 /// Rebuild an expression which simply semantically wraps another
9846 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 template <class T> ExprResult rebuildSugarExpr(T *E) {
9848 ExprResult SubResult = Visit(E->getSubExpr());
9849 if (SubResult.isInvalid()) return ExprError();
9850 Expr *SubExpr = SubResult.take();
9851 E->setSubExpr(SubExpr);
9852 E->setType(SubExpr->getType());
9853 E->setValueKind(SubExpr->getValueKind());
9854 assert(E->getObjectKind() == OK_Ordinary);
9855 return E;
John McCall39439732011-04-09 22:50:59 +00009856 }
John McCall31996342011-04-07 08:22:57 +00009857
Richard Trieu10162ab2011-09-09 03:59:41 +00009858 ExprResult VisitParenExpr(ParenExpr *E) {
9859 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009860 }
9861
Richard Trieu10162ab2011-09-09 03:59:41 +00009862 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9863 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009864 }
9865
Richard Trieu10162ab2011-09-09 03:59:41 +00009866 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9867 const PointerType *Ptr = DestType->getAs<PointerType>();
9868 if (!Ptr) {
9869 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9870 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009871 return ExprError();
9872 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009873 assert(E->getValueKind() == VK_RValue);
9874 assert(E->getObjectKind() == OK_Ordinary);
9875 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009876
9877 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009878 DestType = Ptr->getPointeeType();
9879 ExprResult SubResult = Visit(E->getSubExpr());
9880 if (SubResult.isInvalid()) return ExprError();
9881 E->setSubExpr(SubResult.take());
9882 return E;
John McCall2979fe02011-04-12 00:42:48 +00009883 }
9884
Richard Trieu10162ab2011-09-09 03:59:41 +00009885 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009886
Richard Trieu10162ab2011-09-09 03:59:41 +00009887 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009888
Richard Trieu10162ab2011-09-09 03:59:41 +00009889 ExprResult VisitMemberExpr(MemberExpr *E) {
9890 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009891 }
John McCall39439732011-04-09 22:50:59 +00009892
Richard Trieu10162ab2011-09-09 03:59:41 +00009893 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9894 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009895 }
9896 };
9897}
9898
John McCall2d2e8702011-04-11 07:02:50 +00009899/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009900ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9901 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009902
9903 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009904 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009905 FK_FunctionPointer,
9906 FK_BlockPointer
9907 };
9908
Richard Trieu10162ab2011-09-09 03:59:41 +00009909 FnKind Kind;
9910 QualType CalleeType = CalleeExpr->getType();
9911 if (CalleeType == S.Context.BoundMemberTy) {
9912 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9913 Kind = FK_MemberFunction;
9914 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9915 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9916 CalleeType = Ptr->getPointeeType();
9917 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009918 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009919 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9920 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009921 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009922 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009923
9924 // Verify that this is a legal result type of a function.
9925 if (DestType->isArrayType() || DestType->isFunctionType()) {
9926 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009927 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009928 diagID = diag::err_block_returning_array_function;
9929
Richard Trieu10162ab2011-09-09 03:59:41 +00009930 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009931 << DestType->isFunctionType() << DestType;
9932 return ExprError();
9933 }
9934
9935 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009936 E->setType(DestType.getNonLValueExprType(S.Context));
9937 E->setValueKind(Expr::getValueKindForType(DestType));
9938 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009939
9940 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009941 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009942 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009943 Proto->arg_type_begin(),
9944 Proto->getNumArgs(),
9945 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009946 else
9947 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009948 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009949
9950 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009951 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009952 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009953 // Nothing to do.
9954 break;
9955
9956 case FK_FunctionPointer:
9957 DestType = S.Context.getPointerType(DestType);
9958 break;
9959
9960 case FK_BlockPointer:
9961 DestType = S.Context.getBlockPointerType(DestType);
9962 break;
9963 }
9964
9965 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009966 ExprResult CalleeResult = Visit(CalleeExpr);
9967 if (!CalleeResult.isUsable()) return ExprError();
9968 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009969
9970 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009971 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009972}
9973
Richard Trieu10162ab2011-09-09 03:59:41 +00009974ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009975 // Verify that this is a legal result type of a call.
9976 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009977 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009978 << DestType->isFunctionType() << DestType;
9979 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009980 }
9981
John McCall3f4138c2011-07-13 17:56:40 +00009982 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009983 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9984 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9985 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009986 }
John McCall2979fe02011-04-12 00:42:48 +00009987
John McCall2d2e8702011-04-11 07:02:50 +00009988 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009989 E->setType(DestType.getNonReferenceType());
9990 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009991
Richard Trieu10162ab2011-09-09 03:59:41 +00009992 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009993}
9994
Richard Trieu10162ab2011-09-09 03:59:41 +00009995ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009996 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +00009997 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9998 assert(E->getValueKind() == VK_RValue);
9999 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010000
Richard Trieu10162ab2011-09-09 03:59:41 +000010001 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010002
John McCall2d2e8702011-04-11 07:02:50 +000010003 // Rebuild the sub-expression as the pointee (function) type.
10004 DestType = DestType->castAs<PointerType>()->getPointeeType();
10005
Richard Trieu10162ab2011-09-09 03:59:41 +000010006 ExprResult Result = Visit(E->getSubExpr());
10007 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010008
Richard Trieu10162ab2011-09-09 03:59:41 +000010009 E->setSubExpr(Result.take());
10010 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010011}
10012
Richard Trieu10162ab2011-09-09 03:59:41 +000010013ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10014 ExprValueKind ValueKind = VK_LValue;
10015 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010016
10017 // We know how to make this work for certain kinds of decls:
10018
10019 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10021 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10022 DestType = Ptr->getPointeeType();
10023 ExprResult Result = resolveDecl(E, VD);
10024 if (Result.isInvalid()) return ExprError();
10025 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010026 CK_FunctionToPointerDecay, VK_RValue);
10027 }
10028
Richard Trieu10162ab2011-09-09 03:59:41 +000010029 if (!Type->isFunctionType()) {
10030 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10031 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010032 return ExprError();
10033 }
John McCall2d2e8702011-04-11 07:02:50 +000010034
Richard Trieu10162ab2011-09-09 03:59:41 +000010035 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10036 if (MD->isInstance()) {
10037 ValueKind = VK_RValue;
10038 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010039 }
10040
John McCall2d2e8702011-04-11 07:02:50 +000010041 // Function references aren't l-values in C.
10042 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010043 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010044
10045 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010046 } else if (isa<VarDecl>(VD)) {
10047 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10048 Type = RefTy->getPointeeType();
10049 } else if (Type->isFunctionType()) {
10050 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10051 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010052 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010053 }
10054
10055 // - nothing else
10056 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010057 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10058 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010059 return ExprError();
10060 }
10061
Richard Trieu10162ab2011-09-09 03:59:41 +000010062 VD->setType(DestType);
10063 E->setType(Type);
10064 E->setValueKind(ValueKind);
10065 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010066}
10067
John McCall31996342011-04-07 08:22:57 +000010068/// Check a cast of an unknown-any type. We intentionally only
10069/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010070ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10071 Expr *CastExpr, CastKind &CastKind,
10072 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010073 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010074 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010075 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010076
Richard Trieuba63ce62011-09-09 01:45:06 +000010077 CastExpr = result.take();
10078 VK = CastExpr->getValueKind();
10079 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010080
Richard Trieuba63ce62011-09-09 01:45:06 +000010081 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010082}
10083
Richard Trieuba63ce62011-09-09 01:45:06 +000010084static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10085 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010086 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010087 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010088 E = E->IgnoreParenImpCasts();
10089 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10090 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010091 diagID = diag::err_uncasted_call_of_unknown_any;
10092 } else {
John McCall31996342011-04-07 08:22:57 +000010093 break;
John McCall2d2e8702011-04-11 07:02:50 +000010094 }
John McCall31996342011-04-07 08:22:57 +000010095 }
10096
John McCall2d2e8702011-04-11 07:02:50 +000010097 SourceLocation loc;
10098 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010099 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010100 loc = ref->getLocation();
10101 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010102 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010103 loc = mem->getMemberLoc();
10104 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010105 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010106 diagID = diag::err_uncasted_call_of_unknown_any;
10107 loc = msg->getSelectorLoc();
10108 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010109 if (!d) {
10110 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10111 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10112 << orig->getSourceRange();
10113 return ExprError();
10114 }
John McCall2d2e8702011-04-11 07:02:50 +000010115 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010116 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10117 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010118 return ExprError();
10119 }
10120
10121 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010122
10123 // Never recoverable.
10124 return ExprError();
10125}
10126
John McCall36e7fe32010-10-12 00:20:44 +000010127/// Check for operands with placeholder types and complain if found.
10128/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010129ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010130 // Placeholder types are always *exactly* the appropriate builtin type.
10131 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010132
John McCall31996342011-04-07 08:22:57 +000010133 // Overloaded expressions.
10134 if (type == Context.OverloadTy)
10135 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010136 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010137 QualType(),
10138 diag::err_ovl_unresolvable);
10139
John McCall0009fcc2011-04-26 20:42:42 +000010140 // Bound member functions.
10141 if (type == Context.BoundMemberTy) {
10142 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10143 << E->getSourceRange();
10144 return ExprError();
10145 }
10146
John McCall31996342011-04-07 08:22:57 +000010147 // Expressions of unknown type.
10148 if (type == Context.UnknownAnyTy)
10149 return diagnoseUnknownAnyExpr(*this, E);
10150
10151 assert(!type->isPlaceholderType());
10152 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010153}
Richard Trieu2c850c02011-04-21 21:44:26 +000010154
Richard Trieuba63ce62011-09-09 01:45:06 +000010155bool Sema::CheckCaseExpression(Expr *E) {
10156 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010157 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010158 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10159 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010160 return false;
10161}