blob: 25f1342aeb08d0c724ce9cf2bfedb95b4ed91142 [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
Douglas Gregor171c45a2009-02-18 21:56:37 +000059/// \brief Determine whether the use of this declaration is valid, and
60/// emit any corresponding diagnostics.
61///
62/// This routine diagnoses various problems with referencing
63/// declarations that can occur when using a declaration. For example,
64/// it might warn if a deprecated or unavailable declaration is being
65/// used, or produce an error (and return true) if a C++0x deleted
66/// function is being used.
67///
68/// \returns true if there was an error (this declaration cannot be
69/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000070///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000071bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000072 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
74 // If there were any diagnostics suppressed by template argument deduction,
75 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000076 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000077 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
78 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000079 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000080 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
81 Diag(Suppressed[I].first, Suppressed[I].second);
82
83 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000084 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000085 // entry from the table, because we want to avoid ever emitting these
86 // diagnostics again.
87 Suppressed.clear();
88 }
89 }
90
Richard Smith30482bc2011-02-20 03:19:35 +000091 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000092 if (ParsingInitForAutoVars.count(D)) {
93 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
94 << D->getDeclName();
95 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000096 }
97
Douglas Gregor171c45a2009-02-18 21:56:37 +000098 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000100 if (FD->isDeleted()) {
101 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000102 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000103 return true;
104 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000105 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000106
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000107 // See if this declaration is unavailable or deprecated.
108 std::string Message;
109 switch (D->getAvailability(&Message)) {
110 case AR_Available:
111 case AR_NotYetIntroduced:
112 break;
113
114 case AR_Deprecated:
115 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
116 break;
117
118 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000119 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
120 if (Message.empty()) {
121 if (!UnknownObjCClass)
122 Diag(Loc, diag::err_unavailable) << D->getDeclName();
123 else
124 Diag(Loc, diag::warn_unavailable_fwdclass_message)
125 << D->getDeclName();
126 }
127 else
128 Diag(Loc, diag::err_unavailable_message)
129 << D->getDeclName() << Message;
130 Diag(D->getLocation(), diag::note_unavailable_here)
131 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000133 break;
134 }
135
Anders Carlsson73067a02010-10-22 23:37:08 +0000136 // Warn if this is used but marked unused.
137 if (D->hasAttr<UnusedAttr>())
138 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
139
Douglas Gregor171c45a2009-02-18 21:56:37 +0000140 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000141}
142
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000143/// \brief Retrieve the message suffix that should be added to a
144/// diagnostic complaining about the given function being deleted or
145/// unavailable.
146std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
147 // FIXME: C++0x implicitly-deleted special member functions could be
148 // detected here so that we could improve diagnostics to say, e.g.,
149 // "base class 'A' had a deleted copy constructor".
150 if (FD->isDeleted())
151 return std::string();
152
153 std::string Message;
154 if (FD->getAvailability(&Message))
155 return ": " + Message;
156
157 return std::string();
158}
159
John McCallb46f2872011-09-09 07:56:05 +0000160/// DiagnoseSentinelCalls - This routine checks whether a call or
161/// message-send is to a declaration with the sentinel attribute, and
162/// if so, it checks that the requirements of the sentinel are
163/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000164void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000165 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000166 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000167 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000168 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000169
John McCallb46f2872011-09-09 07:56:05 +0000170 // The number of formal parameters of the declaration.
171 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000172
John McCallb46f2872011-09-09 07:56:05 +0000173 // The kind of declaration. This is also an index into a %select in
174 // the diagnostic.
175 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
176
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000178 numFormalParams = MD->param_size();
179 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000180 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000181 numFormalParams = FD->param_size();
182 calleeType = CT_Function;
183 } else if (isa<VarDecl>(D)) {
184 QualType type = cast<ValueDecl>(D)->getType();
185 const FunctionType *fn = 0;
186 if (const PointerType *ptr = type->getAs<PointerType>()) {
187 fn = ptr->getPointeeType()->getAs<FunctionType>();
188 if (!fn) return;
189 calleeType = CT_Function;
190 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
191 fn = ptr->getPointeeType()->castAs<FunctionType>();
192 calleeType = CT_Block;
193 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000194 return;
John McCallb46f2872011-09-09 07:56:05 +0000195 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000196
John McCallb46f2872011-09-09 07:56:05 +0000197 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
198 numFormalParams = proto->getNumArgs();
199 } else {
200 numFormalParams = 0;
201 }
202 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000203 return;
204 }
John McCallb46f2872011-09-09 07:56:05 +0000205
206 // "nullPos" is the number of formal parameters at the end which
207 // effectively count as part of the variadic arguments. This is
208 // useful if you would prefer to not have *any* formal parameters,
209 // but the language forces you to have at least one.
210 unsigned nullPos = attr->getNullPos();
211 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
212 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
213
214 // The number of arguments which should follow the sentinel.
215 unsigned numArgsAfterSentinel = attr->getSentinel();
216
217 // If there aren't enough arguments for all the formal parameters,
218 // the sentinel, and the args after the sentinel, complain.
219 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000220 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000221 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000222 return;
223 }
John McCallb46f2872011-09-09 07:56:05 +0000224
225 // Otherwise, find the sentinel expression.
226 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000227 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000228 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000229
230 // nullptr_t is always treated as null.
231 if (sentinelExpr->getType()->isNullPtrType()) return;
232
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000233 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000234 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
235 Expr::NPC_ValueDependentIsNull))
236 return;
237
238 // Unfortunately, __null has type 'int'.
239 if (isa<GNUNullExpr>(sentinelExpr)) return;
240
John McCallb46f2872011-09-09 07:56:05 +0000241 // Pick a reasonable string to insert. Optimistically use 'nil' or
242 // 'NULL' if those are actually defined in the context. Only use
243 // 'nil' for ObjC methods, where it's much more likely that the
244 // variadic arguments form a list of object pointers.
245 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000246 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
247 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000248 if (calleeType == CT_Method &&
249 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000253 else
John McCallb46f2872011-09-09 07:56:05 +0000254 NullValue = "(void*) 0";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000255
256 Diag(MissingNilLoc, diag::warn_missing_sentinel)
John McCallb46f2872011-09-09 07:56:05 +0000257 << calleeType
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000258 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000259 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000260}
261
Richard Trieuba63ce62011-09-09 01:45:06 +0000262SourceRange Sema::getExprRange(Expr *E) const {
263 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000264}
265
Chris Lattner513165e2008-07-25 21:10:04 +0000266//===----------------------------------------------------------------------===//
267// Standard Promotions and Conversions
268//===----------------------------------------------------------------------===//
269
Chris Lattner513165e2008-07-25 21:10:04 +0000270/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000271ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000272 QualType Ty = E->getType();
273 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
274
Chris Lattner513165e2008-07-25 21:10:04 +0000275 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000276 E = ImpCastExprToType(E, Context.getPointerType(Ty),
277 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000278 else if (Ty->isArrayType()) {
279 // In C90 mode, arrays only promote to pointers if the array expression is
280 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
281 // type 'array of type' is converted to an expression that has type 'pointer
282 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
283 // that has type 'array of type' ...". The relevant change is "an lvalue"
284 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000285 //
286 // C++ 4.2p1:
287 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
288 // T" can be converted to an rvalue of type "pointer to T".
289 //
John McCall086a4642010-11-24 05:12:34 +0000290 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000291 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
292 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000293 }
John Wiegley01296292011-04-08 18:41:53 +0000294 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000295}
296
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000297static void CheckForNullPointerDereference(Sema &S, Expr *E) {
298 // Check to see if we are dereferencing a null pointer. If so,
299 // and if not volatile-qualified, this is undefined behavior that the
300 // optimizer will delete, so warn about it. People sometimes try to use this
301 // to get a deterministic trap and are surprised by clang's behavior. This
302 // only handles the pattern "*null", which is a very syntactic check.
303 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
304 if (UO->getOpcode() == UO_Deref &&
305 UO->getSubExpr()->IgnoreParenCasts()->
306 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
307 !UO->getType().isVolatileQualified()) {
308 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
309 S.PDiag(diag::warn_indirection_through_null)
310 << UO->getSubExpr()->getSourceRange());
311 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
312 S.PDiag(diag::note_indirection_through_null));
313 }
314}
315
John Wiegley01296292011-04-08 18:41:53 +0000316ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000317 // C++ [conv.lval]p1:
318 // A glvalue of a non-function, non-array type T can be
319 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000320 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000321
John McCall27584242010-12-06 20:48:59 +0000322 QualType T = E->getType();
323 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000324
John McCall27584242010-12-06 20:48:59 +0000325 // Create a load out of an ObjCProperty l-value, if necessary.
326 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000327 ExprResult Res = ConvertPropertyForRValue(E);
328 if (Res.isInvalid())
329 return Owned(E);
330 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000331 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000332 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000333 }
John McCall27584242010-12-06 20:48:59 +0000334
335 // We don't want to throw lvalue-to-rvalue casts on top of
336 // expressions of certain types in C++.
337 if (getLangOptions().CPlusPlus &&
338 (E->getType() == Context.OverloadTy ||
339 T->isDependentType() ||
340 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000341 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000342
343 // The C standard is actually really unclear on this point, and
344 // DR106 tells us what the result should be but not why. It's
345 // generally best to say that void types just doesn't undergo
346 // lvalue-to-rvalue at all. Note that expressions of unqualified
347 // 'void' type are never l-values, but qualified void can be.
348 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000349 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000350
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000351 CheckForNullPointerDereference(*this, E);
352
John McCall27584242010-12-06 20:48:59 +0000353 // C++ [conv.lval]p1:
354 // [...] If T is a non-class type, the type of the prvalue is the
355 // cv-unqualified version of T. Otherwise, the type of the
356 // rvalue is T.
357 //
358 // C99 6.3.2.1p2:
359 // If the lvalue has qualified type, the value has the unqualified
360 // version of the type of the lvalue; otherwise, the value has the
361 // type of the lvalue.
362 if (T.hasQualifiers())
363 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000364
John Wiegley01296292011-04-08 18:41:53 +0000365 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
366 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000367}
368
John Wiegley01296292011-04-08 18:41:53 +0000369ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
370 ExprResult Res = DefaultFunctionArrayConversion(E);
371 if (Res.isInvalid())
372 return ExprError();
373 Res = DefaultLvalueConversion(Res.take());
374 if (Res.isInvalid())
375 return ExprError();
376 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000377}
378
379
Chris Lattner513165e2008-07-25 21:10:04 +0000380/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000381/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000382/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000383/// apply if the array is an argument to the sizeof or address (&) operators.
384/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000385ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000386 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000387 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
388 if (Res.isInvalid())
389 return Owned(E);
390 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000391
392 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000393 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000394
395 // Try to perform integral promotions if the object has a theoretically
396 // promotable type.
397 if (Ty->isIntegralOrUnscopedEnumerationType()) {
398 // C99 6.3.1.1p2:
399 //
400 // The following may be used in an expression wherever an int or
401 // unsigned int may be used:
402 // - an object or expression with an integer type whose integer
403 // conversion rank is less than or equal to the rank of int
404 // and unsigned int.
405 // - A bit-field of type _Bool, int, signed int, or unsigned int.
406 //
407 // If an int can represent all values of the original type, the
408 // value is converted to an int; otherwise, it is converted to an
409 // unsigned int. These are called the integer promotions. All
410 // other types are unchanged by the integer promotions.
411
412 QualType PTy = Context.isPromotableBitField(E);
413 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000414 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
415 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000416 }
417 if (Ty->isPromotableIntegerType()) {
418 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000419 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
420 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000421 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000422 }
John Wiegley01296292011-04-08 18:41:53 +0000423 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000424}
425
Chris Lattner2ce500f2008-07-25 22:25:12 +0000426/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000427/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000428/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000429ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
430 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000432
John Wiegley01296292011-04-08 18:41:53 +0000433 ExprResult Res = UsualUnaryConversions(E);
434 if (Res.isInvalid())
435 return Owned(E);
436 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000437
Chris Lattner2ce500f2008-07-25 22:25:12 +0000438 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000439 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000440 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
441
John McCall4bb057d2011-08-27 22:06:17 +0000442 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000443 // promotion, even on class types, but note:
444 // C++11 [conv.lval]p2:
445 // When an lvalue-to-rvalue conversion occurs in an unevaluated
446 // operand or a subexpression thereof the value contained in the
447 // referenced object is not accessed. Otherwise, if the glvalue
448 // has a class type, the conversion copy-initializes a temporary
449 // of type T from the glvalue and the result of the conversion
450 // is a prvalue for the temporary.
451 // FIXME: add some way to gate this entire thing for correctness in
452 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000453 if (getLangOptions().CPlusPlus && E->isGLValue() &&
454 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000455 ExprResult Temp = PerformCopyInitialization(
456 InitializedEntity::InitializeTemporary(E->getType()),
457 E->getExprLoc(),
458 Owned(E));
459 if (Temp.isInvalid())
460 return ExprError();
461 E = Temp.get();
462 }
463
John Wiegley01296292011-04-08 18:41:53 +0000464 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000465}
466
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000467/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
468/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000469/// interfaces passed by value.
470ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000471 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000472 ExprResult ExprRes = CheckPlaceholderExpr(E);
473 if (ExprRes.isInvalid())
474 return ExprError();
475
476 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000477 if (ExprRes.isInvalid())
478 return ExprError();
479 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Douglas Gregor347e0f22011-05-21 19:26:31 +0000481 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000482 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000483 DiagRuntimeBehavior(E->getLocStart(), 0,
484 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
485 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000486 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000487
John McCall31168b02011-06-15 23:02:42 +0000488 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000489 // C++0x [expr.call]p7:
490 // Passing a potentially-evaluated argument of class type (Clause 9)
491 // having a non-trivial copy constructor, a non-trivial move constructor,
492 // or a non-trivial destructor, with no corresponding parameter,
493 // is conditionally-supported with implementation-defined semantics.
494 bool TrivialEnough = false;
495 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
496 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
497 if (Record->hasTrivialCopyConstructor() &&
498 Record->hasTrivialMoveConstructor() &&
499 Record->hasTrivialDestructor())
500 TrivialEnough = true;
501 }
502 }
John McCall31168b02011-06-15 23:02:42 +0000503
504 if (!TrivialEnough &&
505 getLangOptions().ObjCAutoRefCount &&
506 E->getType()->isObjCLifetimeType())
507 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000508
509 if (TrivialEnough) {
510 // Nothing to diagnose. This is okay.
511 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000512 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000513 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000514 << CT)) {
515 // Turn this into a trap.
516 CXXScopeSpec SS;
517 UnqualifiedId Name;
518 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
519 E->getLocStart());
520 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
521 if (TrapFn.isInvalid())
522 return ExprError();
523
524 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
525 MultiExprArg(), E->getLocEnd());
526 if (Call.isInvalid())
527 return ExprError();
528
529 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
530 Call.get(), E);
531 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000532 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000533 E = Comma.get();
534 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000535 }
536
John Wiegley01296292011-04-08 18:41:53 +0000537 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000538}
539
Richard Trieu7aa58f12011-09-02 20:58:51 +0000540/// \brief Converts an integer to complex float type. Helper function of
541/// UsualArithmeticConversions()
542///
543/// \return false if the integer expression is an integer type and is
544/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000545static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
546 ExprResult &ComplexExpr,
547 QualType IntTy,
548 QualType ComplexTy,
549 bool SkipCast) {
550 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
551 if (SkipCast) return false;
552 if (IntTy->isIntegerType()) {
553 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
554 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
555 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000556 CK_FloatingRealToComplex);
557 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000558 assert(IntTy->isComplexIntegerType());
559 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000560 CK_IntegralComplexToFloatingComplex);
561 }
562 return false;
563}
564
565/// \brief Takes two complex float types and converts them to the same type.
566/// Helper function of UsualArithmeticConversions()
567static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000568handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
569 ExprResult &RHS, QualType LHSType,
570 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000571 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000572 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000573
574 if (order < 0) {
575 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000576 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000577 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
578 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000579 }
580 if (order > 0)
581 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000582 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
583 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000584}
585
586/// \brief Converts otherExpr to complex float and promotes complexExpr if
587/// necessary. Helper function of UsualArithmeticConversions()
588static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000589 ExprResult &ComplexExpr,
590 ExprResult &OtherExpr,
591 QualType ComplexTy,
592 QualType OtherTy,
593 bool ConvertComplexExpr,
594 bool ConvertOtherExpr) {
595 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000596
597 // If just the complexExpr is complex, the otherExpr needs to be converted,
598 // and the complexExpr might need to be promoted.
599 if (order > 0) { // complexExpr is wider
600 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000601 if (ConvertOtherExpr) {
602 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
603 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
604 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000605 CK_FloatingRealToComplex);
606 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000607 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000608 }
609
610 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000611 QualType result = (order == 0 ? ComplexTy :
612 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000613
614 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000615 if (ConvertOtherExpr)
616 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000617 CK_FloatingRealToComplex);
618
619 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000620 if (ConvertComplexExpr && order < 0)
621 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000622 CK_FloatingComplexCast);
623
624 return result;
625}
626
627/// \brief Handle arithmetic conversion with complex types. Helper function of
628/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000629static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
630 ExprResult &RHS, QualType LHSType,
631 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000632 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000633 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000634 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000635 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000636 return LHSType;
637 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000638 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000639 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000640
641 // This handles complex/complex, complex/float, or float/complex.
642 // When both operands are complex, the shorter operand is converted to the
643 // type of the longer, and that is the type of the result. This corresponds
644 // to what is done when combining two real floating-point operands.
645 // The fun begins when size promotion occur across type domains.
646 // From H&S 6.3.4: When one operand is complex and the other is a real
647 // floating-point type, the less precise type is converted, within it's
648 // real or complex domain, to the precision of the other type. For example,
649 // when combining a "long double" with a "double _Complex", the
650 // "double _Complex" is promoted to "long double _Complex".
651
Richard Trieu5065cdd2011-09-06 18:25:09 +0000652 bool LHSComplexFloat = LHSType->isComplexType();
653 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000654
655 // If both are complex, just cast to the more precise type.
656 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000657 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
658 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000659 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000660
661 // If only one operand is complex, promote it if necessary and convert the
662 // other operand to complex.
663 if (LHSComplexFloat)
664 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000665 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000666 /*convertOtherExpr*/ true);
667
668 assert(RHSComplexFloat);
669 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000670 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000671 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000672}
673
674/// \brief Hande arithmetic conversion from integer to float. Helper function
675/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000676static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
677 ExprResult &IntExpr,
678 QualType FloatTy, QualType IntTy,
679 bool ConvertFloat, bool ConvertInt) {
680 if (IntTy->isIntegerType()) {
681 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000682 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000683 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000684 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000685 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000686 }
687
688 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000689 assert(IntTy->isComplexIntegerType());
690 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000691
692 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000693 if (ConvertInt)
694 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000695 CK_IntegralComplexToFloatingComplex);
696
697 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000698 if (ConvertFloat)
699 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000700 CK_FloatingRealToComplex);
701
702 return result;
703}
704
705/// \brief Handle arithmethic conversion with floating point types. Helper
706/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000707static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
708 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000709 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000710 bool LHSFloat = LHSType->isRealFloatingType();
711 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000712
713 // If we have two real floating types, convert the smaller operand
714 // to the bigger result.
715 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000716 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000717 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000718 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
719 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 }
721
722 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000723 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000724 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
725 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000726 }
727
728 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000729 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000730 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000731 /*convertInt=*/ true);
732 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000733 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000734 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000735 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000736}
737
738/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000739/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000740// FIXME: if the operands are (int, _Complex long), we currently
741// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000742static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
743 ExprResult &RHS, QualType LHSType,
744 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000745 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000746 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
747 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000748
Richard Trieucfe3f212011-09-06 18:38:41 +0000749 if (LHSComplexInt && RHSComplexInt) {
750 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
751 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000752 assert(order && "inequal types with equal element ordering");
753 if (order > 0) {
754 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000755 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
756 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000757 }
758
Richard Trieuba63ce62011-09-09 01:45:06 +0000759 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000760 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
761 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000762 }
763
Richard Trieucfe3f212011-09-06 18:38:41 +0000764 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000765 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000766 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
767 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000768 }
769
Richard Trieucfe3f212011-09-06 18:38:41 +0000770 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000772 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000773 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
774 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000775}
776
777/// \brief Handle integer arithmetic conversions. Helper function of
778/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000779static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
780 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000781 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000783 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
784 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
785 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
786 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000787 // Same signedness; use the higher-ranked type
788 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000789 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
790 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000791 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000792 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
793 return RHSType;
794 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795 // The unsigned type has greater than or equal rank to the
796 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000797 if (RHSSigned) {
798 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
799 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000800 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000801 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
802 return RHSType;
803 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 // The two types are different widths; if we are here, that
805 // means the signed type is larger than the unsigned type, so
806 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000807 if (LHSSigned) {
808 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
809 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000811 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
812 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000813 } else {
814 // The signed type is higher-ranked than the unsigned type,
815 // but isn't actually any bigger (like unsigned int and long
816 // on most 32-bit systems). Use the unsigned type corresponding
817 // to the signed type.
818 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000819 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
820 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000821 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000822 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000823 return result;
824 }
825}
826
Chris Lattner513165e2008-07-25 21:10:04 +0000827/// UsualArithmeticConversions - Performs various conversions that are common to
828/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000829/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000830/// responsible for emitting appropriate error diagnostics.
831/// FIXME: verify the conversion rules for "complex int" are consistent with
832/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000833QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000834 bool IsCompAssign) {
835 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000836 LHS = UsualUnaryConversions(LHS.take());
837 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000838 return QualType();
839 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000840
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000841 RHS = UsualUnaryConversions(RHS.take());
842 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000843 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000844
Mike Stump11289f42009-09-09 15:08:12 +0000845 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000846 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000847 QualType LHSType =
848 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
849 QualType RHSType =
850 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000851
852 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000853 if (LHSType == RHSType)
854 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000855
856 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
857 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000858 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
859 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000860
John McCalld005ac92010-11-13 08:17:45 +0000861 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000862 QualType LHSUnpromotedType = LHSType;
863 if (LHSType->isPromotableIntegerType())
864 LHSType = Context.getPromotedIntegerType(LHSType);
865 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000866 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000868 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000869 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000870
John McCalld005ac92010-11-13 08:17:45 +0000871 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000872 if (LHSType == RHSType)
873 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000874
875 // At this point, we have two different arithmetic types.
876
877 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000878 if (LHSType->isComplexType() || RHSType->isComplexType())
879 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000880 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000881
882 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000883 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
884 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000885 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000886
887 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000888 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000889 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000890 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000891
892 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000893 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000894 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000895}
896
Chris Lattner513165e2008-07-25 21:10:04 +0000897//===----------------------------------------------------------------------===//
898// Semantic Analysis for various Expression Types
899//===----------------------------------------------------------------------===//
900
901
Peter Collingbourne91147592011-04-15 00:35:48 +0000902ExprResult
903Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
904 SourceLocation DefaultLoc,
905 SourceLocation RParenLoc,
906 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000907 MultiTypeArg ArgTypes,
908 MultiExprArg ArgExprs) {
909 unsigned NumAssocs = ArgTypes.size();
910 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000911
Richard Trieuba63ce62011-09-09 01:45:06 +0000912 ParsedType *ParsedTypes = ArgTypes.release();
913 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000914
915 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
916 for (unsigned i = 0; i < NumAssocs; ++i) {
917 if (ParsedTypes[i])
918 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
919 else
920 Types[i] = 0;
921 }
922
923 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
924 ControllingExpr, Types, Exprs,
925 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000926 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000927 return ER;
928}
929
930ExprResult
931Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
932 SourceLocation DefaultLoc,
933 SourceLocation RParenLoc,
934 Expr *ControllingExpr,
935 TypeSourceInfo **Types,
936 Expr **Exprs,
937 unsigned NumAssocs) {
938 bool TypeErrorFound = false,
939 IsResultDependent = ControllingExpr->isTypeDependent(),
940 ContainsUnexpandedParameterPack
941 = ControllingExpr->containsUnexpandedParameterPack();
942
943 for (unsigned i = 0; i < NumAssocs; ++i) {
944 if (Exprs[i]->containsUnexpandedParameterPack())
945 ContainsUnexpandedParameterPack = true;
946
947 if (Types[i]) {
948 if (Types[i]->getType()->containsUnexpandedParameterPack())
949 ContainsUnexpandedParameterPack = true;
950
951 if (Types[i]->getType()->isDependentType()) {
952 IsResultDependent = true;
953 } else {
954 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
955 // complete object type other than a variably modified type."
956 unsigned D = 0;
957 if (Types[i]->getType()->isIncompleteType())
958 D = diag::err_assoc_type_incomplete;
959 else if (!Types[i]->getType()->isObjectType())
960 D = diag::err_assoc_type_nonobject;
961 else if (Types[i]->getType()->isVariablyModifiedType())
962 D = diag::err_assoc_type_variably_modified;
963
964 if (D != 0) {
965 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
966 << Types[i]->getTypeLoc().getSourceRange()
967 << Types[i]->getType();
968 TypeErrorFound = true;
969 }
970
971 // C1X 6.5.1.1p2 "No two generic associations in the same generic
972 // selection shall specify compatible types."
973 for (unsigned j = i+1; j < NumAssocs; ++j)
974 if (Types[j] && !Types[j]->getType()->isDependentType() &&
975 Context.typesAreCompatible(Types[i]->getType(),
976 Types[j]->getType())) {
977 Diag(Types[j]->getTypeLoc().getBeginLoc(),
978 diag::err_assoc_compatible_types)
979 << Types[j]->getTypeLoc().getSourceRange()
980 << Types[j]->getType()
981 << Types[i]->getType();
982 Diag(Types[i]->getTypeLoc().getBeginLoc(),
983 diag::note_compat_assoc)
984 << Types[i]->getTypeLoc().getSourceRange()
985 << Types[i]->getType();
986 TypeErrorFound = true;
987 }
988 }
989 }
990 }
991 if (TypeErrorFound)
992 return ExprError();
993
994 // If we determined that the generic selection is result-dependent, don't
995 // try to compute the result expression.
996 if (IsResultDependent)
997 return Owned(new (Context) GenericSelectionExpr(
998 Context, KeyLoc, ControllingExpr,
999 Types, Exprs, NumAssocs, DefaultLoc,
1000 RParenLoc, ContainsUnexpandedParameterPack));
1001
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001002 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001003 unsigned DefaultIndex = -1U;
1004 for (unsigned i = 0; i < NumAssocs; ++i) {
1005 if (!Types[i])
1006 DefaultIndex = i;
1007 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1008 Types[i]->getType()))
1009 CompatIndices.push_back(i);
1010 }
1011
1012 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1013 // type compatible with at most one of the types named in its generic
1014 // association list."
1015 if (CompatIndices.size() > 1) {
1016 // We strip parens here because the controlling expression is typically
1017 // parenthesized in macro definitions.
1018 ControllingExpr = ControllingExpr->IgnoreParens();
1019 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1020 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1021 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001022 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001023 E = CompatIndices.end(); I != E; ++I) {
1024 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1025 diag::note_compat_assoc)
1026 << Types[*I]->getTypeLoc().getSourceRange()
1027 << Types[*I]->getType();
1028 }
1029 return ExprError();
1030 }
1031
1032 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1033 // its controlling expression shall have type compatible with exactly one of
1034 // the types named in its generic association list."
1035 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
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_no_match)
1040 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1041 return ExprError();
1042 }
1043
1044 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1045 // type name that is compatible with the type of the controlling expression,
1046 // then the result expression of the generic selection is the expression
1047 // in that generic association. Otherwise, the result expression of the
1048 // generic selection is the expression in the default generic association."
1049 unsigned ResultIndex =
1050 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1051
1052 return Owned(new (Context) GenericSelectionExpr(
1053 Context, KeyLoc, ControllingExpr,
1054 Types, Exprs, NumAssocs, DefaultLoc,
1055 RParenLoc, ContainsUnexpandedParameterPack,
1056 ResultIndex));
1057}
1058
Steve Naroff83895f72007-09-16 03:34:24 +00001059/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001060/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1061/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1062/// multiple tokens. However, the common case is that StringToks points to one
1063/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001064///
John McCalldadc5752010-08-24 06:29:42 +00001065ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001066Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001067 assert(NumStringToks && "Must have at least one string!");
1068
Chris Lattner8a24e582009-01-16 18:51:42 +00001069 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001070 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001071 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001072
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001073 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001074 for (unsigned i = 0; i != NumStringToks; ++i)
1075 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001076
Chris Lattner36fc8792008-02-11 00:02:17 +00001077 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001078 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001079 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001080 else if (Literal.isUTF16())
1081 StrTy = Context.Char16Ty;
1082 else if (Literal.isUTF32())
1083 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001084 else if (Literal.Pascal)
1085 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001086
Douglas Gregorfb65e592011-07-27 05:40:30 +00001087 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1088 if (Literal.isWide())
1089 Kind = StringLiteral::Wide;
1090 else if (Literal.isUTF8())
1091 Kind = StringLiteral::UTF8;
1092 else if (Literal.isUTF16())
1093 Kind = StringLiteral::UTF16;
1094 else if (Literal.isUTF32())
1095 Kind = StringLiteral::UTF32;
1096
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001097 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001098 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001099 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001100
Chris Lattner36fc8792008-02-11 00:02:17 +00001101 // Get an array type for the string, according to C99 6.4.5. This includes
1102 // the nul terminator character as well as the string length for pascal
1103 // strings.
1104 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001105 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001106 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner5b183d82006-11-10 05:03:26 +00001108 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001109 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001110 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001111 &StringTokLocs[0],
1112 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001113}
1114
John McCallc63de662011-02-02 13:00:07 +00001115enum CaptureResult {
1116 /// No capture is required.
1117 CR_NoCapture,
1118
1119 /// A capture is required.
1120 CR_Capture,
1121
John McCall351762c2011-02-07 10:33:21 +00001122 /// A by-ref capture is required.
1123 CR_CaptureByRef,
1124
John McCallc63de662011-02-02 13:00:07 +00001125 /// An error occurred when trying to capture the given variable.
1126 CR_Error
1127};
1128
1129/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001130///
John McCallc63de662011-02-02 13:00:07 +00001131/// \param var - the variable referenced
1132/// \param DC - the context which we couldn't capture through
1133static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001134diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001135 VarDecl *var, DeclContext *DC) {
1136 switch (S.ExprEvalContexts.back().Context) {
1137 case Sema::Unevaluated:
1138 // The argument will never be evaluated, so don't complain.
1139 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001140
John McCallc63de662011-02-02 13:00:07 +00001141 case Sema::PotentiallyEvaluated:
1142 case Sema::PotentiallyEvaluatedIfUsed:
1143 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001144
John McCallc63de662011-02-02 13:00:07 +00001145 case Sema::PotentiallyPotentiallyEvaluated:
1146 // FIXME: delay these!
1147 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001148 }
Mike Stump11289f42009-09-09 15:08:12 +00001149
John McCallc63de662011-02-02 13:00:07 +00001150 // Don't diagnose about capture if we're not actually in code right
1151 // now; in general, there are more appropriate places that will
1152 // diagnose this.
1153 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1154
John McCall92d627e2011-03-22 23:15:50 +00001155 // Certain madnesses can happen with parameter declarations, which
1156 // we want to ignore.
1157 if (isa<ParmVarDecl>(var)) {
1158 // - If the parameter still belongs to the translation unit, then
1159 // we're actually just using one parameter in the declaration of
1160 // the next. This is useful in e.g. VLAs.
1161 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1162 return CR_NoCapture;
1163
1164 // - This particular madness can happen in ill-formed default
1165 // arguments; claim it's okay and let downstream code handle it.
1166 if (S.CurContext == var->getDeclContext()->getParent())
1167 return CR_NoCapture;
1168 }
John McCallc63de662011-02-02 13:00:07 +00001169
1170 DeclarationName functionName;
1171 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1172 functionName = fn->getDeclName();
1173 // FIXME: variable from enclosing block that we couldn't capture from!
1174
1175 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1176 << var->getIdentifier() << functionName;
1177 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1178 << var->getIdentifier();
1179
1180 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001181}
1182
John McCall351762c2011-02-07 10:33:21 +00001183/// There is a well-formed capture at a particular scope level;
1184/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001185static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1186 const BlockDecl::Capture &Capture) {
1187 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001188
1189 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001190 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001191 i != e; ++i) {
1192 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1193 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001194 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1195 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001196 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1197 }
1198
Richard Trieuba63ce62011-09-09 01:45:06 +00001199 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001200}
1201
1202/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001203/// given value in the current context requires a variable capture.
1204///
1205/// This also keeps the captures set in the BlockScopeInfo records
1206/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001207static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001208 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001209 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001210 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001211 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001212
1213 // Fast path: variables from the current context never require capture.
1214 DeclContext *DC = S.CurContext;
1215 if (var->getDeclContext() == DC) return CR_NoCapture;
1216
1217 // Only variables with local storage require capture.
1218 // FIXME: What about 'const' variables in C++?
1219 if (!var->hasLocalStorage()) return CR_NoCapture;
1220
1221 // Otherwise, we need to capture.
1222
1223 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001224 do {
1225 // Only blocks (and eventually C++0x closures) can capture; other
1226 // scopes don't work.
1227 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001228 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001229
1230 BlockScopeInfo *blockScope =
1231 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1232 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1233
John McCall351762c2011-02-07 10:33:21 +00001234 // Check whether we've already captured it in this block. If so,
1235 // we're done.
1236 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1237 return propagateCapture(S, functionScopesIndex,
1238 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001239
1240 functionScopesIndex--;
1241 DC = cast<BlockDecl>(DC)->getDeclContext();
1242 } while (var->getDeclContext() != DC);
1243
John McCall351762c2011-02-07 10:33:21 +00001244 // Okay, we descended all the way to the block that defines the variable.
1245 // Actually try to capture it.
1246 QualType type = var->getType();
1247
1248 // Prohibit variably-modified types.
1249 if (type->isVariablyModifiedType()) {
1250 S.Diag(loc, diag::err_ref_vm_type);
1251 S.Diag(var->getLocation(), diag::note_declared_at);
1252 return CR_Error;
1253 }
1254
1255 // Prohibit arrays, even in __block variables, but not references to
1256 // them.
1257 if (type->isArrayType()) {
1258 S.Diag(loc, diag::err_ref_array_type);
1259 S.Diag(var->getLocation(), diag::note_declared_at);
1260 return CR_Error;
1261 }
1262
1263 S.MarkDeclarationReferenced(loc, var);
1264
1265 // The BlocksAttr indicates the variable is bound by-reference.
1266 bool byRef = var->hasAttr<BlocksAttr>();
1267
1268 // Build a copy expression.
1269 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001270 const RecordType *rtype;
1271 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1272 (rtype = type->getAs<RecordType>())) {
1273
1274 // The capture logic needs the destructor, so make sure we mark it.
1275 // Usually this is unnecessary because most local variables have
1276 // their destructors marked at declaration time, but parameters are
1277 // an exception because it's technically only the call site that
1278 // actually requires the destructor.
1279 if (isa<ParmVarDecl>(var))
1280 S.FinalizeVarWithDestructor(var, rtype);
1281
John McCall351762c2011-02-07 10:33:21 +00001282 // According to the blocks spec, the capture of a variable from
1283 // the stack requires a const copy constructor. This is not true
1284 // of the copy/move done to move a __block variable to the heap.
1285 type.addConst();
1286
1287 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1288 ExprResult result =
1289 S.PerformCopyInitialization(
1290 InitializedEntity::InitializeBlock(var->getLocation(),
1291 type, false),
1292 loc, S.Owned(declRef));
1293
1294 // Build a full-expression copy expression if initialization
1295 // succeeded and used a non-trivial constructor. Recover from
1296 // errors by pretending that the copy isn't necessary.
1297 if (!result.isInvalid() &&
1298 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1299 result = S.MaybeCreateExprWithCleanups(result);
1300 copyExpr = result.take();
1301 }
1302 }
1303
1304 // We're currently at the declarer; go back to the closure.
1305 functionScopesIndex++;
1306 BlockScopeInfo *blockScope =
1307 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1308
1309 // Build a valid capture in this scope.
1310 blockScope->Captures.push_back(
1311 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1312 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1313
1314 // Propagate that to inner captures if necessary.
1315 return propagateCapture(S, functionScopesIndex,
1316 blockScope->Captures.back());
1317}
1318
Richard Trieuba63ce62011-09-09 01:45:06 +00001319static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001320 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001321 bool ByRef) {
1322 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001323
Richard Trieuba63ce62011-09-09 01:45:06 +00001324 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001325 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001326 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001327
1328 QualType exprType = var->getType().getNonReferenceType();
1329
1330 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001331 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001332 // The variable will be bound by copy; make it const within the
1333 // closure, but record that this was done in the expression.
1334 bool constAdded = !exprType.isConstQualified();
1335 exprType.addConst();
1336
1337 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1338 NameInfo.getLoc(), false,
1339 constAdded);
1340 } else {
1341 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1342 NameInfo.getLoc(), true);
1343 }
1344
1345 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001346}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001347
John McCalldadc5752010-08-24 06:29:42 +00001348ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001349Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001350 SourceLocation Loc,
1351 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001352 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001353 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001354}
1355
John McCallf4cd4f92011-02-09 01:13:10 +00001356/// BuildDeclRefExpr - Build an expression that references a
1357/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001358ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001359Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001360 const DeclarationNameInfo &NameInfo,
1361 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001362 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001363
John McCall086a4642010-11-24 05:12:34 +00001364 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001365 SS? SS->getWithLocInContext(Context)
1366 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001367 D, NameInfo, Ty, VK);
1368
1369 // Just in case we're building an illegal pointer-to-member.
1370 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1371 E->setObjectKind(OK_BitField);
1372
1373 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001374}
1375
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001376/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001377/// possibly a list of template arguments.
1378///
1379/// If this produces template arguments, it is permitted to call
1380/// DecomposeTemplateName.
1381///
1382/// This actually loses a lot of source location information for
1383/// non-standard name kinds; we should consider preserving that in
1384/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001385void
1386Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1387 TemplateArgumentListInfo &Buffer,
1388 DeclarationNameInfo &NameInfo,
1389 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001390 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1391 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1392 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1393
Douglas Gregor5476205b2011-06-23 00:49:38 +00001394 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001395 Id.TemplateId->getTemplateArgs(),
1396 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001397 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001398 TemplateArgsPtr.release();
1399
John McCall3e56fd42010-08-23 07:28:44 +00001400 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001401 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001402 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001403 TemplateArgs = &Buffer;
1404 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001405 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001406 TemplateArgs = 0;
1407 }
1408}
1409
John McCalld681c392009-12-16 08:11:27 +00001410/// Diagnose an empty lookup.
1411///
1412/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001413bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001414 CorrectTypoContext CTC,
1415 TemplateArgumentListInfo *ExplicitTemplateArgs,
1416 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001417 DeclarationName Name = R.getLookupName();
1418
John McCalld681c392009-12-16 08:11:27 +00001419 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001420 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001421 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1422 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001423 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001424 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001425 diagnostic_suggest = diag::err_undeclared_use_suggest;
1426 }
John McCalld681c392009-12-16 08:11:27 +00001427
Douglas Gregor598b08f2009-12-31 05:20:13 +00001428 // If the original lookup was an unqualified lookup, fake an
1429 // unqualified lookup. This is useful when (for example) the
1430 // original lookup would not have found something because it was a
1431 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001432 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001433 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001434 if (isa<CXXRecordDecl>(DC)) {
1435 LookupQualifiedName(R, DC);
1436
1437 if (!R.empty()) {
1438 // Don't give errors about ambiguities in this lookup.
1439 R.suppressDiagnostics();
1440
1441 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1442 bool isInstance = CurMethod &&
1443 CurMethod->isInstance() &&
1444 DC == CurMethod->getParent();
1445
1446 // Give a code modification hint to insert 'this->'.
1447 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1448 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001449 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001450 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1451 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001452 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001453 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001454 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001455 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001456 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001457 Diag(R.getNameLoc(), diagnostic) << Name
1458 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1459 QualType DepThisType = DepMethod->getThisType(Context);
1460 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1461 R.getNameLoc(), DepThisType, false);
1462 TemplateArgumentListInfo TList;
1463 if (ULE->hasExplicitTemplateArgs())
1464 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001465
Douglas Gregore16af532011-02-28 18:50:33 +00001466 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001467 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001468 CXXDependentScopeMemberExpr *DepExpr =
1469 CXXDependentScopeMemberExpr::Create(
1470 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001471 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001472 R.getLookupNameInfo(),
1473 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001474 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001475 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001476 // FIXME: we should be able to handle this case too. It is correct
1477 // to add this-> here. This is a workaround for PR7947.
1478 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001479 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001480 } else {
John McCalld681c392009-12-16 08:11:27 +00001481 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001482 }
John McCalld681c392009-12-16 08:11:27 +00001483
1484 // Do we really want to note all of these?
1485 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1486 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1487
1488 // Tell the callee to try to recover.
1489 return false;
1490 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001491
1492 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001493 }
1494 }
1495
Douglas Gregor598b08f2009-12-31 05:20:13 +00001496 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001497 TypoCorrection Corrected;
1498 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1499 S, &SS, NULL, false, CTC))) {
1500 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1501 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1502 R.setLookupName(Corrected.getCorrection());
1503
Hans Wennborg38198de2011-07-12 08:45:31 +00001504 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001505 if (Corrected.isOverloaded()) {
1506 OverloadCandidateSet OCS(R.getNameLoc());
1507 OverloadCandidateSet::iterator Best;
1508 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1509 CDEnd = Corrected.end();
1510 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001511 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001512 dyn_cast<FunctionTemplateDecl>(*CD))
1513 AddTemplateOverloadCandidate(
1514 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1515 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001516 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1517 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1518 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1519 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001520 }
1521 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1522 case OR_Success:
1523 ND = Best->Function;
1524 break;
1525 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001526 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001527 }
1528 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001529 R.addDecl(ND);
1530 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001531 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001532 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1533 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001534 else
1535 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001536 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001537 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001538 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1539 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001540 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001541 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001542
1543 // Tell the callee to try to recover.
1544 return false;
1545 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001546
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001547 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001548 // FIXME: If we ended up with a typo for a type name or
1549 // Objective-C class name, we're in trouble because the parser
1550 // is in the wrong place to recover. Suggest the typo
1551 // correction, but don't make it a fix-it since we're not going
1552 // to recover well anyway.
1553 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001554 Diag(R.getNameLoc(), diagnostic_suggest)
1555 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001556 else
1557 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001558 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001559 << SS.getRange();
1560
1561 // Don't try to recover; it won't work.
1562 return true;
1563 }
1564 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001565 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001566 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001567 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001568 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001569 else
Douglas Gregor25363982010-01-01 00:15:04 +00001570 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001571 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001572 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001573 return true;
1574 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001575 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001576 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001577
1578 // Emit a special diagnostic for failed member lookups.
1579 // FIXME: computing the declaration context might fail here (?)
1580 if (!SS.isEmpty()) {
1581 Diag(R.getNameLoc(), diag::err_no_member)
1582 << Name << computeDeclContext(SS, false)
1583 << SS.getRange();
1584 return true;
1585 }
1586
John McCalld681c392009-12-16 08:11:27 +00001587 // Give up, we can't recover.
1588 Diag(R.getNameLoc(), diagnostic) << Name;
1589 return true;
1590}
1591
John McCalldadc5752010-08-24 06:29:42 +00001592ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001593 CXXScopeSpec &SS,
1594 UnqualifiedId &Id,
1595 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001596 bool IsAddressOfOperand) {
1597 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001598 "cannot be direct & operand and have a trailing lparen");
1599
1600 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001601 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001602
John McCall10eae182009-11-30 22:42:35 +00001603 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001604
1605 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001606 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001607 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001608 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001609
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001610 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001611 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001612 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001613
John McCalle66edc12009-11-24 19:00:30 +00001614 // C++ [temp.dep.expr]p3:
1615 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001616 // -- an identifier that was declared with a dependent type,
1617 // (note: handled after lookup)
1618 // -- a template-id that is dependent,
1619 // (note: handled in BuildTemplateIdExpr)
1620 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001621 // -- a nested-name-specifier that contains a class-name that
1622 // names a dependent type.
1623 // Determine whether this is a member of an unknown specialization;
1624 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001625 bool DependentID = false;
1626 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1627 Name.getCXXNameType()->isDependentType()) {
1628 DependentID = true;
1629 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001630 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001631 if (RequireCompleteDeclContext(SS, DC))
1632 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001633 } else {
1634 DependentID = true;
1635 }
1636 }
1637
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001638 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001639 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001640 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001641
Fariborz Jahanian86151342010-07-22 23:33:21 +00001642 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001643 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001644 LookupResult R(*this, NameInfo,
1645 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1646 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001647 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001648 // Lookup the template name again to correctly establish the context in
1649 // which it was found. This is really unfortunate as we already did the
1650 // lookup to determine that it was a template name in the first place. If
1651 // this becomes a performance hit, we can work harder to preserve those
1652 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001653 bool MemberOfUnknownSpecialization;
1654 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1655 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001656
1657 if (MemberOfUnknownSpecialization ||
1658 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001659 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001660 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001661 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001662 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001663 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001664
Douglas Gregora5226932011-02-04 13:35:07 +00001665 // If the result might be in a dependent base class, this is a dependent
1666 // id-expression.
1667 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001668 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001669 TemplateArgs);
1670
John McCalle66edc12009-11-24 19:00:30 +00001671 // If this reference is in an Objective-C method, then we need to do
1672 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001673 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001674 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001675 if (E.isInvalid())
1676 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001678 if (Expr *Ex = E.takeAs<Expr>())
1679 return Owned(Ex);
1680
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001681 // for further use, this must be set to false if in class method.
1682 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001683 }
Chris Lattner59a25942008-03-31 00:36:02 +00001684 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001685
John McCalle66edc12009-11-24 19:00:30 +00001686 if (R.isAmbiguous())
1687 return ExprError();
1688
Douglas Gregor171c45a2009-02-18 21:56:37 +00001689 // Determine whether this name might be a candidate for
1690 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001691 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001692
John McCalle66edc12009-11-24 19:00:30 +00001693 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001694 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001695 // in C90, extension in C99, forbidden in C++).
1696 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1697 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1698 if (D) R.addDecl(D);
1699 }
1700
1701 // If this name wasn't predeclared and if this is not a function
1702 // call, diagnose the problem.
1703 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001704
1705 // In Microsoft mode, if we are inside a template class member function
1706 // and we can't resolve an identifier then assume the identifier is type
1707 // dependent. The goal is to postpone name lookup to instantiation time
1708 // to be able to search into type dependent base classes.
1709 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1710 isa<CXXMethodDecl>(CurContext))
1711 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1712 TemplateArgs);
1713
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001714 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001715 return ExprError();
1716
1717 assert(!R.empty() &&
1718 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001719
1720 // If we found an Objective-C instance variable, let
1721 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001722 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001723 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1724 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001725 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001726 // In a hopelessly buggy code, Objective-C instance variable
1727 // lookup fails and no expression will be built to reference it.
1728 if (!E.isInvalid() && !E.get())
1729 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001730 return move(E);
1731 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001732 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001733 }
Mike Stump11289f42009-09-09 15:08:12 +00001734
John McCalle66edc12009-11-24 19:00:30 +00001735 // This is guaranteed from this point on.
1736 assert(!R.empty() || ADL);
1737
John McCall2d74de92009-12-01 22:10:20 +00001738 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001739 // C++ [class.mfct.non-static]p3:
1740 // When an id-expression that is not part of a class member access
1741 // syntax and not used to form a pointer to member is used in the
1742 // body of a non-static member function of class X, if name lookup
1743 // resolves the name in the id-expression to a non-static non-type
1744 // member of some class C, the id-expression is transformed into a
1745 // class member access expression using (*this) as the
1746 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001747 //
1748 // But we don't actually need to do this for '&' operands if R
1749 // resolved to a function or overloaded function set, because the
1750 // expression is ill-formed if it actually works out to be a
1751 // non-static member function:
1752 //
1753 // C++ [expr.ref]p4:
1754 // Otherwise, if E1.E2 refers to a non-static member function. . .
1755 // [t]he expression can be used only as the left-hand operand of a
1756 // member function call.
1757 //
1758 // There are other safeguards against such uses, but it's important
1759 // to get this right here so that we don't end up making a
1760 // spuriously dependent expression if we're inside a dependent
1761 // instance method.
John McCall57500772009-12-16 12:17:52 +00001762 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001763 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001764 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001765 MightBeImplicitMember = true;
1766 else if (!SS.isEmpty())
1767 MightBeImplicitMember = false;
1768 else if (R.isOverloadedResult())
1769 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001770 else if (R.isUnresolvableResult())
1771 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001772 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001773 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1774 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001775
1776 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001777 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001778 }
1779
John McCalle66edc12009-11-24 19:00:30 +00001780 if (TemplateArgs)
1781 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001782
John McCalle66edc12009-11-24 19:00:30 +00001783 return BuildDeclarationNameExpr(SS, R, ADL);
1784}
1785
John McCall10eae182009-11-30 22:42:35 +00001786/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1787/// declaration name, generally during template instantiation.
1788/// There's a large number of things which don't need to be done along
1789/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001790ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001791Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001792 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001793 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001794 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001795 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001796
John McCall0b66eb32010-05-01 00:40:08 +00001797 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001798 return ExprError();
1799
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001800 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001801 LookupQualifiedName(R, DC);
1802
1803 if (R.isAmbiguous())
1804 return ExprError();
1805
1806 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001807 Diag(NameInfo.getLoc(), diag::err_no_member)
1808 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001809 return ExprError();
1810 }
1811
1812 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1813}
1814
1815/// LookupInObjCMethod - The parser has read a name in, and Sema has
1816/// detected that we're currently inside an ObjC method. Perform some
1817/// additional lookup.
1818///
1819/// Ideally, most of this would be done by lookup, but there's
1820/// actually quite a lot of extra work involved.
1821///
1822/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001823ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001824Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001825 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001826 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001827 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001828
John McCalle66edc12009-11-24 19:00:30 +00001829 // There are two cases to handle here. 1) scoped lookup could have failed,
1830 // in which case we should look for an ivar. 2) scoped lookup could have
1831 // found a decl, but that decl is outside the current instance method (i.e.
1832 // a global variable). In these two cases, we do a lookup for an ivar with
1833 // this name, if the lookup sucedes, we replace it our current decl.
1834
1835 // If we're in a class method, we don't normally want to look for
1836 // ivars. But if we don't find anything else, and there's an
1837 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001838 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001839
1840 bool LookForIvars;
1841 if (Lookup.empty())
1842 LookForIvars = true;
1843 else if (IsClassMethod)
1844 LookForIvars = false;
1845 else
1846 LookForIvars = (Lookup.isSingleResult() &&
1847 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001848 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001849 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001850 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001851 ObjCInterfaceDecl *ClassDeclared;
1852 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1853 // Diagnose using an ivar in a class method.
1854 if (IsClassMethod)
1855 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1856 << IV->getDeclName());
1857
1858 // If we're referencing an invalid decl, just return this as a silent
1859 // error node. The error diagnostic was already emitted on the decl.
1860 if (IV->isInvalidDecl())
1861 return ExprError();
1862
1863 // Check if referencing a field with __attribute__((deprecated)).
1864 if (DiagnoseUseOfDecl(IV, Loc))
1865 return ExprError();
1866
1867 // Diagnose the use of an ivar outside of the declaring class.
1868 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1869 ClassDeclared != IFace)
1870 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1871
1872 // FIXME: This should use a new expr for a direct reference, don't
1873 // turn this into Self->ivar, just return a BareIVarExpr or something.
1874 IdentifierInfo &II = Context.Idents.get("self");
1875 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001876 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001877 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001878 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001879 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001880 SelfName, false, false);
1881 if (SelfExpr.isInvalid())
1882 return ExprError();
1883
John Wiegley01296292011-04-08 18:41:53 +00001884 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1885 if (SelfExpr.isInvalid())
1886 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001887
John McCalle66edc12009-11-24 19:00:30 +00001888 MarkDeclarationReferenced(Loc, IV);
1889 return Owned(new (Context)
1890 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001891 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001892 }
Chris Lattner87313662010-04-12 05:10:17 +00001893 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001894 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001895 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001896 ObjCInterfaceDecl *ClassDeclared;
1897 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1898 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1899 IFace == ClassDeclared)
1900 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1901 }
1902 }
1903
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001904 if (Lookup.empty() && II && AllowBuiltinCreation) {
1905 // FIXME. Consolidate this with similar code in LookupName.
1906 if (unsigned BuiltinID = II->getBuiltinID()) {
1907 if (!(getLangOptions().CPlusPlus &&
1908 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1909 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1910 S, Lookup.isForRedeclaration(),
1911 Lookup.getNameLoc());
1912 if (D) Lookup.addDecl(D);
1913 }
1914 }
1915 }
John McCalle66edc12009-11-24 19:00:30 +00001916 // Sentinel value saying that we didn't do anything special.
1917 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001918}
John McCalld14a8642009-11-21 08:51:07 +00001919
John McCall16df1e52010-03-30 21:47:33 +00001920/// \brief Cast a base object to a member's actual type.
1921///
1922/// Logically this happens in three phases:
1923///
1924/// * First we cast from the base type to the naming class.
1925/// The naming class is the class into which we were looking
1926/// when we found the member; it's the qualifier type if a
1927/// qualifier was provided, and otherwise it's the base type.
1928///
1929/// * Next we cast from the naming class to the declaring class.
1930/// If the member we found was brought into a class's scope by
1931/// a using declaration, this is that class; otherwise it's
1932/// the class declaring the member.
1933///
1934/// * Finally we cast from the declaring class to the "true"
1935/// declaring class of the member. This conversion does not
1936/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001937ExprResult
1938Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001939 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001940 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 NamedDecl *Member) {
1942 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1943 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001944 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001945
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 QualType DestRecordType;
1947 QualType DestType;
1948 QualType FromRecordType;
1949 QualType FromType = From->getType();
1950 bool PointerConversions = false;
1951 if (isa<FieldDecl>(Member)) {
1952 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001953
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001954 if (FromType->getAs<PointerType>()) {
1955 DestType = Context.getPointerType(DestRecordType);
1956 FromRecordType = FromType->getPointeeType();
1957 PointerConversions = true;
1958 } else {
1959 DestType = DestRecordType;
1960 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001961 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001962 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1963 if (Method->isStatic())
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 DestType = Method->getThisType(Context);
1967 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001968
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001969 if (FromType->getAs<PointerType>()) {
1970 FromRecordType = FromType->getPointeeType();
1971 PointerConversions = true;
1972 } else {
1973 FromRecordType = FromType;
1974 DestType = DestRecordType;
1975 }
1976 } else {
1977 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001978 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001979 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001980
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001981 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001982 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001984 // If the unqualified types are the same, no conversion is necessary.
1985 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001986 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001987
John McCall16df1e52010-03-30 21:47:33 +00001988 SourceRange FromRange = From->getSourceRange();
1989 SourceLocation FromLoc = FromRange.getBegin();
1990
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001991 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001992
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001993 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001994 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 // class name.
1996 //
1997 // If the member was a qualified name and the qualified referred to a
1998 // specific base subobject type, we'll cast to that intermediate type
1999 // first and then to the object in which the member is declared. That allows
2000 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2001 //
2002 // class Base { public: int x; };
2003 // class Derived1 : public Base { };
2004 // class Derived2 : public Base { };
2005 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2006 //
2007 // void VeryDerived::f() {
2008 // x = 17; // error: ambiguous base subobjects
2009 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2010 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002011 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002012 QualType QType = QualType(Qualifier->getAsType(), 0);
2013 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2014 assert(QType->isRecordType() && "lookup done with non-record type");
2015
2016 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2017
2018 // In C++98, the qualifier type doesn't actually have to be a base
2019 // type of the object type, in which case we just ignore it.
2020 // Otherwise build the appropriate casts.
2021 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002022 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002023 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002024 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002025 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002026
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002027 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002028 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002029 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2030 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002031
2032 FromType = QType;
2033 FromRecordType = QRecordType;
2034
2035 // If the qualifier type was the same as the destination type,
2036 // we're done.
2037 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002038 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002039 }
2040 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002041
John McCall16df1e52010-03-30 21:47:33 +00002042 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002043
John McCall16df1e52010-03-30 21:47:33 +00002044 // If we actually found the member through a using declaration, cast
2045 // down to the using declaration's type.
2046 //
2047 // Pointer equality is fine here because only one declaration of a
2048 // class ever has member declarations.
2049 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2050 assert(isa<UsingShadowDecl>(FoundDecl));
2051 QualType URecordType = Context.getTypeDeclType(
2052 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2053
2054 // We only need to do this if the naming-class to declaring-class
2055 // conversion is non-trivial.
2056 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2057 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002058 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002059 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002060 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002061 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002062
John McCall16df1e52010-03-30 21:47:33 +00002063 QualType UType = URecordType;
2064 if (PointerConversions)
2065 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002066 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2067 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002068 FromType = UType;
2069 FromRecordType = URecordType;
2070 }
2071
2072 // We don't do access control for the conversion from the
2073 // declaring class to the true declaring class.
2074 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002076
John McCallcf142162010-08-07 06:22:56 +00002077 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002078 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2079 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002080 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002081 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002082
John Wiegley01296292011-04-08 18:41:53 +00002083 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2084 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002085}
Douglas Gregor3256d042009-06-30 15:47:41 +00002086
John McCalle66edc12009-11-24 19:00:30 +00002087bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002088 const LookupResult &R,
2089 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002090 // Only when used directly as the postfix-expression of a call.
2091 if (!HasTrailingLParen)
2092 return false;
2093
2094 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002095 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002096 return false;
2097
2098 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002099 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002100 return false;
2101
2102 // Turn off ADL when we find certain kinds of declarations during
2103 // normal lookup:
2104 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2105 NamedDecl *D = *I;
2106
2107 // C++0x [basic.lookup.argdep]p3:
2108 // -- a declaration of a class member
2109 // Since using decls preserve this property, we check this on the
2110 // original decl.
John McCall57500772009-12-16 12:17:52 +00002111 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002112 return false;
2113
2114 // C++0x [basic.lookup.argdep]p3:
2115 // -- a block-scope function declaration that is not a
2116 // using-declaration
2117 // NOTE: we also trigger this for function templates (in fact, we
2118 // don't check the decl type at all, since all other decl types
2119 // turn off ADL anyway).
2120 if (isa<UsingShadowDecl>(D))
2121 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2122 else if (D->getDeclContext()->isFunctionOrMethod())
2123 return false;
2124
2125 // C++0x [basic.lookup.argdep]p3:
2126 // -- a declaration that is neither a function or a function
2127 // template
2128 // And also for builtin functions.
2129 if (isa<FunctionDecl>(D)) {
2130 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2131
2132 // But also builtin functions.
2133 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2134 return false;
2135 } else if (!isa<FunctionTemplateDecl>(D))
2136 return false;
2137 }
2138
2139 return true;
2140}
2141
2142
John McCalld14a8642009-11-21 08:51:07 +00002143/// Diagnoses obvious problems with the use of the given declaration
2144/// as an expression. This is only actually called for lookups that
2145/// were not overloaded, and it doesn't promise that the declaration
2146/// will in fact be used.
2147static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002148 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002149 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2150 return true;
2151 }
2152
2153 if (isa<ObjCInterfaceDecl>(D)) {
2154 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2155 return true;
2156 }
2157
2158 if (isa<NamespaceDecl>(D)) {
2159 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2160 return true;
2161 }
2162
2163 return false;
2164}
2165
John McCalldadc5752010-08-24 06:29:42 +00002166ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002167Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002168 LookupResult &R,
2169 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002170 // If this is a single, fully-resolved result and we don't need ADL,
2171 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002172 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002173 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2174 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002175
2176 // We only need to check the declaration if there's exactly one
2177 // result, because in the overloaded case the results can only be
2178 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002179 if (R.isSingleResult() &&
2180 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002181 return ExprError();
2182
John McCall58cc69d2010-01-27 01:50:18 +00002183 // Otherwise, just build an unresolved lookup expression. Suppress
2184 // any lookup-related diagnostics; we'll hash these out later, when
2185 // we've picked a target.
2186 R.suppressDiagnostics();
2187
John McCalld14a8642009-11-21 08:51:07 +00002188 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002189 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002190 SS.getWithLocInContext(Context),
2191 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002192 NeedsADL, R.isOverloadedResult(),
2193 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002194
2195 return Owned(ULE);
2196}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002197
John McCalld14a8642009-11-21 08:51:07 +00002198/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002199ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002200Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002201 const DeclarationNameInfo &NameInfo,
2202 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002203 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002204 assert(!isa<FunctionTemplateDecl>(D) &&
2205 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002206
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002207 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002208 if (CheckDeclInExpr(*this, Loc, D))
2209 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002210
Douglas Gregore7488b92009-12-01 16:58:18 +00002211 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2212 // Specifically diagnose references to class templates that are missing
2213 // a template argument list.
2214 Diag(Loc, diag::err_template_decl_ref)
2215 << Template << SS.getRange();
2216 Diag(Template->getLocation(), diag::note_template_decl_here);
2217 return ExprError();
2218 }
2219
2220 // Make sure that we're referring to a value.
2221 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2222 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002223 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002224 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002225 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002226 return ExprError();
2227 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002228
Douglas Gregor171c45a2009-02-18 21:56:37 +00002229 // Check whether this declaration can be used. Note that we suppress
2230 // this check when we're going to perform argument-dependent lookup
2231 // on this function name, because this might not be the function
2232 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002233 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002234 return ExprError();
2235
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002236 // Only create DeclRefExpr's for valid Decl's.
2237 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002238 return ExprError();
2239
John McCallf3a88602011-02-03 08:15:49 +00002240 // Handle members of anonymous structs and unions. If we got here,
2241 // and the reference is to a class member indirect field, then this
2242 // must be the subject of a pointer-to-member expression.
2243 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2244 if (!indirectField->isCXXClassMember())
2245 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2246 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002247
Chris Lattner2a9d9892008-10-20 05:16:36 +00002248 // If the identifier reference is inside a block, and it refers to a value
2249 // that is outside the block, create a BlockDeclRefExpr instead of a
2250 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2251 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002252 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002253 // We do not do this for things like enum constants, global variables, etc,
2254 // as they do not get snapshotted.
2255 //
John McCall351762c2011-02-07 10:33:21 +00002256 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002257 case CR_Error:
2258 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002259
John McCallc63de662011-02-02 13:00:07 +00002260 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002261 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2262 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2263
2264 case CR_CaptureByRef:
2265 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2266 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002267
2268 case CR_NoCapture: {
2269 // If this reference is not in a block or if the referenced
2270 // variable is within the block, create a normal DeclRefExpr.
2271
2272 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002273 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002274
2275 switch (D->getKind()) {
2276 // Ignore all the non-ValueDecl kinds.
2277#define ABSTRACT_DECL(kind)
2278#define VALUE(type, base)
2279#define DECL(type, base) \
2280 case Decl::type:
2281#include "clang/AST/DeclNodes.inc"
2282 llvm_unreachable("invalid value decl kind");
2283 return ExprError();
2284
2285 // These shouldn't make it here.
2286 case Decl::ObjCAtDefsField:
2287 case Decl::ObjCIvar:
2288 llvm_unreachable("forming non-member reference to ivar?");
2289 return ExprError();
2290
2291 // Enum constants are always r-values and never references.
2292 // Unresolved using declarations are dependent.
2293 case Decl::EnumConstant:
2294 case Decl::UnresolvedUsingValue:
2295 valueKind = VK_RValue;
2296 break;
2297
2298 // Fields and indirect fields that got here must be for
2299 // pointer-to-member expressions; we just call them l-values for
2300 // internal consistency, because this subexpression doesn't really
2301 // exist in the high-level semantics.
2302 case Decl::Field:
2303 case Decl::IndirectField:
2304 assert(getLangOptions().CPlusPlus &&
2305 "building reference to field in C?");
2306
2307 // These can't have reference type in well-formed programs, but
2308 // for internal consistency we do this anyway.
2309 type = type.getNonReferenceType();
2310 valueKind = VK_LValue;
2311 break;
2312
2313 // Non-type template parameters are either l-values or r-values
2314 // depending on the type.
2315 case Decl::NonTypeTemplateParm: {
2316 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2317 type = reftype->getPointeeType();
2318 valueKind = VK_LValue; // even if the parameter is an r-value reference
2319 break;
2320 }
2321
2322 // For non-references, we need to strip qualifiers just in case
2323 // the template parameter was declared as 'const int' or whatever.
2324 valueKind = VK_RValue;
2325 type = type.getUnqualifiedType();
2326 break;
2327 }
2328
2329 case Decl::Var:
2330 // In C, "extern void blah;" is valid and is an r-value.
2331 if (!getLangOptions().CPlusPlus &&
2332 !type.hasQualifiers() &&
2333 type->isVoidType()) {
2334 valueKind = VK_RValue;
2335 break;
2336 }
2337 // fallthrough
2338
2339 case Decl::ImplicitParam:
2340 case Decl::ParmVar:
2341 // These are always l-values.
2342 valueKind = VK_LValue;
2343 type = type.getNonReferenceType();
2344 break;
2345
2346 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002347 const FunctionType *fty = type->castAs<FunctionType>();
2348
2349 // If we're referring to a function with an __unknown_anytype
2350 // result type, make the entire expression __unknown_anytype.
2351 if (fty->getResultType() == Context.UnknownAnyTy) {
2352 type = Context.UnknownAnyTy;
2353 valueKind = VK_RValue;
2354 break;
2355 }
2356
John McCallf4cd4f92011-02-09 01:13:10 +00002357 // Functions are l-values in C++.
2358 if (getLangOptions().CPlusPlus) {
2359 valueKind = VK_LValue;
2360 break;
2361 }
2362
2363 // C99 DR 316 says that, if a function type comes from a
2364 // function definition (without a prototype), that type is only
2365 // used for checking compatibility. Therefore, when referencing
2366 // the function, we pretend that we don't have the full function
2367 // type.
John McCall2979fe02011-04-12 00:42:48 +00002368 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2369 isa<FunctionProtoType>(fty))
2370 type = Context.getFunctionNoProtoType(fty->getResultType(),
2371 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002372
2373 // Functions are r-values in C.
2374 valueKind = VK_RValue;
2375 break;
2376 }
2377
2378 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002379 // If we're referring to a method with an __unknown_anytype
2380 // result type, make the entire expression __unknown_anytype.
2381 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002382 if (const FunctionProtoType *proto
2383 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002384 if (proto->getResultType() == Context.UnknownAnyTy) {
2385 type = Context.UnknownAnyTy;
2386 valueKind = VK_RValue;
2387 break;
2388 }
2389
John McCallf4cd4f92011-02-09 01:13:10 +00002390 // C++ methods are l-values if static, r-values if non-static.
2391 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2392 valueKind = VK_LValue;
2393 break;
2394 }
2395 // fallthrough
2396
2397 case Decl::CXXConversion:
2398 case Decl::CXXDestructor:
2399 case Decl::CXXConstructor:
2400 valueKind = VK_RValue;
2401 break;
2402 }
2403
2404 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2405 }
2406
John McCallc63de662011-02-02 13:00:07 +00002407 }
John McCall7decc9e2010-11-18 06:31:45 +00002408
John McCall351762c2011-02-07 10:33:21 +00002409 llvm_unreachable("unknown capture result");
2410 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002411}
Chris Lattnere168f762006-11-10 05:29:30 +00002412
John McCall2979fe02011-04-12 00:42:48 +00002413ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002414 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002415
Chris Lattnere168f762006-11-10 05:29:30 +00002416 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002417 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002418 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2419 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2420 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002421 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002422
Chris Lattnera81a0272008-01-12 08:14:25 +00002423 // Pre-defined identifiers are of type char[x], where x is the length of the
2424 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002425
Anders Carlsson2fb08242009-09-08 18:24:21 +00002426 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002427 if (!currentDecl && getCurBlock())
2428 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002429 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002430 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002431 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002432 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002433
Anders Carlsson0b209a82009-09-11 01:22:35 +00002434 QualType ResTy;
2435 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2436 ResTy = Context.DependentTy;
2437 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002438 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002439
Anders Carlsson0b209a82009-09-11 01:22:35 +00002440 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002441 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002442 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2443 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002444 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002445}
2446
John McCalldadc5752010-08-24 06:29:42 +00002447ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002448 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002449 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002450 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002451 if (Invalid)
2452 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002453
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002454 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002455 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002456 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002457 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002458
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002459 QualType Ty;
2460 if (!getLangOptions().CPlusPlus)
2461 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2462 else if (Literal.isWide())
2463 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002464 else if (Literal.isUTF16())
2465 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2466 else if (Literal.isUTF32())
2467 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002468 else if (Literal.isMultiChar())
2469 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002470 else
2471 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002472
Douglas Gregorfb65e592011-07-27 05:40:30 +00002473 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2474 if (Literal.isWide())
2475 Kind = CharacterLiteral::Wide;
2476 else if (Literal.isUTF16())
2477 Kind = CharacterLiteral::UTF16;
2478 else if (Literal.isUTF32())
2479 Kind = CharacterLiteral::UTF32;
2480
2481 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2482 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002483}
2484
John McCalldadc5752010-08-24 06:29:42 +00002485ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002486 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002487 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2488 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002489 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002490 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002491 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002492 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002493 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002494
Chris Lattner23b7eb62007-06-15 23:05:46 +00002495 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002496 // Add padding so that NumericLiteralParser can overread by one character.
2497 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002498 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002499
Chris Lattner67ca9252007-05-21 01:08:44 +00002500 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002501 bool Invalid = false;
2502 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2503 if (Invalid)
2504 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002505
Mike Stump11289f42009-09-09 15:08:12 +00002506 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002507 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002508 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002509 return ExprError();
2510
Chris Lattner1c20a172007-08-26 03:42:43 +00002511 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512
Chris Lattner1c20a172007-08-26 03:42:43 +00002513 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002514 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002515 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002516 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002517 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002518 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002519 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002520 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002521
2522 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2523
John McCall53b93a02009-12-24 09:08:04 +00002524 using llvm::APFloat;
2525 APFloat Val(Format);
2526
2527 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002528
2529 // Overflow is always an error, but underflow is only an error if
2530 // we underflowed to zero (APFloat reports denormals as underflow).
2531 if ((result & APFloat::opOverflow) ||
2532 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002533 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002534 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002535 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002536 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002537 APFloat::getLargest(Format).toString(buffer);
2538 } else {
John McCall62abc942010-02-26 23:35:57 +00002539 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002540 APFloat::getSmallest(Format).toString(buffer);
2541 }
2542
2543 Diag(Tok.getLocation(), diagnostic)
2544 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002545 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002546 }
2547
2548 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002549 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002551 if (Ty == Context.DoubleTy) {
2552 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002553 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002554 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2555 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002556 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002557 }
2558 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002559 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002560 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002561 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002562 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002563
Neil Boothac582c52007-08-29 22:00:19 +00002564 // long long is a C99 feature.
2565 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002566 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002567 Diag(Tok.getLocation(), diag::ext_longlong);
2568
Chris Lattner67ca9252007-05-21 01:08:44 +00002569 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002570 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 if (Literal.GetIntegerValue(ResultVal)) {
2573 // If this value didn't fit into uintmax_t, warn and force to ull.
2574 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002575 Ty = Context.UnsignedLongLongTy;
2576 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002577 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002578 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002579 // If this value fits into a ULL, try to figure out what else it fits into
2580 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2583 // be an unsigned int.
2584 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2585
2586 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002587 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002588 if (!Literal.isLong && !Literal.isLongLong) {
2589 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002590 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002591
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 // Does it fit in a unsigned int?
2593 if (ResultVal.isIntN(IntSize)) {
2594 // Does it fit in a signed int?
2595 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002596 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002597 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002598 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002599 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002600 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002601 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002602
Chris Lattner67ca9252007-05-21 01:08:44 +00002603 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002604 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002605 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002606
Chris Lattner67ca9252007-05-21 01:08:44 +00002607 // Does it fit in a unsigned long?
2608 if (ResultVal.isIntN(LongSize)) {
2609 // Does it fit in a signed long?
2610 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002611 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002613 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002614 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002615 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002616 }
2617
Chris Lattner67ca9252007-05-21 01:08:44 +00002618 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002619 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002620 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002621
Chris Lattner67ca9252007-05-21 01:08:44 +00002622 // Does it fit in a unsigned long long?
2623 if (ResultVal.isIntN(LongLongSize)) {
2624 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002625 // To be compatible with MSVC, hex integer literals ending with the
2626 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002627 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002628 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002629 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002630 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002632 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002633 }
2634 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002635
Chris Lattner67ca9252007-05-21 01:08:44 +00002636 // If we still couldn't decide a type, we probably have something that
2637 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002638 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002640 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002641 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002643
Chris Lattner55258cf2008-05-09 05:59:00 +00002644 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002645 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002646 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002647 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002648 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002649
Chris Lattner1c20a172007-08-26 03:42:43 +00002650 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2651 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002652 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002653 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002654
2655 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002656}
2657
Richard Trieuba63ce62011-09-09 01:45:06 +00002658ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002659 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002660 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002661}
2662
Chandler Carruth62da79c2011-05-26 08:53:12 +00002663static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2664 SourceLocation Loc,
2665 SourceRange ArgRange) {
2666 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2667 // scalar or vector data type argument..."
2668 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2669 // type (C99 6.2.5p18) or void.
2670 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2671 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2672 << T << ArgRange;
2673 return true;
2674 }
2675
2676 assert((T->isVoidType() || !T->isIncompleteType()) &&
2677 "Scalar types should always be complete");
2678 return false;
2679}
2680
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002681static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2682 SourceLocation Loc,
2683 SourceRange ArgRange,
2684 UnaryExprOrTypeTrait TraitKind) {
2685 // C99 6.5.3.4p1:
2686 if (T->isFunctionType()) {
2687 // alignof(function) is allowed as an extension.
2688 if (TraitKind == UETT_SizeOf)
2689 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2690 return false;
2691 }
2692
2693 // Allow sizeof(void)/alignof(void) as an extension.
2694 if (T->isVoidType()) {
2695 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2696 return false;
2697 }
2698
2699 return true;
2700}
2701
2702static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2703 SourceLocation Loc,
2704 SourceRange ArgRange,
2705 UnaryExprOrTypeTrait TraitKind) {
2706 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2707 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2708 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2709 << T << (TraitKind == UETT_SizeOf)
2710 << ArgRange;
2711 return true;
2712 }
2713
2714 return false;
2715}
2716
Chandler Carruth14502c22011-05-26 08:53:10 +00002717/// \brief Check the constrains on expression operands to unary type expression
2718/// and type traits.
2719///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002720/// Completes any types necessary and validates the constraints on the operand
2721/// expression. The logic mostly mirrors the type-based overload, but may modify
2722/// the expression as it completes the type for that expression through template
2723/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002724bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002725 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002726 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002727
2728 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2729 // the result is the size of the referenced type."
2730 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2731 // result shall be the alignment of the referenced type."
2732 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2733 ExprTy = Ref->getPointeeType();
2734
2735 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002736 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2737 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002738
2739 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002740 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2741 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002742 return false;
2743
Richard Trieuba63ce62011-09-09 01:45:06 +00002744 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002745 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002746 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002747 std::make_pair(SourceLocation(), PDiag(0))))
2748 return true;
2749
2750 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002751 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002752 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2753 ExprTy = Ref->getPointeeType();
2754
Richard Trieuba63ce62011-09-09 01:45:06 +00002755 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2756 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002757 return true;
2758
Nico Weber0870deb2011-06-15 02:47:03 +00002759 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002760 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002761 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2762 QualType OType = PVD->getOriginalType();
2763 QualType Type = PVD->getType();
2764 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002765 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002766 << Type << OType;
2767 Diag(PVD->getLocation(), diag::note_declared_at);
2768 }
2769 }
2770 }
2771 }
2772
Chandler Carruth7c430c02011-05-27 01:33:31 +00002773 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002774}
2775
2776/// \brief Check the constraints on operands to unary expression and type
2777/// traits.
2778///
2779/// This will complete any types necessary, and validate the various constraints
2780/// on those operands.
2781///
Steve Naroff71b59a92007-06-04 22:22:31 +00002782/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002783/// C99 6.3.2.1p[2-4] all state:
2784/// Except when it is the operand of the sizeof operator ...
2785///
2786/// C++ [expr.sizeof]p4
2787/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2788/// standard conversions are not applied to the operand of sizeof.
2789///
2790/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002791bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002792 SourceLocation OpLoc,
2793 SourceRange ExprRange,
2794 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002795 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002796 return false;
2797
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002798 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2799 // the result is the size of the referenced type."
2800 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2801 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002802 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2803 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002804
Chandler Carruth62da79c2011-05-26 08:53:12 +00002805 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002806 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002807
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002808 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002809 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002810 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002811 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002812
Richard Trieuba63ce62011-09-09 01:45:06 +00002813 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002814 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002815 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002816 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002817
Richard Trieuba63ce62011-09-09 01:45:06 +00002818 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002819 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002820 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002821
Chris Lattner62975a72009-04-24 00:30:45 +00002822 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002823}
2824
Chandler Carruth14502c22011-05-26 08:53:10 +00002825static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002826 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002827
Mike Stump11289f42009-09-09 15:08:12 +00002828 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002829 if (isa<DeclRefExpr>(E))
2830 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002831
2832 // Cannot know anything else if the expression is dependent.
2833 if (E->isTypeDependent())
2834 return false;
2835
Douglas Gregor71235ec2009-05-02 02:18:30 +00002836 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002837 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2838 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002839 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002840 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002841
2842 // Alignment of a field access is always okay, so long as it isn't a
2843 // bit-field.
2844 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002845 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002846 return false;
2847
Chandler Carruth14502c22011-05-26 08:53:10 +00002848 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002849}
2850
Chandler Carruth14502c22011-05-26 08:53:10 +00002851bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852 E = E->IgnoreParens();
2853
2854 // Cannot know anything else if the expression is dependent.
2855 if (E->isTypeDependent())
2856 return false;
2857
Chandler Carruth14502c22011-05-26 08:53:10 +00002858 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002859}
2860
Douglas Gregor0950e412009-03-13 21:01:28 +00002861/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002862ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002863Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2864 SourceLocation OpLoc,
2865 UnaryExprOrTypeTrait ExprKind,
2866 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002867 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002868 return ExprError();
2869
John McCallbcd03502009-12-07 02:54:59 +00002870 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002871
Douglas Gregor0950e412009-03-13 21:01:28 +00002872 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002873 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002874 return ExprError();
2875
2876 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002877 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2878 Context.getSizeType(),
2879 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002880}
2881
2882/// \brief Build a sizeof or alignof expression given an expression
2883/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002884ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002885Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2886 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002887 ExprResult PE = CheckPlaceholderExpr(E);
2888 if (PE.isInvalid())
2889 return ExprError();
2890
2891 E = PE.get();
2892
Douglas Gregor0950e412009-03-13 21:01:28 +00002893 // Verify that the operand is valid.
2894 bool isInvalid = false;
2895 if (E->isTypeDependent()) {
2896 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002898 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002899 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002900 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002901 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002902 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002903 isInvalid = true;
2904 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002905 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 }
2907
2908 if (isInvalid)
2909 return ExprError();
2910
2911 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002912 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002913 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002914 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002915}
2916
Peter Collingbournee190dee2011-03-11 19:24:49 +00002917/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2918/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002919/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002920ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002921Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002922 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002923 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002924 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002925 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002926
Richard Trieuba63ce62011-09-09 01:45:06 +00002927 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002928 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002929 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002930 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002931 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002932
Douglas Gregor0950e412009-03-13 21:01:28 +00002933 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002934 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002935 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002936}
2937
John Wiegley01296292011-04-08 18:41:53 +00002938static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002939 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002940 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002941 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002942
John McCall34376a62010-12-04 03:47:34 +00002943 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002944 if (V.get()->getObjectKind() != OK_Ordinary) {
2945 V = S.DefaultLvalueConversion(V.take());
2946 if (V.isInvalid())
2947 return QualType();
2948 }
John McCall34376a62010-12-04 03:47:34 +00002949
Chris Lattnere267f5d2007-08-26 05:39:26 +00002950 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002951 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002952 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002953
Chris Lattnere267f5d2007-08-26 05:39:26 +00002954 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002955 if (V.get()->getType()->isArithmeticType())
2956 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002957
John McCall36226622010-10-12 02:09:17 +00002958 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002959 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002960 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002961 if (PR.get() != V.get()) {
2962 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002963 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002964 }
2965
Chris Lattnere267f5d2007-08-26 05:39:26 +00002966 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002967 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002968 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002969 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002970}
2971
2972
Chris Lattnere168f762006-11-10 05:29:30 +00002973
John McCalldadc5752010-08-24 06:29:42 +00002974ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002975Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002976 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002977 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002978 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002979 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002980 case tok::plusplus: Opc = UO_PostInc; break;
2981 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002982 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002983
John McCallb268a282010-08-23 23:25:46 +00002984 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002985}
2986
John McCalldadc5752010-08-24 06:29:42 +00002987ExprResult
John McCallb268a282010-08-23 23:25:46 +00002988Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2989 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002990 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002991 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002992 if (Result.isInvalid()) return ExprError();
2993 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002994
John McCallb268a282010-08-23 23:25:46 +00002995 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002996
Douglas Gregor40412ac2008-11-19 17:17:41 +00002997 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002998 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002999 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003000 Context.DependentTy,
3001 VK_LValue, OK_Ordinary,
3002 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003003 }
3004
Mike Stump11289f42009-09-09 15:08:12 +00003005 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003006 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003007 LHSExp->getType()->isEnumeralType() ||
3008 RHSExp->getType()->isRecordType() ||
3009 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003010 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003011 }
3012
John McCallb268a282010-08-23 23:25:46 +00003013 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003014}
3015
3016
John McCalldadc5752010-08-24 06:29:42 +00003017ExprResult
John McCallb268a282010-08-23 23:25:46 +00003018Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003019 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003020 Expr *LHSExp = Base;
3021 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003022
Chris Lattner36d572b2007-07-16 00:14:47 +00003023 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003024 if (!LHSExp->getType()->getAs<VectorType>()) {
3025 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3026 if (Result.isInvalid())
3027 return ExprError();
3028 LHSExp = Result.take();
3029 }
3030 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3031 if (Result.isInvalid())
3032 return ExprError();
3033 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003034
Chris Lattner36d572b2007-07-16 00:14:47 +00003035 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003036 ExprValueKind VK = VK_LValue;
3037 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003038
Steve Naroffc1aadb12007-03-28 21:49:40 +00003039 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003040 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003041 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003042 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003043 Expr *BaseExpr, *IndexExpr;
3044 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003045 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3046 BaseExpr = LHSExp;
3047 IndexExpr = RHSExp;
3048 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003049 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003050 BaseExpr = LHSExp;
3051 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003052 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003053 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003054 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 BaseExpr = RHSExp;
3056 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003057 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003058 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003059 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003060 BaseExpr = LHSExp;
3061 IndexExpr = RHSExp;
3062 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003063 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003064 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003065 // Handle the uncommon case of "123[Ptr]".
3066 BaseExpr = RHSExp;
3067 IndexExpr = LHSExp;
3068 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003069 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003070 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003071 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003072 VK = LHSExp->getValueKind();
3073 if (VK != VK_RValue)
3074 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003075
Chris Lattner36d572b2007-07-16 00:14:47 +00003076 // FIXME: need to deal with const...
3077 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003078 } else if (LHSTy->isArrayType()) {
3079 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003080 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003081 // wasn't promoted because of the C90 rule that doesn't
3082 // allow promoting non-lvalue arrays. Warn, then
3083 // force the promotion here.
3084 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3085 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003086 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3087 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003088 LHSTy = LHSExp->getType();
3089
3090 BaseExpr = LHSExp;
3091 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003092 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003093 } else if (RHSTy->isArrayType()) {
3094 // Same as previous, except for 123[f().a] case
3095 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3096 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003097 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3098 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003099 RHSTy = RHSExp->getType();
3100
3101 BaseExpr = RHSExp;
3102 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003103 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003104 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003105 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3106 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003107 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003108 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003109 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003110 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3111 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003112
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003113 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003114 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3115 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003116 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3117
Douglas Gregorac1fb652009-03-24 19:52:54 +00003118 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003119 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3120 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003121 // incomplete types are not object types.
3122 if (ResultType->isFunctionType()) {
3123 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3124 << ResultType << BaseExpr->getSourceRange();
3125 return ExprError();
3126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003128 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3129 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003130 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3131 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003132
3133 // C forbids expressions of unqualified void type from being l-values.
3134 // See IsCForbiddenLValueType.
3135 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003136 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003137 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003138 PDiag(diag::err_subscript_incomplete_type)
3139 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003140 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003141
Chris Lattner62975a72009-04-24 00:30:45 +00003142 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003143 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003144 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3145 << ResultType << BaseExpr->getSourceRange();
3146 return ExprError();
3147 }
Mike Stump11289f42009-09-09 15:08:12 +00003148
John McCall4bc41ae2010-11-18 19:01:18 +00003149 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003150 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003151
Mike Stump4e1f26a2009-02-19 03:04:26 +00003152 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003153 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003154}
3155
John McCalldadc5752010-08-24 06:29:42 +00003156ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003157 FunctionDecl *FD,
3158 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003159 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003160 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003161 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003162 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003163 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003164 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003165 return ExprError();
3166 }
3167
3168 if (Param->hasUninstantiatedDefaultArg()) {
3169 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003170
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003171 // Instantiate the expression.
3172 MultiLevelTemplateArgumentList ArgList
3173 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003174
Nico Weber44887f62010-11-29 18:19:25 +00003175 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003176 = ArgList.getInnermost();
3177 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3178 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003179
Nico Weber44887f62010-11-29 18:19:25 +00003180 ExprResult Result;
3181 {
3182 // C++ [dcl.fct.default]p5:
3183 // The names in the [default argument] expression are bound, and
3184 // the semantic constraints are checked, at the point where the
3185 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003186 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003187 Result = SubstExpr(UninstExpr, ArgList);
3188 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003189 if (Result.isInvalid())
3190 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003192 // Check the expression as an initializer for the parameter.
3193 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003194 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003195 InitializationKind Kind
3196 = InitializationKind::CreateCopy(Param->getLocation(),
3197 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3198 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003199
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003200 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3201 Result = InitSeq.Perform(*this, Entity, Kind,
3202 MultiExprArg(*this, &ResultE, 1));
3203 if (Result.isInvalid())
3204 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003205
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003206 // Build the default argument expression.
3207 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3208 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003209 }
3210
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003211 // If the default expression creates temporaries, we need to
3212 // push them to the current stack of expression temporaries so they'll
3213 // be properly destroyed.
3214 // FIXME: We should really be rebuilding the default argument with new
3215 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003216 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3217 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3218 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3219 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3220 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003221 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003222 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003223
3224 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003225 // Just mark all of the declarations in this potentially-evaluated expression
3226 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003227 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003228 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003229}
3230
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003231/// ConvertArgumentsForCall - Converts the arguments specified in
3232/// Args/NumArgs to the parameter types of the function FDecl with
3233/// function prototype Proto. Call is the call expression itself, and
3234/// Fn is the function expression. For a C++ member function, this
3235/// routine does not attempt to convert the object argument. Returns
3236/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003237bool
3238Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003239 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003240 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003241 Expr **Args, unsigned NumArgs,
3242 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003243 // Bail out early if calling a builtin with custom typechecking.
3244 // We don't need to do this in the
3245 if (FDecl)
3246 if (unsigned ID = FDecl->getBuiltinID())
3247 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3248 return false;
3249
Mike Stump4e1f26a2009-02-19 03:04:26 +00003250 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003251 // assignment, to the types of the corresponding parameter, ...
3252 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003253 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003254
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003255 // If too few arguments are available (and we don't have default
3256 // arguments for the remaining parameters), don't make the call.
3257 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003258 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3259 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003260 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003261 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003262
3263 // Emit the location of the prototype.
3264 if (FDecl && !FDecl->getBuiltinID())
3265 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3266 << FDecl;
3267
3268 return true;
3269 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003270 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003271 }
3272
3273 // If too many are passed and not variadic, error on the extras and drop
3274 // them.
3275 if (NumArgs > NumArgsInProto) {
3276 if (!Proto->isVariadic()) {
3277 Diag(Args[NumArgsInProto]->getLocStart(),
3278 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003279 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003280 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003281 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3282 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003283
3284 // Emit the location of the prototype.
3285 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003286 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3287 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003288
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003289 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003290 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003291 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003292 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003293 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003294 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003295 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003296 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3297 if (Fn->getType()->isBlockPointerType())
3298 CallType = VariadicBlock; // Block
3299 else if (isa<MemberExpr>(Fn))
3300 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003301 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003302 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003303 if (Invalid)
3304 return true;
3305 unsigned TotalNumArgs = AllArgs.size();
3306 for (unsigned i = 0; i < TotalNumArgs; ++i)
3307 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003308
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003309 return false;
3310}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003311
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003312bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3313 FunctionDecl *FDecl,
3314 const FunctionProtoType *Proto,
3315 unsigned FirstProtoArg,
3316 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003317 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003318 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003319 unsigned NumArgsInProto = Proto->getNumArgs();
3320 unsigned NumArgsToCheck = NumArgs;
3321 bool Invalid = false;
3322 if (NumArgs != NumArgsInProto)
3323 // Use default arguments for missing arguments
3324 NumArgsToCheck = NumArgsInProto;
3325 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003326 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003327 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003328 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003329
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003330 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003331 if (ArgIx < NumArgs) {
3332 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003333
Eli Friedman3164fb12009-03-22 22:00:50 +00003334 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3335 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003336 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003337 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003338 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003339
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003340 // Pass the argument
3341 ParmVarDecl *Param = 0;
3342 if (FDecl && i < FDecl->getNumParams())
3343 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003344
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003345 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003346 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003347 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3348 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003349 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003350 SourceLocation(),
3351 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003352 if (ArgE.isInvalid())
3353 return true;
3354
3355 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003356 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003357 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003358
John McCalldadc5752010-08-24 06:29:42 +00003359 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003360 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003361 if (ArgExpr.isInvalid())
3362 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003363
Anders Carlsson355933d2009-08-25 03:49:14 +00003364 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003365 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003366
3367 // Check for array bounds violations for each argument to the call. This
3368 // check only triggers warnings when the argument isn't a more complex Expr
3369 // with its own checking, such as a BinaryOperator.
3370 CheckArrayAccess(Arg);
3371
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003372 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003373 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003374
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003375 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003376 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003377
3378 // Assume that extern "C" functions with variadic arguments that
3379 // return __unknown_anytype aren't *really* variadic.
3380 if (Proto->getResultType() == Context.UnknownAnyTy &&
3381 FDecl && FDecl->isExternC()) {
3382 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3383 ExprResult arg;
3384 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3385 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3386 else
3387 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3388 Invalid |= arg.isInvalid();
3389 AllArgs.push_back(arg.take());
3390 }
3391
3392 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3393 } else {
3394 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003395 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3396 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003397 Invalid |= Arg.isInvalid();
3398 AllArgs.push_back(Arg.take());
3399 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003400 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003401
3402 // Check for array bounds violations.
3403 for (unsigned i = ArgIx; i != NumArgs; ++i)
3404 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003406 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003407}
3408
John McCall2979fe02011-04-12 00:42:48 +00003409/// Given a function expression of unknown-any type, try to rebuild it
3410/// to have a function type.
3411static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3412
Steve Naroff83895f72007-09-16 03:34:24 +00003413/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003414/// This provides the location of the left/right parens and a list of comma
3415/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003416ExprResult
John McCallb268a282010-08-23 23:25:46 +00003417Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003418 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003419 Expr *ExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003420 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003421
3422 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003423 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003424 if (Result.isInvalid()) return ExprError();
3425 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003426
Richard Trieuba63ce62011-09-09 01:45:06 +00003427 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003429 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003430 // If this is a pseudo-destructor expression, build the call immediately.
3431 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3432 if (NumArgs > 0) {
3433 // Pseudo-destructor calls should not have any arguments.
3434 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003435 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003436 SourceRange(Args[0]->getLocStart(),
3437 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003438
Douglas Gregorad8a3362009-09-04 17:36:40 +00003439 NumArgs = 0;
3440 }
Mike Stump11289f42009-09-09 15:08:12 +00003441
Douglas Gregorad8a3362009-09-04 17:36:40 +00003442 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003443 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003444 }
Mike Stump11289f42009-09-09 15:08:12 +00003445
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003446 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003447 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003448 // FIXME: Will need to cache the results of name lookup (including ADL) in
3449 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003450 bool Dependent = false;
3451 if (Fn->isTypeDependent())
3452 Dependent = true;
3453 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3454 Dependent = true;
3455
Peter Collingbourne41f85462011-02-09 21:07:24 +00003456 if (Dependent) {
3457 if (ExecConfig) {
3458 return Owned(new (Context) CUDAKernelCallExpr(
3459 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3460 Context.DependentTy, VK_RValue, RParenLoc));
3461 } else {
3462 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3463 Context.DependentTy, VK_RValue,
3464 RParenLoc));
3465 }
3466 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003467
3468 // Determine whether this is a call to an object (C++ [over.call.object]).
3469 if (Fn->getType()->isRecordType())
3470 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003471 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003472
John McCall2979fe02011-04-12 00:42:48 +00003473 if (Fn->getType() == Context.UnknownAnyTy) {
3474 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3475 if (result.isInvalid()) return ExprError();
3476 Fn = result.take();
3477 }
3478
John McCall0009fcc2011-04-26 20:42:42 +00003479 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003480 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003481 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003482 }
John McCall0009fcc2011-04-26 20:42:42 +00003483 }
John McCall10eae182009-11-30 22:42:35 +00003484
John McCall0009fcc2011-04-26 20:42:42 +00003485 // Check for overloaded calls. This can happen even in C due to extensions.
3486 if (Fn->getType() == Context.OverloadTy) {
3487 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3488
3489 // We aren't supposed to apply this logic if there's an '&' involved.
3490 if (!find.IsAddressOfOperand) {
3491 OverloadExpr *ovl = find.Expression;
3492 if (isa<UnresolvedLookupExpr>(ovl)) {
3493 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3494 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3495 RParenLoc, ExecConfig);
3496 } else {
John McCall2d74de92009-12-01 22:10:20 +00003497 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003498 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003499 }
3500 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003501 }
3502
Douglas Gregore254f902009-02-04 00:32:51 +00003503 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003504
Eli Friedmane14b1992009-12-26 03:35:45 +00003505 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003506
John McCall57500772009-12-16 12:17:52 +00003507 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003508 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3509 if (UnOp->getOpcode() == UO_AddrOf)
3510 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3511
John McCall57500772009-12-16 12:17:52 +00003512 if (isa<DeclRefExpr>(NakedFn))
3513 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003514 else if (isa<MemberExpr>(NakedFn))
3515 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003516
Peter Collingbourne41f85462011-02-09 21:07:24 +00003517 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3518 ExecConfig);
3519}
3520
3521ExprResult
3522Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003523 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003524 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3525 if (!ConfigDecl)
3526 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3527 << "cudaConfigureCall");
3528 QualType ConfigQTy = ConfigDecl->getType();
3529
3530 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3531 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3532
Richard Trieuba63ce62011-09-09 01:45:06 +00003533 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003534}
3535
Tanya Lattner55808c12011-06-04 00:47:47 +00003536/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3537///
3538/// __builtin_astype( value, dst type )
3539///
Richard Trieuba63ce62011-09-09 01:45:06 +00003540ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003541 SourceLocation BuiltinLoc,
3542 SourceLocation RParenLoc) {
3543 ExprValueKind VK = VK_RValue;
3544 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003545 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3546 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003547 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3548 return ExprError(Diag(BuiltinLoc,
3549 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003550 << DstTy
3551 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003552 << E->getSourceRange());
3553 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003554 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003555}
3556
John McCall57500772009-12-16 12:17:52 +00003557/// BuildResolvedCallExpr - Build a call to a resolved expression,
3558/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003559/// unary-convert to an expression of function-pointer or
3560/// block-pointer type.
3561///
3562/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003563ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003564Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3565 SourceLocation LParenLoc,
3566 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003567 SourceLocation RParenLoc,
3568 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003569 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3570
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003571 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003572 ExprResult Result = UsualUnaryConversions(Fn);
3573 if (Result.isInvalid())
3574 return ExprError();
3575 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003576
Chris Lattner08464942007-12-28 05:29:59 +00003577 // Make the call expr early, before semantic checks. This guarantees cleanup
3578 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003579 CallExpr *TheCall;
3580 if (Config) {
3581 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3582 cast<CallExpr>(Config),
3583 Args, NumArgs,
3584 Context.BoolTy,
3585 VK_RValue,
3586 RParenLoc);
3587 } else {
3588 TheCall = new (Context) CallExpr(Context, Fn,
3589 Args, NumArgs,
3590 Context.BoolTy,
3591 VK_RValue,
3592 RParenLoc);
3593 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003594
John McCallbebede42011-02-26 05:39:39 +00003595 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3596
3597 // Bail out early if calling a builtin with custom typechecking.
3598 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3599 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3600
John McCall31996342011-04-07 08:22:57 +00003601 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003602 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003603 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003604 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3605 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003606 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003607 if (FuncT == 0)
3608 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3609 << Fn->getType() << Fn->getSourceRange());
3610 } else if (const BlockPointerType *BPT =
3611 Fn->getType()->getAs<BlockPointerType>()) {
3612 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3613 } else {
John McCall31996342011-04-07 08:22:57 +00003614 // Handle calls to expressions of unknown-any type.
3615 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003616 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003617 if (rewrite.isInvalid()) return ExprError();
3618 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003619 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003620 goto retry;
3621 }
3622
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003623 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3624 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003625 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003626
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003627 if (getLangOptions().CUDA) {
3628 if (Config) {
3629 // CUDA: Kernel calls must be to global functions
3630 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3631 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3632 << FDecl->getName() << Fn->getSourceRange());
3633
3634 // CUDA: Kernel function must have 'void' return type
3635 if (!FuncT->getResultType()->isVoidType())
3636 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3637 << Fn->getType() << Fn->getSourceRange());
3638 }
3639 }
3640
Eli Friedman3164fb12009-03-22 22:00:50 +00003641 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003642 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003643 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003644 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003645 return ExprError();
3646
Chris Lattner08464942007-12-28 05:29:59 +00003647 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003648 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003649 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003650
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003651 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003652 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003653 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003654 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003655 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003656 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003657
Douglas Gregord8e97de2009-04-02 15:37:10 +00003658 if (FDecl) {
3659 // Check if we have too few/too many template arguments, based
3660 // on our knowledge of the function definition.
3661 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003662 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003663 const FunctionProtoType *Proto
3664 = Def->getType()->getAs<FunctionProtoType>();
3665 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003666 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3667 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003668 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003669
3670 // If the function we're calling isn't a function prototype, but we have
3671 // a function prototype from a prior declaratiom, use that prototype.
3672 if (!FDecl->hasPrototype())
3673 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003674 }
3675
Steve Naroff0b661582007-08-28 23:30:39 +00003676 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003677 for (unsigned i = 0; i != NumArgs; i++) {
3678 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003679
3680 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003681 InitializedEntity Entity
3682 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003683 Proto->getArgType(i),
3684 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003685 ExprResult ArgE = PerformCopyInitialization(Entity,
3686 SourceLocation(),
3687 Owned(Arg));
3688 if (ArgE.isInvalid())
3689 return true;
3690
3691 Arg = ArgE.takeAs<Expr>();
3692
3693 } else {
John Wiegley01296292011-04-08 18:41:53 +00003694 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3695
3696 if (ArgE.isInvalid())
3697 return true;
3698
3699 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003700 }
3701
Douglas Gregor83025412010-10-26 05:45:40 +00003702 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3703 Arg->getType(),
3704 PDiag(diag::err_call_incomplete_argument)
3705 << Arg->getSourceRange()))
3706 return ExprError();
3707
Chris Lattner08464942007-12-28 05:29:59 +00003708 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003709 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003710 }
Chris Lattner08464942007-12-28 05:29:59 +00003711
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003712 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3713 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003714 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3715 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003716
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003717 // Check for sentinels
3718 if (NDecl)
3719 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003720
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003721 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003722 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003723 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003724 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003725
John McCallbebede42011-02-26 05:39:39 +00003726 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003727 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003728 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003729 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003730 return ExprError();
3731 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003732
John McCallb268a282010-08-23 23:25:46 +00003733 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003734}
3735
John McCalldadc5752010-08-24 06:29:42 +00003736ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003737Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003738 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003739 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003740 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003741 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003742
3743 TypeSourceInfo *TInfo;
3744 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3745 if (!TInfo)
3746 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3747
John McCallb268a282010-08-23 23:25:46 +00003748 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003749}
3750
John McCalldadc5752010-08-24 06:29:42 +00003751ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003752Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003753 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003754 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003755
Eli Friedman37a186d2008-05-20 05:22:08 +00003756 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003757 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3758 PDiag(diag::err_illegal_decl_array_incomplete_type)
3759 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003760 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003761 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003762 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003763 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003764 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003765 } else if (!literalType->isDependentType() &&
3766 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003767 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003768 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003769 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003770 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003771
Douglas Gregor85dabae2009-12-16 01:38:02 +00003772 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003773 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003774 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003775 = InitializationKind::CreateCStyleCast(LParenLoc,
3776 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003777 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003778 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003779 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003780 &literalType);
3781 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003782 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003783 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003784
Chris Lattner79413952008-12-04 23:50:19 +00003785 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003786 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003787 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003788 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003789 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003790
John McCall7decc9e2010-11-18 06:31:45 +00003791 // In C, compound literals are l-values for some reason.
3792 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3793
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003794 return MaybeBindToTemporary(
3795 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003796 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003797}
3798
John McCalldadc5752010-08-24 06:29:42 +00003799ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003800Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003801 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003802 unsigned NumInit = InitArgList.size();
3803 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003804
Steve Naroff30d242c2007-09-15 18:49:24 +00003805 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003806 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003807
Ted Kremenekac034612010-04-13 23:39:13 +00003808 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3809 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003810 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003811 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003812}
3813
John McCallcd78e802011-09-10 01:16:55 +00003814/// Do an explicit extend of the given block pointer if we're in ARC.
3815static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3816 assert(E.get()->getType()->isBlockPointerType());
3817 assert(E.get()->isRValue());
3818
3819 // Only do this in an r-value context.
3820 if (!S.getLangOptions().ObjCAutoRefCount) return;
3821
3822 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003823 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003824 /*base path*/ 0, VK_RValue);
3825 S.ExprNeedsCleanups = true;
3826}
3827
3828/// Prepare a conversion of the given expression to an ObjC object
3829/// pointer type.
3830CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3831 QualType type = E.get()->getType();
3832 if (type->isObjCObjectPointerType()) {
3833 return CK_BitCast;
3834 } else if (type->isBlockPointerType()) {
3835 maybeExtendBlockObject(*this, E);
3836 return CK_BlockPointerToObjCPointerCast;
3837 } else {
3838 assert(type->isPointerType());
3839 return CK_CPointerToObjCPointerCast;
3840 }
3841}
3842
John McCalld7646252010-11-14 08:17:51 +00003843/// Prepares for a scalar cast, performing all the necessary stages
3844/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003845static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003846 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3847 // Also, callers should have filtered out the invalid cases with
3848 // pointers. Everything else should be possible.
3849
John Wiegley01296292011-04-08 18:41:53 +00003850 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003851 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003852 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003853
John McCall9320b872011-09-09 05:25:32 +00003854 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003855 case Type::STK_MemberPointer:
3856 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003857
John McCall9320b872011-09-09 05:25:32 +00003858 case Type::STK_CPointer:
3859 case Type::STK_BlockPointer:
3860 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003861 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003862 case Type::STK_CPointer:
3863 return CK_BitCast;
3864 case Type::STK_BlockPointer:
3865 return (SrcKind == Type::STK_BlockPointer
3866 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3867 case Type::STK_ObjCObjectPointer:
3868 if (SrcKind == Type::STK_ObjCObjectPointer)
3869 return CK_BitCast;
3870 else if (SrcKind == Type::STK_CPointer)
3871 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003872 else {
3873 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003874 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003875 }
John McCall8cb679e2010-11-15 09:13:47 +00003876 case Type::STK_Bool:
3877 return CK_PointerToBoolean;
3878 case Type::STK_Integral:
3879 return CK_PointerToIntegral;
3880 case Type::STK_Floating:
3881 case Type::STK_FloatingComplex:
3882 case Type::STK_IntegralComplex:
3883 case Type::STK_MemberPointer:
3884 llvm_unreachable("illegal cast from pointer");
3885 }
3886 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003887
John McCall8cb679e2010-11-15 09:13:47 +00003888 case Type::STK_Bool: // casting from bool is like casting from an integer
3889 case Type::STK_Integral:
3890 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003891 case Type::STK_CPointer:
3892 case Type::STK_ObjCObjectPointer:
3893 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003894 if (Src.get()->isNullPointerConstant(S.Context,
3895 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003896 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003897 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003898 case Type::STK_Bool:
3899 return CK_IntegralToBoolean;
3900 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003901 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003902 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003903 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003904 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003905 Src = S.ImpCastExprToType(Src.take(),
3906 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003907 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003908 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003909 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003910 Src = S.ImpCastExprToType(Src.take(),
3911 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003912 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003913 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003914 case Type::STK_MemberPointer:
3915 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003916 }
3917 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003918
John McCall8cb679e2010-11-15 09:13:47 +00003919 case Type::STK_Floating:
3920 switch (DestTy->getScalarTypeKind()) {
3921 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003922 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003923 case Type::STK_Bool:
3924 return CK_FloatingToBoolean;
3925 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003926 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003927 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003928 Src = S.ImpCastExprToType(Src.take(),
3929 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003930 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003931 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003932 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003933 Src = S.ImpCastExprToType(Src.take(),
3934 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003935 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003936 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003937 case Type::STK_CPointer:
3938 case Type::STK_ObjCObjectPointer:
3939 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003940 llvm_unreachable("valid float->pointer cast?");
3941 case Type::STK_MemberPointer:
3942 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003943 }
3944 break;
3945
John McCall8cb679e2010-11-15 09:13:47 +00003946 case Type::STK_FloatingComplex:
3947 switch (DestTy->getScalarTypeKind()) {
3948 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003949 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003950 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003951 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003952 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003953 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003954 if (S.Context.hasSameType(ET, DestTy))
3955 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003956 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003957 return CK_FloatingCast;
3958 }
John McCall8cb679e2010-11-15 09:13:47 +00003959 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003960 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003961 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003962 Src = S.ImpCastExprToType(Src.take(),
3963 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003964 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003965 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00003966 case Type::STK_CPointer:
3967 case Type::STK_ObjCObjectPointer:
3968 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003969 llvm_unreachable("valid complex float->pointer cast?");
3970 case Type::STK_MemberPointer:
3971 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003972 }
3973 break;
3974
John McCall8cb679e2010-11-15 09:13:47 +00003975 case Type::STK_IntegralComplex:
3976 switch (DestTy->getScalarTypeKind()) {
3977 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003978 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003979 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003980 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003981 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003982 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003983 if (S.Context.hasSameType(ET, DestTy))
3984 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003985 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003986 return CK_IntegralCast;
3987 }
John McCall8cb679e2010-11-15 09:13:47 +00003988 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003989 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003990 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003991 Src = S.ImpCastExprToType(Src.take(),
3992 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003993 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003994 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00003995 case Type::STK_CPointer:
3996 case Type::STK_ObjCObjectPointer:
3997 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003998 llvm_unreachable("valid complex int->pointer cast?");
3999 case Type::STK_MemberPointer:
4000 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004001 }
4002 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004003 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004004
John McCalld7646252010-11-14 08:17:51 +00004005 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004006}
4007
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004008/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004009ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4010 SourceRange TypeRange, QualType CastType,
4011 Expr *CastExpr, CastKind &Kind,
4012 ExprValueKind &VK, CXXCastPath &BasePath,
4013 bool FunctionalStyle) {
4014 if (CastExpr->getType() == Context.UnknownAnyTy)
4015 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4016 BasePath);
John McCall31996342011-04-07 08:22:57 +00004017
Sebastian Redl9f831db2009-07-25 15:41:38 +00004018 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004019 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004020 CastExpr->getLocEnd()),
4021 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004022 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004023
Richard Trieuba63ce62011-09-09 01:45:06 +00004024 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004025
John McCall7decc9e2010-11-18 06:31:45 +00004026 // We only support r-value casts in C.
4027 VK = VK_RValue;
4028
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004029 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4030 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004031 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004032 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004033 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004034 if (castExprRes.isInvalid())
4035 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004036 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004037
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004038 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004039 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004040 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004041 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004042
Richard Trieuba63ce62011-09-09 01:45:06 +00004043 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004044 if (castExprRes.isInvalid())
4045 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004046 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004047
Richard Trieuba63ce62011-09-09 01:45:06 +00004048 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004049 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004050 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004051
Richard Trieuba63ce62011-09-09 01:45:06 +00004052 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4053 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4054 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004055 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004056 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004057 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4058 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004059 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004060 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004061 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004062
Richard Trieuba63ce62011-09-09 01:45:06 +00004063 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004064 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004065 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004066 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004067 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004068 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004069 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004070 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004071 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004072 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4073 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004074 break;
4075 }
4076 }
John Wiegley01296292011-04-08 18:41:53 +00004077 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004078 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4079 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004080 return ExprError();
4081 }
John McCalle3027922010-08-25 11:45:40 +00004082 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004083 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004084 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004085
Anders Carlsson525b76b2009-10-16 02:48:28 +00004086 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004087 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4088 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004089 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004090 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004091
John McCalld7646252010-11-14 08:17:51 +00004092 // The type we're casting to is known to be a scalar or vector.
4093
4094 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004095 if (!CastExpr->getType()->isScalarType() &&
4096 !CastExpr->getType()->isVectorType()) {
4097 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004098 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004099 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004100 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004101 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004102
Richard Trieuba63ce62011-09-09 01:45:06 +00004103 if (CastType->isExtVectorType())
4104 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004105
Richard Trieuba63ce62011-09-09 01:45:06 +00004106 if (CastType->isVectorType()) {
4107 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004108 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004109 (CastExpr->getType()->isIntegerType() ||
4110 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004111 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004112 return Owned(CastExpr);
4113 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4114 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004115 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004116 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004117 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004118 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004119 if (CastExpr->getType()->isVectorType()) {
4120 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004121 return ExprError();
4122 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004123 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004124 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004125
John McCalld7646252010-11-14 08:17:51 +00004126 // The source and target types are both scalars, i.e.
4127 // - arithmetic types (fundamental, enum, and complex)
4128 // - all kinds of pointers
4129 // Note that member pointers were filtered out with C++, above.
4130
Richard Trieuba63ce62011-09-09 01:45:06 +00004131 if (isa<ObjCSelectorExpr>(CastExpr)) {
4132 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004133 return ExprError();
4134 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004135
John McCalld7646252010-11-14 08:17:51 +00004136 // If either type is a pointer, the other type has to be either an
4137 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004138 QualType CastExprType = CastExpr->getType();
4139 if (!CastType->isArithmeticType()) {
4140 if (!CastExprType->isIntegralType(Context) &&
4141 CastExprType->isArithmeticType()) {
4142 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004143 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004144 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004145 return ExprError();
4146 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004147 } else if (!CastExpr->getType()->isArithmeticType()) {
4148 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4149 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4150 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004151 return ExprError();
4152 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004153 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004154
John McCall31168b02011-06-15 23:02:42 +00004155 if (getLangOptions().ObjCAutoRefCount) {
4156 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004157 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4158 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004159
Richard Trieuba63ce62011-09-09 01:45:06 +00004160 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4161 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004162 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4163 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4164 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4165 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4166 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004167 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004168 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004169 << CastExprType << CastType << AA_Casting
4170 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004171
4172 return ExprError();
4173 }
4174 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004175 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004176 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4177 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004178 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004179 << CastExprType << CastType
4180 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004181 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004182 }
4183 }
4184
Richard Trieuba63ce62011-09-09 01:45:06 +00004185 castExprRes = Owned(CastExpr);
4186 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004187 if (castExprRes.isInvalid())
4188 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004189 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004190
John McCalld7646252010-11-14 08:17:51 +00004191 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004192 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004193
Richard Trieuba63ce62011-09-09 01:45:06 +00004194 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004195}
4196
Anders Carlsson525b76b2009-10-16 02:48:28 +00004197bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004198 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004199 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004200
Anders Carlssonde71adf2007-11-27 05:51:55 +00004201 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004202 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004203 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004204 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004205 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004206 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004207 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004208 } else
4209 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004210 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004211 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004212
John McCalle3027922010-08-25 11:45:40 +00004213 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004214 return false;
4215}
4216
John Wiegley01296292011-04-08 18:41:53 +00004217ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4218 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004219 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004220
Anders Carlsson43d70f82009-10-16 05:23:41 +00004221 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004222
Nate Begemanc8961a42009-06-27 22:05:55 +00004223 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4224 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004225 // In OpenCL, casts between vectors of different types are not allowed.
4226 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004227 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004228 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4229 || (getLangOptions().OpenCL &&
4230 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004231 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004232 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004233 return ExprError();
4234 }
John McCalle3027922010-08-25 11:45:40 +00004235 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004236 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004237 }
4238
Nate Begemanbd956c42009-06-28 02:36:38 +00004239 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004240 // conversion will take place first from scalar to elt type, and then
4241 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004242 if (SrcTy->isPointerType())
4243 return Diag(R.getBegin(),
4244 diag::err_invalid_conversion_between_vector_and_scalar)
4245 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004246
4247 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004248 ExprResult CastExprRes = Owned(CastExpr);
4249 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4250 if (CastExprRes.isInvalid())
4251 return ExprError();
4252 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004253
John McCalle3027922010-08-25 11:45:40 +00004254 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004255 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004256}
4257
John McCalldadc5752010-08-24 06:29:42 +00004258ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004259Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4260 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004261 SourceLocation RParenLoc, Expr *CastExpr) {
4262 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004263 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004264
Richard Trieuba63ce62011-09-09 01:45:06 +00004265 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004266 if (D.isInvalidType())
4267 return ExprError();
4268
4269 if (getLangOptions().CPlusPlus) {
4270 // Check that there are no default arguments (C++ only).
4271 CheckExtraCXXDefaultArguments(D);
4272 }
4273
4274 QualType castType = castTInfo->getType();
4275 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004276
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004277 bool isVectorLiteral = false;
4278
4279 // Check for an altivec or OpenCL literal,
4280 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004281 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4282 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004283 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4284 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004285 if (PLE && PLE->getNumExprs() == 0) {
4286 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4287 return ExprError();
4288 }
4289 if (PE || PLE->getNumExprs() == 1) {
4290 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4291 if (!E->getType()->isVectorType())
4292 isVectorLiteral = true;
4293 }
4294 else
4295 isVectorLiteral = true;
4296 }
4297
4298 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4299 // then handle it as such.
4300 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004301 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004302
Nate Begeman5ec4b312009-08-10 23:49:36 +00004303 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004304 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4305 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004306 if (isa<ParenListExpr>(CastExpr)) {
4307 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004308 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004309 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004310 }
John McCallebe54742010-01-15 18:56:44 +00004311
Richard Trieuba63ce62011-09-09 01:45:06 +00004312 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004313}
4314
John McCalldadc5752010-08-24 06:29:42 +00004315ExprResult
John McCallebe54742010-01-15 18:56:44 +00004316Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004317 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004318 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004319 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004320 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004321 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004322 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004323 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004324 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004325 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004326 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004327
Richard Trieucfc491d2011-08-02 04:35:43 +00004328 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004329 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004330 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004331}
4332
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004333ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4334 SourceLocation RParenLoc, Expr *E,
4335 TypeSourceInfo *TInfo) {
4336 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4337 "Expected paren or paren list expression");
4338
4339 Expr **exprs;
4340 unsigned numExprs;
4341 Expr *subExpr;
4342 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4343 exprs = PE->getExprs();
4344 numExprs = PE->getNumExprs();
4345 } else {
4346 subExpr = cast<ParenExpr>(E)->getSubExpr();
4347 exprs = &subExpr;
4348 numExprs = 1;
4349 }
4350
4351 QualType Ty = TInfo->getType();
4352 assert(Ty->isVectorType() && "Expected vector type");
4353
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004354 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004355 const VectorType *VTy = Ty->getAs<VectorType>();
4356 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4357
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004358 // '(...)' form of vector initialization in AltiVec: the number of
4359 // initializers must be one or must match the size of the vector.
4360 // If a single value is specified in the initializer then it will be
4361 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004362 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004363 // The number of initializers must be one or must match the size of the
4364 // vector. If a single value is specified in the initializer then it will
4365 // be replicated to all the components of the vector
4366 if (numExprs == 1) {
4367 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4368 ExprResult Literal = Owned(exprs[0]);
4369 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4370 PrepareScalarCast(*this, Literal, ElemTy));
4371 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4372 }
4373 else if (numExprs < numElems) {
4374 Diag(E->getExprLoc(),
4375 diag::err_incorrect_number_of_vector_initializers);
4376 return ExprError();
4377 }
4378 else
4379 for (unsigned i = 0, e = numExprs; i != e; ++i)
4380 initExprs.push_back(exprs[i]);
4381 }
Tanya Lattner83559382011-07-15 23:07:01 +00004382 else {
4383 // For OpenCL, when the number of initializers is a single value,
4384 // it will be replicated to all components of the vector.
4385 if (getLangOptions().OpenCL &&
4386 VTy->getVectorKind() == VectorType::GenericVector &&
4387 numExprs == 1) {
4388 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4389 ExprResult Literal = Owned(exprs[0]);
4390 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4391 PrepareScalarCast(*this, Literal, ElemTy));
4392 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4393 }
4394
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004395 for (unsigned i = 0, e = numExprs; i != e; ++i)
4396 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004397 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004398 // FIXME: This means that pretty-printing the final AST will produce curly
4399 // braces instead of the original commas.
4400 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4401 &initExprs[0],
4402 initExprs.size(), RParenLoc);
4403 initE->setType(Ty);
4404 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4405}
4406
Nate Begeman5ec4b312009-08-10 23:49:36 +00004407/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4408/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004409ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004410Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4411 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004412 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004413 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004414
John McCalldadc5752010-08-24 06:29:42 +00004415 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004416
Nate Begeman5ec4b312009-08-10 23:49:36 +00004417 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004418 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4419 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004420
John McCallb268a282010-08-23 23:25:46 +00004421 if (Result.isInvalid()) return ExprError();
4422
4423 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004424}
4425
John McCalldadc5752010-08-24 06:29:42 +00004426ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004427 SourceLocation R,
4428 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004429 unsigned nexprs = Val.size();
4430 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004431 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4432 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004433 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004434 expr = new (Context) ParenExpr(L, R, exprs[0]);
4435 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004436 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4437 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004438 return Owned(expr);
4439}
4440
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004441/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004442/// constant and the other is not a pointer. Returns true if a diagnostic is
4443/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004444bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004445 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004446 Expr *NullExpr = LHSExpr;
4447 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004448 Expr::NullPointerConstantKind NullKind =
4449 NullExpr->isNullPointerConstant(Context,
4450 Expr::NPC_ValueDependentIsNotNull);
4451
4452 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004453 NullExpr = RHSExpr;
4454 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004455 NullKind =
4456 NullExpr->isNullPointerConstant(Context,
4457 Expr::NPC_ValueDependentIsNotNull);
4458 }
4459
4460 if (NullKind == Expr::NPCK_NotNull)
4461 return false;
4462
4463 if (NullKind == Expr::NPCK_ZeroInteger) {
4464 // In this case, check to make sure that we got here from a "NULL"
4465 // string in the source code.
4466 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004467 SourceLocation loc = NullExpr->getExprLoc();
4468 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004469 return false;
4470 }
4471
4472 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4473 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4474 << NonPointerExpr->getType() << DiagType
4475 << NonPointerExpr->getSourceRange();
4476 return true;
4477}
4478
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004479/// \brief Return false if the condition expression is valid, true otherwise.
4480static bool checkCondition(Sema &S, Expr *Cond) {
4481 QualType CondTy = Cond->getType();
4482
4483 // C99 6.5.15p2
4484 if (CondTy->isScalarType()) return false;
4485
4486 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4487 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4488 return false;
4489
4490 // Emit the proper error message.
4491 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4492 diag::err_typecheck_cond_expect_scalar :
4493 diag::err_typecheck_cond_expect_scalar_or_vector)
4494 << CondTy;
4495 return true;
4496}
4497
4498/// \brief Return false if the two expressions can be converted to a vector,
4499/// true otherwise
4500static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4501 ExprResult &RHS,
4502 QualType CondTy) {
4503 // Both operands should be of scalar type.
4504 if (!LHS.get()->getType()->isScalarType()) {
4505 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4506 << CondTy;
4507 return true;
4508 }
4509 if (!RHS.get()->getType()->isScalarType()) {
4510 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4511 << CondTy;
4512 return true;
4513 }
4514
4515 // Implicity convert these scalars to the type of the condition.
4516 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4517 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4518 return false;
4519}
4520
4521/// \brief Handle when one or both operands are void type.
4522static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4523 ExprResult &RHS) {
4524 Expr *LHSExpr = LHS.get();
4525 Expr *RHSExpr = RHS.get();
4526
4527 if (!LHSExpr->getType()->isVoidType())
4528 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4529 << RHSExpr->getSourceRange();
4530 if (!RHSExpr->getType()->isVoidType())
4531 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4532 << LHSExpr->getSourceRange();
4533 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4534 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4535 return S.Context.VoidTy;
4536}
4537
4538/// \brief Return false if the NullExpr can be promoted to PointerTy,
4539/// true otherwise.
4540static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4541 QualType PointerTy) {
4542 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4543 !NullExpr.get()->isNullPointerConstant(S.Context,
4544 Expr::NPC_ValueDependentIsNull))
4545 return true;
4546
4547 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4548 return false;
4549}
4550
4551/// \brief Checks compatibility between two pointers and return the resulting
4552/// type.
4553static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4554 ExprResult &RHS,
4555 SourceLocation Loc) {
4556 QualType LHSTy = LHS.get()->getType();
4557 QualType RHSTy = RHS.get()->getType();
4558
4559 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4560 // Two identical pointers types are always compatible.
4561 return LHSTy;
4562 }
4563
4564 QualType lhptee, rhptee;
4565
4566 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004567 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4568 lhptee = LHSBTy->getPointeeType();
4569 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004570 } else {
John McCall9320b872011-09-09 05:25:32 +00004571 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4572 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004573 }
4574
4575 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4576 rhptee.getUnqualifiedType())) {
4577 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4578 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4579 << RHS.get()->getSourceRange();
4580 // In this situation, we assume void* type. No especially good
4581 // reason, but this is what gcc does, and we do have to pick
4582 // to get a consistent AST.
4583 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4584 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4585 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4586 return incompatTy;
4587 }
4588
4589 // The pointer types are compatible.
4590 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4591 // differently qualified versions of compatible types, the result type is
4592 // a pointer to an appropriately qualified version of the *composite*
4593 // type.
4594 // FIXME: Need to calculate the composite type.
4595 // FIXME: Need to add qualifiers
4596
4597 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4598 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4599 return LHSTy;
4600}
4601
4602/// \brief Return the resulting type when the operands are both block pointers.
4603static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4604 ExprResult &LHS,
4605 ExprResult &RHS,
4606 SourceLocation Loc) {
4607 QualType LHSTy = LHS.get()->getType();
4608 QualType RHSTy = RHS.get()->getType();
4609
4610 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4611 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4612 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4613 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4614 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4615 return destType;
4616 }
4617 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4618 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4619 << RHS.get()->getSourceRange();
4620 return QualType();
4621 }
4622
4623 // We have 2 block pointer types.
4624 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4625}
4626
4627/// \brief Return the resulting type when the operands are both pointers.
4628static QualType
4629checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4630 ExprResult &RHS,
4631 SourceLocation Loc) {
4632 // get the pointer types
4633 QualType LHSTy = LHS.get()->getType();
4634 QualType RHSTy = RHS.get()->getType();
4635
4636 // get the "pointed to" types
4637 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4638 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4639
4640 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4641 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4642 // Figure out necessary qualifiers (C99 6.5.15p6)
4643 QualType destPointee
4644 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4645 QualType destType = S.Context.getPointerType(destPointee);
4646 // Add qualifiers if necessary.
4647 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4648 // Promote to void*.
4649 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4650 return destType;
4651 }
4652 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4653 QualType destPointee
4654 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4655 QualType destType = S.Context.getPointerType(destPointee);
4656 // Add qualifiers if necessary.
4657 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4658 // Promote to void*.
4659 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4660 return destType;
4661 }
4662
4663 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4664}
4665
4666/// \brief Return false if the first expression is not an integer and the second
4667/// expression is not a pointer, true otherwise.
4668static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4669 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004670 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004671 if (!PointerExpr->getType()->isPointerType() ||
4672 !Int.get()->getType()->isIntegerType())
4673 return false;
4674
Richard Trieuba63ce62011-09-09 01:45:06 +00004675 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4676 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004677
4678 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4679 << Expr1->getType() << Expr2->getType()
4680 << Expr1->getSourceRange() << Expr2->getSourceRange();
4681 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4682 CK_IntegralToPointer);
4683 return true;
4684}
4685
Richard Trieud33e46e2011-09-06 20:06:39 +00004686/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4687/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004688/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004689QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4690 ExprResult &RHS, ExprValueKind &VK,
4691 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004692 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004693
Richard Trieud33e46e2011-09-06 20:06:39 +00004694 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4695 if (!LHSResult.isUsable()) return QualType();
4696 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004697
Richard Trieud33e46e2011-09-06 20:06:39 +00004698 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4699 if (!RHSResult.isUsable()) return QualType();
4700 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004701
Sebastian Redl1a99f442009-04-16 17:51:27 +00004702 // C++ is sufficiently different to merit its own checker.
4703 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004704 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004705
4706 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004707 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004708
John Wiegley01296292011-04-08 18:41:53 +00004709 Cond = UsualUnaryConversions(Cond.take());
4710 if (Cond.isInvalid())
4711 return QualType();
4712 LHS = UsualUnaryConversions(LHS.take());
4713 if (LHS.isInvalid())
4714 return QualType();
4715 RHS = UsualUnaryConversions(RHS.take());
4716 if (RHS.isInvalid())
4717 return QualType();
4718
4719 QualType CondTy = Cond.get()->getType();
4720 QualType LHSTy = LHS.get()->getType();
4721 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004722
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004723 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004724 if (checkCondition(*this, Cond.get()))
4725 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004726
Chris Lattnere2949f42008-01-06 22:42:25 +00004727 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004728 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004729 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004730
Nate Begemanabb5a732010-09-20 22:41:17 +00004731 // OpenCL: If the condition is a vector, and both operands are scalar,
4732 // attempt to implicity convert them to the vector type to act like the
4733 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004734 if (getLangOptions().OpenCL && CondTy->isVectorType())
4735 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004736 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004737
Chris Lattnere2949f42008-01-06 22:42:25 +00004738 // If both operands have arithmetic type, do the usual arithmetic conversions
4739 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004740 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4741 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004742 if (LHS.isInvalid() || RHS.isInvalid())
4743 return QualType();
4744 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004745 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004746
Chris Lattnere2949f42008-01-06 22:42:25 +00004747 // If both operands are the same structure or union type, the result is that
4748 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004749 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4750 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004751 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004752 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004753 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004754 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004755 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004756 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004757
Chris Lattnere2949f42008-01-06 22:42:25 +00004758 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004759 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004760 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004761 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004762 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004763
Steve Naroff039ad3c2008-01-08 01:11:38 +00004764 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4765 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004766 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4767 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004768
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004769 // All objective-c pointer type analysis is done here.
4770 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4771 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004772 if (LHS.isInvalid() || RHS.isInvalid())
4773 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004774 if (!compositeType.isNull())
4775 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004776
4777
Steve Naroff05efa972009-07-01 14:36:47 +00004778 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004779 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4780 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4781 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004782
Steve Naroff05efa972009-07-01 14:36:47 +00004783 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004784 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4785 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4786 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004787
John McCalle84af4e2010-11-13 01:35:44 +00004788 // GCC compatibility: soften pointer/integer mismatch. Note that
4789 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004790 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4791 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004792 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004793 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4794 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004795 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004796
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004797 // Emit a better diagnostic if one of the expressions is a null pointer
4798 // constant and the other is not a pointer type. In this case, the user most
4799 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004800 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004801 return QualType();
4802
Chris Lattnere2949f42008-01-06 22:42:25 +00004803 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004804 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004805 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4806 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004807 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004808}
4809
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004810/// FindCompositeObjCPointerType - Helper method to find composite type of
4811/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004812QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004813 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004814 QualType LHSTy = LHS.get()->getType();
4815 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004816
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004817 // Handle things like Class and struct objc_class*. Here we case the result
4818 // to the pseudo-builtin, because that will be implicitly cast back to the
4819 // redefinition type if an attempt is made to access its fields.
4820 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004821 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004822 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004823 return LHSTy;
4824 }
4825 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004826 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004827 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004828 return RHSTy;
4829 }
4830 // And the same for struct objc_object* / id
4831 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004832 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004833 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004834 return LHSTy;
4835 }
4836 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004837 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004838 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004839 return RHSTy;
4840 }
4841 // And the same for struct objc_selector* / SEL
4842 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004843 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004844 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004845 return LHSTy;
4846 }
4847 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004848 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004849 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004850 return RHSTy;
4851 }
4852 // Check constraints for Objective-C object pointers types.
4853 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004854
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004855 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4856 // Two identical object pointer types are always compatible.
4857 return LHSTy;
4858 }
John McCall9320b872011-09-09 05:25:32 +00004859 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4860 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004861 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004862
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004863 // If both operands are interfaces and either operand can be
4864 // assigned to the other, use that type as the composite
4865 // type. This allows
4866 // xxx ? (A*) a : (B*) b
4867 // where B is a subclass of A.
4868 //
4869 // Additionally, as for assignment, if either type is 'id'
4870 // allow silent coercion. Finally, if the types are
4871 // incompatible then make sure to use 'id' as the composite
4872 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004873
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004874 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4875 // It could return the composite type.
4876 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4877 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4878 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4879 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4880 } else if ((LHSTy->isObjCQualifiedIdType() ||
4881 RHSTy->isObjCQualifiedIdType()) &&
4882 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4883 // Need to handle "id<xx>" explicitly.
4884 // GCC allows qualified id and any Objective-C type to devolve to
4885 // id. Currently localizing to here until clear this should be
4886 // part of ObjCQualifiedIdTypesAreCompatible.
4887 compositeType = Context.getObjCIdType();
4888 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4889 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004890 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004891 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4892 ;
4893 else {
4894 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4895 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004896 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004897 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004898 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4899 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004900 return incompatTy;
4901 }
4902 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004903 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4904 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004905 return compositeType;
4906 }
4907 // Check Objective-C object pointer types and 'void *'
4908 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4909 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4910 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4911 QualType destPointee
4912 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4913 QualType destType = Context.getPointerType(destPointee);
4914 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004915 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004916 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004917 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004918 return destType;
4919 }
4920 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4921 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4922 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4923 QualType destPointee
4924 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4925 QualType destType = Context.getPointerType(destPointee);
4926 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004927 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004928 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004929 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004930 return destType;
4931 }
4932 return QualType();
4933}
4934
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004935/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004936/// ParenRange in parentheses.
4937static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004938 const PartialDiagnostic &Note,
4939 SourceRange ParenRange) {
4940 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4941 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4942 EndLoc.isValid()) {
4943 Self.Diag(Loc, Note)
4944 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4945 << FixItHint::CreateInsertion(EndLoc, ")");
4946 } else {
4947 // We can't display the parentheses, so just show the bare note.
4948 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004949 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004950}
4951
4952static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4953 return Opc >= BO_Mul && Opc <= BO_Shr;
4954}
4955
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004956/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4957/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004958/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4959/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004960static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004961 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004962 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4963 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004964 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004965 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004966
4967 // Built-in binary operator.
4968 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4969 if (IsArithmeticOp(OP->getOpcode())) {
4970 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004971 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004972 return true;
4973 }
4974 }
4975
4976 // Overloaded operator.
4977 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4978 if (Call->getNumArgs() != 2)
4979 return false;
4980
4981 // Make sure this is really a binary operator that is safe to pass into
4982 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4983 OverloadedOperatorKind OO = Call->getOperator();
4984 if (OO < OO_Plus || OO > OO_Arrow)
4985 return false;
4986
4987 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4988 if (IsArithmeticOp(OpKind)) {
4989 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004990 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004991 return true;
4992 }
4993 }
4994
4995 return false;
4996}
4997
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004998static bool IsLogicOp(BinaryOperatorKind Opc) {
4999 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5000}
5001
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005002/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5003/// or is a logical expression such as (x==y) which has int type, but is
5004/// commonly interpreted as boolean.
5005static bool ExprLooksBoolean(Expr *E) {
5006 E = E->IgnoreParenImpCasts();
5007
5008 if (E->getType()->isBooleanType())
5009 return true;
5010 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5011 return IsLogicOp(OP->getOpcode());
5012 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5013 return OP->getOpcode() == UO_LNot;
5014
5015 return false;
5016}
5017
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005018/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5019/// and binary operator are mixed in a way that suggests the programmer assumed
5020/// the conditional operator has higher precedence, for example:
5021/// "int x = a + someBinaryCondition ? 1 : 2".
5022static void DiagnoseConditionalPrecedence(Sema &Self,
5023 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005024 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005025 Expr *LHSExpr,
5026 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005027 BinaryOperatorKind CondOpcode;
5028 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005029
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005030 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005031 return;
5032 if (!ExprLooksBoolean(CondRHS))
5033 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005034
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005035 // The condition is an arithmetic binary expression, with a right-
5036 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005037
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005038 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005039 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005040 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005041
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005042 SuggestParentheses(Self, OpLoc,
5043 Self.PDiag(diag::note_precedence_conditional_silence)
5044 << BinaryOperator::getOpcodeStr(CondOpcode),
5045 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005046
5047 SuggestParentheses(Self, OpLoc,
5048 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005049 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005050}
5051
Steve Naroff83895f72007-09-16 03:34:24 +00005052/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005053/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005054ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005055 SourceLocation ColonLoc,
5056 Expr *CondExpr, Expr *LHSExpr,
5057 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005058 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5059 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005060 OpaqueValueExpr *opaqueValue = 0;
5061 Expr *commonExpr = 0;
5062 if (LHSExpr == 0) {
5063 commonExpr = CondExpr;
5064
5065 // We usually want to apply unary conversions *before* saving, except
5066 // in the special case of a C++ l-value conditional.
5067 if (!(getLangOptions().CPlusPlus
5068 && !commonExpr->isTypeDependent()
5069 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5070 && commonExpr->isGLValue()
5071 && commonExpr->isOrdinaryOrBitFieldObject()
5072 && RHSExpr->isOrdinaryOrBitFieldObject()
5073 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005074 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5075 if (commonRes.isInvalid())
5076 return ExprError();
5077 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005078 }
5079
5080 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5081 commonExpr->getType(),
5082 commonExpr->getValueKind(),
5083 commonExpr->getObjectKind());
5084 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005085 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005086
John McCall7decc9e2010-11-18 06:31:45 +00005087 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005088 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005089 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5090 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005091 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005092 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5093 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005094 return ExprError();
5095
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005096 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5097 RHS.get());
5098
John McCallc07a0c72011-02-17 10:25:35 +00005099 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005100 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5101 LHS.take(), ColonLoc,
5102 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005103
5104 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005105 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005106 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5107 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005108}
5109
John McCallaba90822011-01-31 23:13:11 +00005110// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005111// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005112// routine is it effectively iqnores the qualifiers on the top level pointee.
5113// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5114// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005115static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005116checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5117 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5118 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005119
Steve Naroff1f4d7272007-05-11 04:00:31 +00005120 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005121 const Type *lhptee, *rhptee;
5122 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005123 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5124 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005125
John McCallaba90822011-01-31 23:13:11 +00005126 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005127
5128 // C99 6.5.16.1p1: This following citation is common to constraints
5129 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5130 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005131 Qualifiers lq;
5132
John McCall31168b02011-06-15 23:02:42 +00005133 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5134 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5135 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5136 // Ignore lifetime for further calculation.
5137 lhq.removeObjCLifetime();
5138 rhq.removeObjCLifetime();
5139 }
5140
John McCall4fff8f62011-02-01 00:10:29 +00005141 if (!lhq.compatiblyIncludes(rhq)) {
5142 // Treat address-space mismatches as fatal. TODO: address subspaces
5143 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5144 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5145
John McCall31168b02011-06-15 23:02:42 +00005146 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005147 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005148 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5149 .compatiblyIncludes(
5150 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005151 && (lhptee->isVoidType() || rhptee->isVoidType()))
5152 ; // keep old
5153
John McCall31168b02011-06-15 23:02:42 +00005154 // Treat lifetime mismatches as fatal.
5155 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5156 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5157
John McCall4fff8f62011-02-01 00:10:29 +00005158 // For GCC compatibility, other qualifier mismatches are treated
5159 // as still compatible in C.
5160 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5161 }
Steve Naroff3f597292007-05-11 22:18:03 +00005162
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5164 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005165 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005166 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005167 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005168 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005169
Chris Lattner0a788432008-01-03 22:56:36 +00005170 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005171 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005172 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005173 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005174
Chris Lattner0a788432008-01-03 22:56:36 +00005175 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005176 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005177 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005178
5179 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005180 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005181 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005182 }
John McCall4fff8f62011-02-01 00:10:29 +00005183
Mike Stump4e1f26a2009-02-19 03:04:26 +00005184 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005185 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005186 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5187 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005188 // Check if the pointee types are compatible ignoring the sign.
5189 // We explicitly check for char so that we catch "char" vs
5190 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005191 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005192 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005193 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005194 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005195
Chris Lattnerec3a1562009-10-17 20:33:28 +00005196 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005197 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005198 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005199 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005200
John McCall4fff8f62011-02-01 00:10:29 +00005201 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005202 // Types are compatible ignoring the sign. Qualifier incompatibility
5203 // takes priority over sign incompatibility because the sign
5204 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005205 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005206 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005207
John McCallaba90822011-01-31 23:13:11 +00005208 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005209 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005210
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005211 // If we are a multi-level pointer, it's possible that our issue is simply
5212 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5213 // the eventual target type is the same and the pointers have the same
5214 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005215 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005216 do {
John McCall4fff8f62011-02-01 00:10:29 +00005217 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5218 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005219 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005220
John McCall4fff8f62011-02-01 00:10:29 +00005221 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005222 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005223 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005224
Eli Friedman80160bd2009-03-22 23:59:44 +00005225 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005226 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005227 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005228 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005229}
5230
John McCallaba90822011-01-31 23:13:11 +00005231/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005232/// block pointer types are compatible or whether a block and normal pointer
5233/// are compatible. It is more restrict than comparing two function pointer
5234// types.
John McCallaba90822011-01-31 23:13:11 +00005235static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005236checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5237 QualType RHSType) {
5238 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5239 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005240
Steve Naroff081c7422008-09-04 15:10:53 +00005241 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005242
Steve Naroff081c7422008-09-04 15:10:53 +00005243 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005244 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5245 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005246
John McCallaba90822011-01-31 23:13:11 +00005247 // In C++, the types have to match exactly.
5248 if (S.getLangOptions().CPlusPlus)
5249 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005250
John McCallaba90822011-01-31 23:13:11 +00005251 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005252
Steve Naroff081c7422008-09-04 15:10:53 +00005253 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005254 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5255 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005256
Richard Trieua871b972011-09-06 20:21:22 +00005257 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005258 return Sema::IncompatibleBlockPointer;
5259
Steve Naroff081c7422008-09-04 15:10:53 +00005260 return ConvTy;
5261}
5262
John McCallaba90822011-01-31 23:13:11 +00005263/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005264/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005265static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005266checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5267 QualType RHSType) {
5268 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5269 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005270
Richard Trieua871b972011-09-06 20:21:22 +00005271 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005272 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005273 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5274 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005275 return Sema::IncompatiblePointer;
5276 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005277 }
Richard Trieua871b972011-09-06 20:21:22 +00005278 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005279 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5280 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005281 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005282 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005283 }
Richard Trieua871b972011-09-06 20:21:22 +00005284 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5285 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005286
John McCallaba90822011-01-31 23:13:11 +00005287 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5288 return Sema::CompatiblePointerDiscardsQualifiers;
5289
Richard Trieua871b972011-09-06 20:21:22 +00005290 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005291 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005292 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005293 return Sema::IncompatibleObjCQualifiedId;
5294 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005295}
5296
John McCall29600e12010-11-16 02:32:08 +00005297Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005298Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005299 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005300 // Fake up an opaque expression. We don't actually care about what
5301 // cast operations are required, so if CheckAssignmentConstraints
5302 // adds casts to this they'll be wasted, but fortunately that doesn't
5303 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005304 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5305 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005306 CastKind K = CK_Invalid;
5307
Richard Trieua871b972011-09-06 20:21:22 +00005308 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005309}
5310
Mike Stump4e1f26a2009-02-19 03:04:26 +00005311/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5312/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005313/// pointers. Here are some objectionable examples that GCC considers warnings:
5314///
5315/// int a, *pint;
5316/// short *pshort;
5317/// struct foo *pfoo;
5318///
5319/// pint = pshort; // warning: assignment from incompatible pointer type
5320/// a = pint; // warning: assignment makes integer from pointer without a cast
5321/// pint = a; // warning: assignment makes pointer from integer without a cast
5322/// pint = pfoo; // warning: assignment from incompatible pointer type
5323///
5324/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005325/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005326///
John McCall8cb679e2010-11-15 09:13:47 +00005327/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005328Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005329Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005330 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005331 QualType RHSType = RHS.get()->getType();
5332 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005333
Chris Lattnera52c2f22008-01-04 23:18:45 +00005334 // Get canonical types. We're not formatting these types, just comparing
5335 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005336 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5337 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005338
John McCalle5255932011-01-31 22:28:28 +00005339 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005340 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005341 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005342 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005343 }
5344
Douglas Gregor6b754842008-10-28 00:22:11 +00005345 // If the left-hand side is a reference type, then we are in a
5346 // (rare!) case where we've allowed the use of references in C,
5347 // e.g., as a parameter type in a built-in function. In this case,
5348 // just make sure that the type referenced is compatible with the
5349 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005350 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005351 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005352 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5353 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005354 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005355 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005356 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005357 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005358 }
John McCalle5255932011-01-31 22:28:28 +00005359
Nate Begemanbd956c42009-06-28 02:36:38 +00005360 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5361 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005362 if (LHSType->isExtVectorType()) {
5363 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005364 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005365 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005366 // CK_VectorSplat does T -> vector T, so first cast to the
5367 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005368 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5369 if (elType != RHSType) {
5370 Kind = PrepareScalarCast(*this, RHS, elType);
5371 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005372 }
5373 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005374 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005375 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005376 }
Mike Stump11289f42009-09-09 15:08:12 +00005377
John McCalle5255932011-01-31 22:28:28 +00005378 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005379 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5380 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005381 // Allow assignments of an AltiVec vector type to an equivalent GCC
5382 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005383 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005384 Kind = CK_BitCast;
5385 return Compatible;
5386 }
5387
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005388 // If we are allowing lax vector conversions, and LHS and RHS are both
5389 // vectors, the total size only needs to be the same. This is a bitcast;
5390 // no bits are changed but the result type is different.
5391 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005392 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005393 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005394 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005395 }
Chris Lattner881a2122008-01-04 23:32:24 +00005396 }
5397 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005398 }
Eli Friedman3360d892008-05-30 18:07:22 +00005399
John McCalle5255932011-01-31 22:28:28 +00005400 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005401 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5402 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5403 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005404 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005405 }
Eli Friedman3360d892008-05-30 18:07:22 +00005406
John McCalle5255932011-01-31 22:28:28 +00005407 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005408 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005409 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005410 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005411 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005412 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005413 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005414
John McCalle5255932011-01-31 22:28:28 +00005415 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005416 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005417 Kind = CK_IntegralToPointer; // FIXME: null?
5418 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005419 }
John McCalle5255932011-01-31 22:28:28 +00005420
5421 // C pointers are not compatible with ObjC object pointers,
5422 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005423 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005424 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005425 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005426 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005427 return Compatible;
5428 }
5429
5430 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005431 if (RHSType->isObjCClassType() &&
5432 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005433 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005434 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005435 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005436 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005437
John McCalle5255932011-01-31 22:28:28 +00005438 Kind = CK_BitCast;
5439 return IncompatiblePointer;
5440 }
5441
5442 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005443 if (RHSType->getAs<BlockPointerType>()) {
5444 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005445 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005446 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005447 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005448 }
John McCalle5255932011-01-31 22:28:28 +00005449
Steve Naroff081c7422008-09-04 15:10:53 +00005450 return Incompatible;
5451 }
5452
John McCalle5255932011-01-31 22:28:28 +00005453 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005454 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005455 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005456 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005457 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005458 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005459 }
5460
5461 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005462 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005463 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005464 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005465 }
5466
John McCalle5255932011-01-31 22:28:28 +00005467 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005469 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005470 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005471 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005472
John McCalle5255932011-01-31 22:28:28 +00005473 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005474 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005475 if (RHSPT->getPointeeType()->isVoidType()) {
5476 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005477 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005478 }
John McCall8cb679e2010-11-15 09:13:47 +00005479
Chris Lattnera52c2f22008-01-04 23:18:45 +00005480 return Incompatible;
5481 }
5482
John McCalle5255932011-01-31 22:28:28 +00005483 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005484 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005485 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005486 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005487 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005488 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005489 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005490 if (getLangOptions().ObjCAutoRefCount &&
5491 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005492 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005493 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005494 return result;
John McCalle5255932011-01-31 22:28:28 +00005495 }
5496
5497 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005498 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005499 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005500 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005501 }
5502
John McCalle5255932011-01-31 22:28:28 +00005503 // In general, C pointers are not compatible with ObjC object pointers,
5504 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005505 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005506 Kind = CK_CPointerToObjCPointerCast;
5507
John McCalle5255932011-01-31 22:28:28 +00005508 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005509 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005510 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005511 }
5512
5513 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005514 if (LHSType->isObjCClassType() &&
5515 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005516 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005517 return Compatible;
5518 }
5519
Steve Naroffaccc4882009-07-20 17:56:53 +00005520 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005521 }
John McCalle5255932011-01-31 22:28:28 +00005522
5523 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005524 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005525 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005526 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005527 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005528 }
5529
Steve Naroff7cae42b2009-07-10 23:34:53 +00005530 return Incompatible;
5531 }
John McCalle5255932011-01-31 22:28:28 +00005532
5533 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005534 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005535 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005536 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005537 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005538 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005539 }
Eli Friedman3360d892008-05-30 18:07:22 +00005540
John McCalle5255932011-01-31 22:28:28 +00005541 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005542 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005543 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005544 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005545 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005546
Chris Lattnera52c2f22008-01-04 23:18:45 +00005547 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005548 }
John McCalle5255932011-01-31 22:28:28 +00005549
5550 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005551 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005552 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005553 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005554 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005555 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005556 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005557
John McCalle5255932011-01-31 22:28:28 +00005558 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005559 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005560 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005561 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005562 }
5563
Steve Naroff7cae42b2009-07-10 23:34:53 +00005564 return Incompatible;
5565 }
Eli Friedman3360d892008-05-30 18:07:22 +00005566
John McCalle5255932011-01-31 22:28:28 +00005567 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005568 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5569 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005570 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005571 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005572 }
Bill Wendling216423b2007-05-30 06:30:29 +00005573 }
John McCalle5255932011-01-31 22:28:28 +00005574
Steve Naroff98cf3e92007-06-06 18:38:38 +00005575 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005576}
5577
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005578/// \brief Constructs a transparent union from an expression that is
5579/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005580static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5581 ExprResult &EResult, QualType UnionType,
5582 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005583 // Build an initializer list that designates the appropriate member
5584 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005585 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005586 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005587 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005588 SourceLocation());
5589 Initializer->setType(UnionType);
5590 Initializer->setInitializedFieldInUnion(Field);
5591
5592 // Build a compound literal constructing a value of the transparent
5593 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005594 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005595 EResult = S.Owned(
5596 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5597 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005598}
5599
5600Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005601Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005602 ExprResult &RHS) {
5603 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005604
Mike Stump11289f42009-09-09 15:08:12 +00005605 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005606 // transparent_union GCC extension.
5607 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005608 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005609 return Incompatible;
5610
5611 // The field to initialize within the transparent union.
5612 RecordDecl *UD = UT->getDecl();
5613 FieldDecl *InitField = 0;
5614 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005615 for (RecordDecl::field_iterator it = UD->field_begin(),
5616 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005617 it != itend; ++it) {
5618 if (it->getType()->isPointerType()) {
5619 // If the transparent union contains a pointer type, we allow:
5620 // 1) void pointer
5621 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005622 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005623 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005624 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005625 InitField = *it;
5626 break;
5627 }
Mike Stump11289f42009-09-09 15:08:12 +00005628
Richard Trieueb299142011-09-06 20:40:12 +00005629 if (RHS.get()->isNullPointerConstant(Context,
5630 Expr::NPC_ValueDependentIsNull)) {
5631 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5632 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005633 InitField = *it;
5634 break;
5635 }
5636 }
5637
John McCall8cb679e2010-11-15 09:13:47 +00005638 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005639 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005640 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005641 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005642 InitField = *it;
5643 break;
5644 }
5645 }
5646
5647 if (!InitField)
5648 return Incompatible;
5649
Richard Trieueb299142011-09-06 20:40:12 +00005650 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005651 return Compatible;
5652}
5653
Chris Lattner9bad62c2008-01-04 18:04:52 +00005654Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005655Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5656 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005657 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005658 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005659 // C++ 5.17p3: If the left operand is not of class type, the
5660 // expression is implicitly converted (C++ 4) to the
5661 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005662 ExprResult Res = PerformImplicitConversion(RHS.get(),
5663 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005664 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005665 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005666 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005667 Sema::AssignConvertType result = Compatible;
5668 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005669 !CheckObjCARCUnavailableWeakConversion(LHSType,
5670 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005671 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005672 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005673 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005674 }
5675
5676 // FIXME: Currently, we fall through and treat C++ classes like C
5677 // structures.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005678 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005679
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005680 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5681 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005682 if ((LHSType->isPointerType() ||
5683 LHSType->isObjCObjectPointerType() ||
5684 LHSType->isBlockPointerType())
5685 && RHS.get()->isNullPointerConstant(Context,
5686 Expr::NPC_ValueDependentIsNull)) {
5687 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005688 return Compatible;
5689 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005690
Chris Lattnere6dcd502007-10-16 02:55:40 +00005691 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005692 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005693 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005694 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005695 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005696 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005697 if (!LHSType->isReferenceType()) {
5698 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5699 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005700 return Incompatible;
5701 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005702
John McCall8cb679e2010-11-15 09:13:47 +00005703 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005704 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005705 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005706
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005707 // C99 6.5.16.1p2: The value of the right operand is converted to the
5708 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005709 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5710 // so that we can use references in built-in functions even in C.
5711 // The getNonReferenceType() call makes sure that the resulting expression
5712 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005713 if (result != Incompatible && RHS.get()->getType() != LHSType)
5714 RHS = ImpCastExprToType(RHS.take(),
5715 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005716 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005717}
5718
Richard Trieueb299142011-09-06 20:40:12 +00005719QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5720 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005721 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005722 << LHS.get()->getType() << RHS.get()->getType()
5723 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005724 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005725}
5726
Richard Trieu859d23f2011-09-06 21:01:04 +00005727QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005728 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005729 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005730 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005731 QualType LHSType =
5732 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5733 QualType RHSType =
5734 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005735
Nate Begeman191a6b12008-07-14 18:02:46 +00005736 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005737 if (LHSType == RHSType)
5738 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005739
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005740 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005741 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5742 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5743 if (LHSType->isExtVectorType()) {
5744 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5745 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005746 }
5747
Richard Trieuba63ce62011-09-09 01:45:06 +00005748 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005749 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5750 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005751 }
5752
Eli Friedman1408bc92011-06-23 18:10:35 +00005753 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005754 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005755 // If we are allowing lax vector conversions, and LHS and RHS are both
5756 // vectors, the total size only needs to be the same. This is a
5757 // bitcast; no bits are changed but the result type is different.
5758 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005759 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5760 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005761 }
5762
Nate Begemanbd956c42009-06-28 02:36:38 +00005763 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5764 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5765 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005766 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005767 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005768 std::swap(RHS, LHS);
5769 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005770 }
Mike Stump11289f42009-09-09 15:08:12 +00005771
Nate Begeman886448d2009-06-28 19:12:57 +00005772 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005773 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005774 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005775 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5776 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005777 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005778 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005779 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005780 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5781 if (swapped) std::swap(RHS, LHS);
5782 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005783 }
5784 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005785 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5786 RHSType->isRealFloatingType()) {
5787 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005788 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005789 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005790 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005791 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5792 if (swapped) std::swap(RHS, LHS);
5793 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005794 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005795 }
5796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
Nate Begeman886448d2009-06-28 19:12:57 +00005798 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005799 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005800 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005801 << LHS.get()->getType() << RHS.get()->getType()
5802 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005803 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005804}
5805
Richard Trieuf8916e12011-09-16 00:53:10 +00005806// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5807// expression. These are mainly cases where the null pointer is used as an
5808// integer instead of a pointer.
5809static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5810 SourceLocation Loc, bool IsCompare) {
5811 // The canonical way to check for a GNU null is with isNullPointerConstant,
5812 // but we use a bit of a hack here for speed; this is a relatively
5813 // hot path, and isNullPointerConstant is slow.
5814 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5815 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5816
5817 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5818
5819 // Avoid analyzing cases where the result will either be invalid (and
5820 // diagnosed as such) or entirely valid and not something to warn about.
5821 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5822 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5823 return;
5824
5825 // Comparison operations would not make sense with a null pointer no matter
5826 // what the other expression is.
5827 if (!IsCompare) {
5828 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5829 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5830 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5831 return;
5832 }
5833
5834 // The rest of the operations only make sense with a null pointer
5835 // if the other expression is a pointer.
5836 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5837 NonNullType->canDecayToPointerType())
5838 return;
5839
5840 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5841 << LHSNull /* LHS is NULL */ << NonNullType
5842 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5843}
5844
Richard Trieu859d23f2011-09-06 21:01:04 +00005845QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005846 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005847 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005848 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5849
Richard Trieu859d23f2011-09-06 21:01:04 +00005850 if (LHS.get()->getType()->isVectorType() ||
5851 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005852 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005853
Richard Trieuba63ce62011-09-09 01:45:06 +00005854 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005855 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005856 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005857
Richard Trieu859d23f2011-09-06 21:01:04 +00005858 if (!LHS.get()->getType()->isArithmeticType() ||
5859 !RHS.get()->getType()->isArithmeticType())
5860 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005861
Chris Lattnerfaa54172010-01-12 21:23:57 +00005862 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005863 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005864 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005865 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005866 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5867 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005868
Chris Lattnerfaa54172010-01-12 21:23:57 +00005869 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005870}
5871
Chris Lattnerfaa54172010-01-12 21:23:57 +00005872QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005873 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005874 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5875
Richard Trieu859d23f2011-09-06 21:01:04 +00005876 if (LHS.get()->getType()->isVectorType() ||
5877 RHS.get()->getType()->isVectorType()) {
5878 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5879 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005880 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005881 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005882 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005883
Richard Trieuba63ce62011-09-09 01:45:06 +00005884 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005885 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005886 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005887
Richard Trieu859d23f2011-09-06 21:01:04 +00005888 if (!LHS.get()->getType()->isIntegerType() ||
5889 !RHS.get()->getType()->isIntegerType())
5890 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005891
Chris Lattnerfaa54172010-01-12 21:23:57 +00005892 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005893 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005894 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005895 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5896 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005897
Chris Lattnerfaa54172010-01-12 21:23:57 +00005898 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005899}
5900
Chandler Carruthc9332212011-06-27 08:02:19 +00005901/// \brief Diagnose invalid arithmetic on two void pointers.
5902static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005903 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005904 S.Diag(Loc, S.getLangOptions().CPlusPlus
5905 ? diag::err_typecheck_pointer_arith_void_type
5906 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005907 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5908 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005909}
5910
5911/// \brief Diagnose invalid arithmetic on a void pointer.
5912static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5913 Expr *Pointer) {
5914 S.Diag(Loc, S.getLangOptions().CPlusPlus
5915 ? diag::err_typecheck_pointer_arith_void_type
5916 : diag::ext_gnu_void_ptr)
5917 << 0 /* one pointer */ << Pointer->getSourceRange();
5918}
5919
5920/// \brief Diagnose invalid arithmetic on two function pointers.
5921static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5922 Expr *LHS, Expr *RHS) {
5923 assert(LHS->getType()->isAnyPointerType());
5924 assert(RHS->getType()->isAnyPointerType());
5925 S.Diag(Loc, S.getLangOptions().CPlusPlus
5926 ? diag::err_typecheck_pointer_arith_function_type
5927 : diag::ext_gnu_ptr_func_arith)
5928 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5929 // We only show the second type if it differs from the first.
5930 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5931 RHS->getType())
5932 << RHS->getType()->getPointeeType()
5933 << LHS->getSourceRange() << RHS->getSourceRange();
5934}
5935
5936/// \brief Diagnose invalid arithmetic on a function pointer.
5937static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5938 Expr *Pointer) {
5939 assert(Pointer->getType()->isAnyPointerType());
5940 S.Diag(Loc, S.getLangOptions().CPlusPlus
5941 ? diag::err_typecheck_pointer_arith_function_type
5942 : diag::ext_gnu_ptr_func_arith)
5943 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5944 << 0 /* one pointer, so only one type */
5945 << Pointer->getSourceRange();
5946}
5947
Richard Trieu993f3ab2011-09-12 18:08:02 +00005948/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005949///
5950/// \returns True if pointer has incomplete type
5951static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5952 Expr *Operand) {
5953 if ((Operand->getType()->isPointerType() &&
5954 !Operand->getType()->isDependentType()) ||
5955 Operand->getType()->isObjCObjectPointerType()) {
5956 QualType PointeeTy = Operand->getType()->getPointeeType();
5957 if (S.RequireCompleteType(
5958 Loc, PointeeTy,
5959 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5960 << PointeeTy << Operand->getSourceRange()))
5961 return true;
5962 }
5963 return false;
5964}
5965
Chandler Carruthc9332212011-06-27 08:02:19 +00005966/// \brief Check the validity of an arithmetic pointer operand.
5967///
5968/// If the operand has pointer type, this code will check for pointer types
5969/// which are invalid in arithmetic operations. These will be diagnosed
5970/// appropriately, including whether or not the use is supported as an
5971/// extension.
5972///
5973/// \returns True when the operand is valid to use (even if as an extension).
5974static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5975 Expr *Operand) {
5976 if (!Operand->getType()->isAnyPointerType()) return true;
5977
5978 QualType PointeeTy = Operand->getType()->getPointeeType();
5979 if (PointeeTy->isVoidType()) {
5980 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5981 return !S.getLangOptions().CPlusPlus;
5982 }
5983 if (PointeeTy->isFunctionType()) {
5984 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5985 return !S.getLangOptions().CPlusPlus;
5986 }
5987
Richard Trieuaba22802011-09-02 02:15:37 +00005988 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005989
5990 return true;
5991}
5992
5993/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5994/// operands.
5995///
5996/// This routine will diagnose any invalid arithmetic on pointer operands much
5997/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5998/// for emitting a single diagnostic even for operations where both LHS and RHS
5999/// are (potentially problematic) pointers.
6000///
6001/// \returns True when the operand is valid to use (even if as an extension).
6002static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006003 Expr *LHSExpr, Expr *RHSExpr) {
6004 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6005 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006006 if (!isLHSPointer && !isRHSPointer) return true;
6007
6008 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006009 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6010 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006011
6012 // Check for arithmetic on pointers to incomplete types.
6013 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6014 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6015 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006016 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6017 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6018 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006019
6020 return !S.getLangOptions().CPlusPlus;
6021 }
6022
6023 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6024 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6025 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006026 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6027 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6028 RHSExpr);
6029 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006030
6031 return !S.getLangOptions().CPlusPlus;
6032 }
6033
Richard Trieu4ae7e972011-09-06 21:13:51 +00006034 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6035 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006036
Chandler Carruthc9332212011-06-27 08:02:19 +00006037 return true;
6038}
6039
Richard Trieub10c6312011-09-01 22:53:23 +00006040/// \brief Check bad cases where we step over interface counts.
6041static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6042 SourceLocation OpLoc,
6043 Expr *Op) {
6044 assert(Op->getType()->isAnyPointerType());
6045 QualType PointeeTy = Op->getType()->getPointeeType();
6046 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6047 return true;
6048
6049 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6050 << PointeeTy << Op->getSourceRange();
6051 return false;
6052}
6053
Richard Trieu993f3ab2011-09-12 18:08:02 +00006054/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006055static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006056 Expr *LHSExpr, Expr *RHSExpr) {
6057 assert(LHSExpr->getType()->isAnyPointerType());
6058 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006059 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006060 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6061 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006062}
6063
Chris Lattnerfaa54172010-01-12 21:23:57 +00006064QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006065 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006066 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6067
Richard Trieu4ae7e972011-09-06 21:13:51 +00006068 if (LHS.get()->getType()->isVectorType() ||
6069 RHS.get()->getType()->isVectorType()) {
6070 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006071 if (CompLHSTy) *CompLHSTy = compType;
6072 return compType;
6073 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006074
Richard Trieu4ae7e972011-09-06 21:13:51 +00006075 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6076 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006077 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006078
Steve Naroffe4718892007-04-27 18:30:00 +00006079 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006080 if (LHS.get()->getType()->isArithmeticType() &&
6081 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006082 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006083 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006084 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006085
Eli Friedman8e122982008-05-18 18:08:51 +00006086 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006087 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006088 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006089 std::swap(PExp, IExp);
6090
Richard Trieub420bca2011-09-12 18:37:54 +00006091 if (!PExp->getType()->isAnyPointerType())
6092 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006093
Richard Trieub420bca2011-09-12 18:37:54 +00006094 if (!IExp->getType()->isIntegerType())
6095 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006096
Richard Trieub420bca2011-09-12 18:37:54 +00006097 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6098 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006099
Richard Trieub420bca2011-09-12 18:37:54 +00006100 // Diagnose bad cases where we step over interface counts.
6101 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6102 return QualType();
6103
6104 // Check array bounds for pointer arithemtic
6105 CheckArrayAccess(PExp, IExp);
6106
6107 if (CompLHSTy) {
6108 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6109 if (LHSTy.isNull()) {
6110 LHSTy = LHS.get()->getType();
6111 if (LHSTy->isPromotableIntegerType())
6112 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006113 }
Richard Trieub420bca2011-09-12 18:37:54 +00006114 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006115 }
6116
Richard Trieub420bca2011-09-12 18:37:54 +00006117 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006118}
6119
Chris Lattner2a3569b2008-04-07 05:30:13 +00006120// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006121QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006122 SourceLocation Loc,
6123 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006124 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6125
Richard Trieu4ae7e972011-09-06 21:13:51 +00006126 if (LHS.get()->getType()->isVectorType() ||
6127 RHS.get()->getType()->isVectorType()) {
6128 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006129 if (CompLHSTy) *CompLHSTy = compType;
6130 return compType;
6131 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006132
Richard Trieu4ae7e972011-09-06 21:13:51 +00006133 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6134 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006135 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006136
Chris Lattner4d62f422007-12-09 21:53:25 +00006137 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006138
Chris Lattner4d62f422007-12-09 21:53:25 +00006139 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006140 if (LHS.get()->getType()->isArithmeticType() &&
6141 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006142 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006143 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006144 }
Mike Stump11289f42009-09-09 15:08:12 +00006145
Chris Lattner4d62f422007-12-09 21:53:25 +00006146 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006147 if (LHS.get()->getType()->isAnyPointerType()) {
6148 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006149
Chris Lattner12bdebb2009-04-24 23:50:08 +00006150 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006151 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006152 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006153
Chris Lattner4d62f422007-12-09 21:53:25 +00006154 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006155 if (RHS.get()->getType()->isIntegerType()) {
6156 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006157 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006158
Richard Trieu4ae7e972011-09-06 21:13:51 +00006159 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006160 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6161 OK_Ordinary, IExpr->getExprLoc());
6162 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006163 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006164
Richard Trieu4ae7e972011-09-06 21:13:51 +00006165 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6166 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006167 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006168
Chris Lattner4d62f422007-12-09 21:53:25 +00006169 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006170 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006171 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006172 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006173
Eli Friedman168fe152009-05-16 13:54:38 +00006174 if (getLangOptions().CPlusPlus) {
6175 // Pointee types must be the same: C++ [expr.add]
6176 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006177 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006178 }
6179 } else {
6180 // Pointee types must be compatible C99 6.5.6p3
6181 if (!Context.typesAreCompatible(
6182 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6183 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006184 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006185 return QualType();
6186 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006187 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006188
Chandler Carruthc9332212011-06-27 08:02:19 +00006189 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006190 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006191 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006192
Richard Trieu4ae7e972011-09-06 21:13:51 +00006193 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006194 return Context.getPointerDiffType();
6195 }
6196 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006197
Richard Trieu4ae7e972011-09-06 21:13:51 +00006198 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006199}
6200
Douglas Gregor0bf31402010-10-08 23:50:27 +00006201static bool isScopedEnumerationType(QualType T) {
6202 if (const EnumType *ET = dyn_cast<EnumType>(T))
6203 return ET->getDecl()->isScoped();
6204 return false;
6205}
6206
Richard Trieue4a19fb2011-09-06 21:21:28 +00006207static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006208 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006209 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006210 llvm::APSInt Right;
6211 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006212 if (RHS.get()->isValueDependent() ||
6213 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006214 return;
6215
6216 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006217 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006218 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006219 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006220 return;
6221 }
6222 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006223 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006224 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006225 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006226 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006227 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006228 return;
6229 }
6230 if (Opc != BO_Shl)
6231 return;
6232
6233 // When left shifting an ICE which is signed, we can check for overflow which
6234 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6235 // integers have defined behavior modulo one more than the maximum value
6236 // representable in the result type, so never warn for those.
6237 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006238 if (LHS.get()->isValueDependent() ||
6239 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6240 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006241 return;
6242 llvm::APInt ResultBits =
6243 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6244 if (LeftBits.uge(ResultBits))
6245 return;
6246 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6247 Result = Result.shl(Right);
6248
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006249 // Print the bit representation of the signed integer as an unsigned
6250 // hexadecimal number.
6251 llvm::SmallString<40> HexResult;
6252 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6253
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006254 // If we are only missing a sign bit, this is less likely to result in actual
6255 // bugs -- if the result is cast back to an unsigned type, it will have the
6256 // expected value. Thus we place this behind a different warning that can be
6257 // turned off separately if needed.
6258 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006259 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006260 << HexResult.str() << LHSType
6261 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006262 return;
6263 }
6264
6265 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006266 << HexResult.str() << Result.getMinSignedBits() << LHSType
6267 << Left.getBitWidth() << LHS.get()->getSourceRange()
6268 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006269}
6270
Chris Lattner2a3569b2008-04-07 05:30:13 +00006271// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006272QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006273 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006274 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006275 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6276
Chris Lattner5c11c412007-12-12 05:47:28 +00006277 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006278 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6279 !RHS.get()->getType()->hasIntegerRepresentation())
6280 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006281
Douglas Gregor0bf31402010-10-08 23:50:27 +00006282 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6283 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006284 if (isScopedEnumerationType(LHS.get()->getType()) ||
6285 isScopedEnumerationType(RHS.get()->getType())) {
6286 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006287 }
6288
Nate Begemane46ee9a2009-10-25 02:26:48 +00006289 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006290 if (LHS.get()->getType()->isVectorType() ||
6291 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006292 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006293
Chris Lattner5c11c412007-12-12 05:47:28 +00006294 // Shifts don't perform usual arithmetic conversions, they just do integer
6295 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006296
John McCall57cdd882010-12-16 19:28:59 +00006297 // For the LHS, do usual unary conversions, but then reset them away
6298 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006299 ExprResult OldLHS = LHS;
6300 LHS = UsualUnaryConversions(LHS.take());
6301 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006302 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006303 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006304 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006305
6306 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006307 RHS = UsualUnaryConversions(RHS.take());
6308 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006309 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006310
Ryan Flynnf53fab82009-08-07 16:20:20 +00006311 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006312 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006313
Chris Lattner5c11c412007-12-12 05:47:28 +00006314 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006315 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006316}
6317
Chandler Carruth17773fc2010-07-10 12:30:03 +00006318static bool IsWithinTemplateSpecialization(Decl *D) {
6319 if (DeclContext *DC = D->getDeclContext()) {
6320 if (isa<ClassTemplateSpecializationDecl>(DC))
6321 return true;
6322 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6323 return FD->isFunctionTemplateSpecialization();
6324 }
6325 return false;
6326}
6327
Richard Trieueea56f72011-09-02 03:48:46 +00006328/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006329static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6330 ExprResult &RHS) {
6331 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6332 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006333
6334 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6335 if (!LHSEnumType)
6336 return;
6337 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6338 if (!RHSEnumType)
6339 return;
6340
6341 // Ignore anonymous enums.
6342 if (!LHSEnumType->getDecl()->getIdentifier())
6343 return;
6344 if (!RHSEnumType->getDecl()->getIdentifier())
6345 return;
6346
6347 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6348 return;
6349
6350 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6351 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006352 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006353}
6354
Richard Trieudd82a5c2011-09-02 02:55:45 +00006355/// \brief Diagnose bad pointer comparisons.
6356static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006357 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006358 bool IsError) {
6359 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006360 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006361 << LHS.get()->getType() << RHS.get()->getType()
6362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006363}
6364
6365/// \brief Returns false if the pointers are converted to a composite type,
6366/// true otherwise.
6367static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006368 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006369 // C++ [expr.rel]p2:
6370 // [...] Pointer conversions (4.10) and qualification
6371 // conversions (4.4) are performed on pointer operands (or on
6372 // a pointer operand and a null pointer constant) to bring
6373 // them to their composite pointer type. [...]
6374 //
6375 // C++ [expr.eq]p1 uses the same notion for (in)equality
6376 // comparisons of pointers.
6377
6378 // C++ [expr.eq]p2:
6379 // In addition, pointers to members can be compared, or a pointer to
6380 // member and a null pointer constant. Pointer to member conversions
6381 // (4.11) and qualification conversions (4.4) are performed to bring
6382 // them to a common type. If one operand is a null pointer constant,
6383 // the common type is the type of the other operand. Otherwise, the
6384 // common type is a pointer to member type similar (4.4) to the type
6385 // of one of the operands, with a cv-qualification signature (4.4)
6386 // that is the union of the cv-qualification signatures of the operand
6387 // types.
6388
Richard Trieu1762d7c2011-09-06 21:27:33 +00006389 QualType LHSType = LHS.get()->getType();
6390 QualType RHSType = RHS.get()->getType();
6391 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6392 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006393
6394 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006395 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006396 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006397 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006398 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006399 return true;
6400 }
6401
6402 if (NonStandardCompositeType)
6403 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006404 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6405 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006406
Richard Trieu1762d7c2011-09-06 21:27:33 +00006407 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6408 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006409 return false;
6410}
6411
6412static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006413 ExprResult &LHS,
6414 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006415 bool IsError) {
6416 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6417 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006418 << LHS.get()->getType() << RHS.get()->getType()
6419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006420}
6421
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006422// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006423QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006424 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006425 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006426 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6427
John McCalle3027922010-08-25 11:45:40 +00006428 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006429
Chris Lattner9a152e22009-12-05 05:40:13 +00006430 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006431 if (LHS.get()->getType()->isVectorType() ||
6432 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006433 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006434
Richard Trieub80728f2011-09-06 21:43:51 +00006435 QualType LHSType = LHS.get()->getType();
6436 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006437
Richard Trieub80728f2011-09-06 21:43:51 +00006438 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6439 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006440
Richard Trieub80728f2011-09-06 21:43:51 +00006441 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006442
Richard Trieub80728f2011-09-06 21:43:51 +00006443 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006444 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006445 !LHS.get()->getLocStart().isMacroID() &&
6446 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006447 // For non-floating point types, check for self-comparisons of the form
6448 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6449 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006450 //
6451 // NOTE: Don't warn about comparison expressions resulting from macro
6452 // expansion. Also don't warn about comparisons which are only self
6453 // comparisons within a template specialization. The warnings should catch
6454 // obvious cases in the definition of the template anyways. The idea is to
6455 // warn when the typed comparison operator will always evaluate to the same
6456 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006457 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006458 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006459 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006460 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006461 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006462 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006463 << (Opc == BO_EQ
6464 || Opc == BO_LE
6465 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006466 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006467 !DRL->getDecl()->getType()->isReferenceType() &&
6468 !DRR->getDecl()->getType()->isReferenceType()) {
6469 // what is it always going to eval to?
6470 char always_evals_to;
6471 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006472 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006473 always_evals_to = 0; // false
6474 break;
John McCalle3027922010-08-25 11:45:40 +00006475 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006476 always_evals_to = 1; // true
6477 break;
6478 default:
6479 // best we can say is 'a constant'
6480 always_evals_to = 2; // e.g. array1 <= array2
6481 break;
6482 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006483 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006484 << 1 // array
6485 << always_evals_to);
6486 }
6487 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006488 }
Mike Stump11289f42009-09-09 15:08:12 +00006489
Chris Lattner222b8bd2009-03-08 19:39:53 +00006490 if (isa<CastExpr>(LHSStripped))
6491 LHSStripped = LHSStripped->IgnoreParenCasts();
6492 if (isa<CastExpr>(RHSStripped))
6493 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006494
Chris Lattner222b8bd2009-03-08 19:39:53 +00006495 // Warn about comparisons against a string constant (unless the other
6496 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006497 Expr *literalString = 0;
6498 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006499 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006500 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006501 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006502 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006503 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006504 } else if ((isa<StringLiteral>(RHSStripped) ||
6505 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006506 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006507 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006508 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006509 literalStringStripped = RHSStripped;
6510 }
6511
6512 if (literalString) {
6513 std::string resultComparison;
6514 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006515 case BO_LT: resultComparison = ") < 0"; break;
6516 case BO_GT: resultComparison = ") > 0"; break;
6517 case BO_LE: resultComparison = ") <= 0"; break;
6518 case BO_GE: resultComparison = ") >= 0"; break;
6519 case BO_EQ: resultComparison = ") == 0"; break;
6520 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006521 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006522 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006523
Ted Kremenek3427fac2011-02-23 01:52:04 +00006524 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006525 PDiag(diag::warn_stringcompare)
6526 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006527 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006528 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006529 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006530
Douglas Gregorec170db2010-06-08 19:50:34 +00006531 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006532 if (LHS.get()->getType()->isArithmeticType() &&
6533 RHS.get()->getType()->isArithmeticType()) {
6534 UsualArithmeticConversions(LHS, RHS);
6535 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006536 return QualType();
6537 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006538 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006539 LHS = UsualUnaryConversions(LHS.take());
6540 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006541 return QualType();
6542
Richard Trieub80728f2011-09-06 21:43:51 +00006543 RHS = UsualUnaryConversions(RHS.take());
6544 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006545 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006546 }
6547
Richard Trieub80728f2011-09-06 21:43:51 +00006548 LHSType = LHS.get()->getType();
6549 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006550
Douglas Gregorca63811b2008-11-19 03:25:36 +00006551 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006552 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006553
Richard Trieuba63ce62011-09-09 01:45:06 +00006554 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006555 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006556 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006557 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006558 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006559 if (LHSType->hasFloatingRepresentation())
6560 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006561
Richard Trieub80728f2011-09-06 21:43:51 +00006562 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006563 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006564 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006565
Richard Trieub80728f2011-09-06 21:43:51 +00006566 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006567 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006568 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006569 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006570
Douglas Gregorf267edd2010-06-15 21:38:40 +00006571 // All of the following pointer-related warnings are GCC extensions, except
6572 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006573 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006574 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006575 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006576 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006577 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006578
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006579 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006580 if (LCanPointeeTy == RCanPointeeTy)
6581 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006582 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006583 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6584 // Valid unless comparison between non-null pointer and function pointer
6585 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006586 // In a SFINAE context, we treat this as a hard error to maintain
6587 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006588 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6589 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006590 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006591 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006592
6593 if (isSFINAEContext())
6594 return QualType();
6595
Richard Trieub80728f2011-09-06 21:43:51 +00006596 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006597 return ResultTy;
6598 }
6599 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006600
Richard Trieub80728f2011-09-06 21:43:51 +00006601 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006602 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006603 else
6604 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006605 }
Eli Friedman16c209612009-08-23 00:27:47 +00006606 // C99 6.5.9p2 and C99 6.5.8p2
6607 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6608 RCanPointeeTy.getUnqualifiedType())) {
6609 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006610 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006611 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006612 << LHSType << RHSType << LHS.get()->getSourceRange()
6613 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006614 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006615 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006616 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6617 // Valid unless comparison between non-null pointer and function pointer
6618 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006619 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006620 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006621 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006622 } else {
6623 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006624 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006625 }
John McCall7684dde2011-03-11 04:25:25 +00006626 if (LCanPointeeTy != RCanPointeeTy) {
6627 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006628 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006629 else
Richard Trieub80728f2011-09-06 21:43:51 +00006630 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006631 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006632 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006633 }
Mike Stump11289f42009-09-09 15:08:12 +00006634
Sebastian Redl576fd422009-05-10 18:38:11 +00006635 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006636 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006637 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006638 return ResultTy;
6639
Mike Stump11289f42009-09-09 15:08:12 +00006640 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006641 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006642 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006643 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006644 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006645 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6646 RHS = ImpCastExprToType(RHS.take(), LHSType,
6647 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006648 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006649 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006650 return ResultTy;
6651 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006652 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006653 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006654 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006655 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6656 LHS = ImpCastExprToType(LHS.take(), RHSType,
6657 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006658 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006659 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006660 return ResultTy;
6661 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006662
6663 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006664 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006665 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6666 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006667 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006668 else
6669 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006670 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006671
6672 // Handle scoped enumeration types specifically, since they don't promote
6673 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006674 if (LHS.get()->getType()->isEnumeralType() &&
6675 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6676 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006677 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006678 }
Mike Stump11289f42009-09-09 15:08:12 +00006679
Steve Naroff081c7422008-09-04 15:10:53 +00006680 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006681 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006682 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006683 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6684 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006685
Steve Naroff081c7422008-09-04 15:10:53 +00006686 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006687 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006688 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006689 << LHSType << RHSType << LHS.get()->getSourceRange()
6690 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006691 }
Richard Trieub80728f2011-09-06 21:43:51 +00006692 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006693 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006694 }
John Wiegley01296292011-04-08 18:41:53 +00006695
Steve Naroffe18f94c2008-09-28 01:11:11 +00006696 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006697 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006698 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6699 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006700 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006701 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006702 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006703 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006704 ->getPointeeType()->isVoidType())))
6705 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006706 << LHSType << RHSType << LHS.get()->getSourceRange()
6707 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006708 }
John McCall7684dde2011-03-11 04:25:25 +00006709 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006710 LHS = ImpCastExprToType(LHS.take(), RHSType,
6711 RHSType->isPointerType() ? CK_BitCast
6712 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006713 else
John McCall9320b872011-09-09 05:25:32 +00006714 RHS = ImpCastExprToType(RHS.take(), LHSType,
6715 LHSType->isPointerType() ? CK_BitCast
6716 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006717 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006718 }
Steve Naroff081c7422008-09-04 15:10:53 +00006719
Richard Trieub80728f2011-09-06 21:43:51 +00006720 if (LHSType->isObjCObjectPointerType() ||
6721 RHSType->isObjCObjectPointerType()) {
6722 const PointerType *LPT = LHSType->getAs<PointerType>();
6723 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006724 if (LPT || RPT) {
6725 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6726 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006727
Steve Naroff753567f2008-11-17 19:49:16 +00006728 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006729 !Context.typesAreCompatible(LHSType, RHSType)) {
6730 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006731 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006732 }
John McCall7684dde2011-03-11 04:25:25 +00006733 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006734 LHS = ImpCastExprToType(LHS.take(), RHSType,
6735 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006736 else
John McCall9320b872011-09-09 05:25:32 +00006737 RHS = ImpCastExprToType(RHS.take(), LHSType,
6738 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006739 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006740 }
Richard Trieub80728f2011-09-06 21:43:51 +00006741 if (LHSType->isObjCObjectPointerType() &&
6742 RHSType->isObjCObjectPointerType()) {
6743 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6744 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006745 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006746 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006747 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006748 else
Richard Trieub80728f2011-09-06 21:43:51 +00006749 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006750 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006751 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006752 }
Richard Trieub80728f2011-09-06 21:43:51 +00006753 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6754 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006755 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006756 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006757 if ((LHSIsNull && LHSType->isIntegerType()) ||
6758 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006759 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006760 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006761 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006762 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006763 else if (getLangOptions().CPlusPlus) {
6764 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6765 isError = true;
6766 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006767 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006768
Chris Lattnerd99bd522009-08-23 00:03:44 +00006769 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006770 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006771 << LHSType << RHSType << LHS.get()->getSourceRange()
6772 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006773 if (isError)
6774 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006775 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006776
Richard Trieub80728f2011-09-06 21:43:51 +00006777 if (LHSType->isIntegerType())
6778 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006779 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006780 else
Richard Trieub80728f2011-09-06 21:43:51 +00006781 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006782 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006783 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006784 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006785
Steve Naroff4b191572008-09-04 16:56:14 +00006786 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006787 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006788 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6789 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006790 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006791 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006792 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006793 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6794 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006795 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006796 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006797
Richard Trieub80728f2011-09-06 21:43:51 +00006798 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006799}
6800
Nate Begeman191a6b12008-07-14 18:02:46 +00006801/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006802/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006803/// like a scalar comparison, a vector comparison produces a vector of integer
6804/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006805QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006806 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006807 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006808 // Check to make sure we're operating on vectors of the same type and width,
6809 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006810 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006811 if (vType.isNull())
6812 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006813
Richard Trieubcce2f72011-09-07 01:19:57 +00006814 QualType LHSType = LHS.get()->getType();
6815 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006816
Anton Yartsev530deb92011-03-27 15:36:07 +00006817 // If AltiVec, the comparison results in a numeric type, i.e.
6818 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006819 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006820 return Context.getLogicalOperationType();
6821
Nate Begeman191a6b12008-07-14 18:02:46 +00006822 // For non-floating point types, check for self-comparisons of the form
6823 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6824 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006825 if (!LHSType->hasFloatingRepresentation()) {
6826 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6827 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006828 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006829 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006830 PDiag(diag::warn_comparison_always)
6831 << 0 // self-
6832 << 2 // "a constant"
6833 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006834 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006835
Nate Begeman191a6b12008-07-14 18:02:46 +00006836 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006837 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006838 assert (RHSType->hasFloatingRepresentation());
6839 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006840 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006841
Nate Begeman191a6b12008-07-14 18:02:46 +00006842 // Return the type for the comparison, which is the same as vector type for
6843 // integer vectors, or an integer type of identical size and number of
6844 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006845 if (LHSType->hasIntegerRepresentation())
6846 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006847
Richard Trieubcce2f72011-09-07 01:19:57 +00006848 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006849 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006850 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006851 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006852 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006853 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6854
Mike Stump4e1f26a2009-02-19 03:04:26 +00006855 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006856 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006857 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6858}
6859
Steve Naroff218bc2b2007-05-04 21:54:46 +00006860inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006861 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006862 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6863
Richard Trieubcce2f72011-09-07 01:19:57 +00006864 if (LHS.get()->getType()->isVectorType() ||
6865 RHS.get()->getType()->isVectorType()) {
6866 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6867 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006868 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006869
Richard Trieubcce2f72011-09-07 01:19:57 +00006870 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006871 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006872
Richard Trieubcce2f72011-09-07 01:19:57 +00006873 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6874 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006875 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006876 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006877 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006878 LHS = LHSResult.take();
6879 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006880
Richard Trieubcce2f72011-09-07 01:19:57 +00006881 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6882 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006883 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006884 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006885}
6886
Steve Naroff218bc2b2007-05-04 21:54:46 +00006887inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006888 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006889
6890 // Diagnose cases where the user write a logical and/or but probably meant a
6891 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6892 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006893 if (LHS.get()->getType()->isIntegerType() &&
6894 !LHS.get()->getType()->isBooleanType() &&
6895 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006896 // Don't warn in macros or template instantiations.
6897 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006898 // If the RHS can be constant folded, and if it constant folds to something
6899 // that isn't 0 or 1 (which indicate a potential logical operation that
6900 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006901 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006902 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006903 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6904 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006905 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6906 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006907 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006908 << (Opc == BO_LAnd ? "&&" : "||");
6909 // Suggest replacing the logical operator with the bitwise version
6910 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6911 << (Opc == BO_LAnd ? "&" : "|")
6912 << FixItHint::CreateReplacement(SourceRange(
6913 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6914 getLangOptions())),
6915 Opc == BO_LAnd ? "&" : "|");
6916 if (Opc == BO_LAnd)
6917 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6918 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6919 << FixItHint::CreateRemoval(
6920 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006921 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006922 0, getSourceManager(),
6923 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006924 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006925 }
Chris Lattner938533d2010-07-24 01:10:11 +00006926 }
Chris Lattner8406c512010-07-13 19:41:32 +00006927
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006928 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006929 LHS = UsualUnaryConversions(LHS.take());
6930 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006931 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006932
Richard Trieubcce2f72011-09-07 01:19:57 +00006933 RHS = UsualUnaryConversions(RHS.take());
6934 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006935 return QualType();
6936
Richard Trieubcce2f72011-09-07 01:19:57 +00006937 if (!LHS.get()->getType()->isScalarType() ||
6938 !RHS.get()->getType()->isScalarType())
6939 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006940
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006941 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006942 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006943
John McCall4a2429a2010-06-04 00:29:51 +00006944 // The following is safe because we only use this method for
6945 // non-overloadable operands.
6946
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006947 // C++ [expr.log.and]p1
6948 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006949 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006950 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6951 if (LHSRes.isInvalid())
6952 return InvalidOperands(Loc, LHS, RHS);
6953 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006954
Richard Trieubcce2f72011-09-07 01:19:57 +00006955 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6956 if (RHSRes.isInvalid())
6957 return InvalidOperands(Loc, LHS, RHS);
6958 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006959
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006960 // C++ [expr.log.and]p2
6961 // C++ [expr.log.or]p2
6962 // The result is a bool.
6963 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006964}
6965
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006966/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6967/// is a read-only property; return true if so. A readonly property expression
6968/// depends on various declarations and thus must be treated specially.
6969///
Mike Stump11289f42009-09-09 15:08:12 +00006970static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006971 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6972 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006973 if (PropExpr->isImplicitProperty()) return false;
6974
6975 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6976 QualType BaseType = PropExpr->isSuperReceiver() ?
6977 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006978 PropExpr->getBase()->getType();
6979
John McCallb7bd14f2010-12-02 01:19:52 +00006980 if (const ObjCObjectPointerType *OPT =
6981 BaseType->getAsObjCInterfacePointerType())
6982 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6983 if (S.isPropertyReadonly(PDecl, IFace))
6984 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006985 }
6986 return false;
6987}
6988
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006989static bool IsConstProperty(Expr *E, Sema &S) {
6990 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6991 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6992 if (PropExpr->isImplicitProperty()) return false;
6993
6994 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6995 QualType T = PDecl->getType();
6996 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006997 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006998 CanQualType CT = S.Context.getCanonicalType(T);
6999 return CT.isConstQualified();
7000 }
7001 return false;
7002}
7003
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007004static bool IsReadonlyMessage(Expr *E, Sema &S) {
7005 if (E->getStmtClass() != Expr::MemberExprClass)
7006 return false;
7007 const MemberExpr *ME = cast<MemberExpr>(E);
7008 NamedDecl *Member = ME->getMemberDecl();
7009 if (isa<FieldDecl>(Member)) {
7010 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7011 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7012 return false;
7013 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7014 }
7015 return false;
7016}
7017
Chris Lattner30bd3272008-11-18 01:22:49 +00007018/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7019/// emit an error and return true. If so, return false.
7020static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007021 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007022 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007023 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007024 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7025 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007026 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7027 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007028 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7029 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007030 if (IsLV == Expr::MLV_Valid)
7031 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007032
Chris Lattner30bd3272008-11-18 01:22:49 +00007033 unsigned Diag = 0;
7034 bool NeedType = false;
7035 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007036 case Expr::MLV_ConstQualified:
7037 Diag = diag::err_typecheck_assign_const;
7038
John McCalld4631322011-06-17 06:42:21 +00007039 // In ARC, use some specialized diagnostics for occasions where we
7040 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007041 if (S.getLangOptions().ObjCAutoRefCount) {
7042 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7043 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7044 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7045
John McCalld4631322011-06-17 06:42:21 +00007046 // Use the normal diagnostic if it's pseudo-__strong but the
7047 // user actually wrote 'const'.
7048 if (var->isARCPseudoStrong() &&
7049 (!var->getTypeSourceInfo() ||
7050 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7051 // There are two pseudo-strong cases:
7052 // - self
John McCall31168b02011-06-15 23:02:42 +00007053 ObjCMethodDecl *method = S.getCurMethodDecl();
7054 if (method && var == method->getSelfDecl())
7055 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007056
7057 // - fast enumeration variables
7058 else
John McCall31168b02011-06-15 23:02:42 +00007059 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007060
John McCall31168b02011-06-15 23:02:42 +00007061 SourceRange Assign;
7062 if (Loc != OrigLoc)
7063 Assign = SourceRange(OrigLoc, OrigLoc);
7064 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7065 // We need to preserve the AST regardless, so migration tool
7066 // can do its job.
7067 return false;
7068 }
7069 }
7070 }
7071
7072 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007073 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007074 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7075 NeedType = true;
7076 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007077 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007078 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7079 NeedType = true;
7080 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007081 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007082 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7083 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007084 case Expr::MLV_Valid:
7085 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007086 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007087 case Expr::MLV_MemberFunction:
7088 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007089 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7090 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007091 case Expr::MLV_IncompleteType:
7092 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007093 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007094 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007095 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007096 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007097 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7098 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007099 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007100 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7101 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007102 case Expr::MLV_ReadonlyProperty:
7103 Diag = diag::error_readonly_property_assignment;
7104 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007105 case Expr::MLV_NoSetterProperty:
7106 Diag = diag::error_nosetter_property_assignment;
7107 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007108 case Expr::MLV_InvalidMessageExpression:
7109 Diag = diag::error_readonly_message_assignment;
7110 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007111 case Expr::MLV_SubObjCPropertySetting:
7112 Diag = diag::error_no_subobject_property_setting;
7113 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007114 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007115
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007116 SourceRange Assign;
7117 if (Loc != OrigLoc)
7118 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007119 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007120 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007121 else
Mike Stump11289f42009-09-09 15:08:12 +00007122 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007123 return true;
7124}
7125
7126
7127
7128// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007129QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007130 SourceLocation Loc,
7131 QualType CompoundType) {
7132 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007133 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007134 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007135
Richard Trieuda4f43a62011-09-07 01:33:52 +00007136 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007137 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7138 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007139 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007140 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007141 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007142 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007143 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7144 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007145 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7146 if (LHSResult.isInvalid())
7147 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007148 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007149 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007150 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007151 if (RHS.isInvalid())
7152 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007153 // Special case of NSObject attributes on c-style pointer types.
7154 if (ConvTy == IncompatiblePointer &&
7155 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007156 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007157 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007158 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007159 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007160
John McCall7decc9e2010-11-18 06:31:45 +00007161 if (ConvTy == Compatible &&
7162 getLangOptions().ObjCNonFragileABI &&
7163 LHSType->isObjCObjectType())
7164 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7165 << LHSType;
7166
Chris Lattnerea714382008-08-21 18:04:13 +00007167 // If the RHS is a unary plus or minus, check to see if they = and + are
7168 // right next to each other. If so, the user may have typo'd "x =+ 4"
7169 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007170 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007171 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7172 RHSCheck = ICE->getSubExpr();
7173 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007174 if ((UO->getOpcode() == UO_Plus ||
7175 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007176 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007177 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007178 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007179 // And there is a space or other character before the subexpr of the
7180 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007181 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007182 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007183 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007184 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007185 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007186 }
Chris Lattnerea714382008-08-21 18:04:13 +00007187 }
John McCall31168b02011-06-15 23:02:42 +00007188
7189 if (ConvTy == Compatible) {
7190 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007191 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007192 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007193 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007194 }
Chris Lattnerea714382008-08-21 18:04:13 +00007195 } else {
7196 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007197 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007198 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007199
Chris Lattner326f7572008-11-18 01:30:42 +00007200 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007201 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007202 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203
Richard Trieuda4f43a62011-09-07 01:33:52 +00007204 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007205
Steve Naroff98cf3e92007-06-06 18:38:38 +00007206 // C99 6.5.16p3: The type of an assignment expression is the type of the
7207 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007208 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007209 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7210 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007211 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007212 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007213 return (getLangOptions().CPlusPlus
7214 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007215}
7216
Chris Lattner326f7572008-11-18 01:30:42 +00007217// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007218static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007219 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007220 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007221
John McCall3aef3d82011-04-10 19:13:55 +00007222 LHS = S.CheckPlaceholderExpr(LHS.take());
7223 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007224 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007225 return QualType();
7226
John McCall73d36182010-10-12 07:14:40 +00007227 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7228 // operands, but not unary promotions.
7229 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007230
John McCall34376a62010-12-04 03:47:34 +00007231 // So we treat the LHS as a ignored value, and in C++ we allow the
7232 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007233 LHS = S.IgnoredValueConversions(LHS.take());
7234 if (LHS.isInvalid())
7235 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007236
7237 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007238 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7239 if (RHS.isInvalid())
7240 return QualType();
7241 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007242 S.RequireCompleteType(Loc, RHS.get()->getType(),
7243 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007244 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007245
John Wiegley01296292011-04-08 18:41:53 +00007246 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007247}
7248
Steve Naroff7a5af782007-07-13 16:58:59 +00007249/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7250/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007251static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7252 ExprValueKind &VK,
7253 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007254 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007255 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007256 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007257
Chris Lattner6b0cf142008-11-21 07:05:48 +00007258 QualType ResType = Op->getType();
7259 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007260
John McCall4bc41ae2010-11-18 19:01:18 +00007261 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007262 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007263 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007264 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007265 return QualType();
7266 }
7267 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007268 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007269 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007270 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007271 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007272 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007273 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007274 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007275
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007276 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007277 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007278 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007279 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007280 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007281 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007282 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007283 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007284 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007285 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007286 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007287 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007288 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7289 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007290 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007291 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007292 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007293 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007294 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007295 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007296 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007297 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007298 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007299 // In C++, a prefix increment is the same type as the operand. Otherwise
7300 // (in C or with postfix), the increment is the unqualified type of the
7301 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007302 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007303 VK = VK_LValue;
7304 return ResType;
7305 } else {
7306 VK = VK_RValue;
7307 return ResType.getUnqualifiedType();
7308 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007309}
7310
John Wiegley01296292011-04-08 18:41:53 +00007311ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007312 assert(E->getValueKind() == VK_LValue &&
7313 E->getObjectKind() == OK_ObjCProperty);
7314 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7315
Douglas Gregor33823722011-06-11 01:09:30 +00007316 QualType T = E->getType();
7317 QualType ReceiverType;
7318 if (PRE->isObjectReceiver())
7319 ReceiverType = PRE->getBase()->getType();
7320 else if (PRE->isSuperReceiver())
7321 ReceiverType = PRE->getSuperReceiverType();
7322 else
7323 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7324
John McCall34376a62010-12-04 03:47:34 +00007325 ExprValueKind VK = VK_RValue;
7326 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007327 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007328 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007329 T = getMessageSendResultType(ReceiverType, GetterMethod,
7330 PRE->isClassReceiver(),
7331 PRE->isSuperReceiver());
7332 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007333 }
7334 else {
7335 Diag(PRE->getLocation(), diag::err_getter_not_found)
7336 << PRE->getBase()->getType();
7337 }
John McCall34376a62010-12-04 03:47:34 +00007338 }
Douglas Gregor33823722011-06-11 01:09:30 +00007339
7340 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007341 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007342
7343 ExprResult Result = MaybeBindToTemporary(E);
7344 if (!Result.isInvalid())
7345 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007346
7347 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007348}
7349
Richard Trieucfc491d2011-08-02 04:35:43 +00007350void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7351 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007352 assert(LHS.get()->getValueKind() == VK_LValue &&
7353 LHS.get()->getObjectKind() == OK_ObjCProperty);
7354 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007355
John McCall31168b02011-06-15 23:02:42 +00007356 bool Consumed = false;
7357
John Wiegley01296292011-04-08 18:41:53 +00007358 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007359 // If using property-dot syntax notation for assignment, and there is a
7360 // setter, RHS expression is being passed to the setter argument. So,
7361 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007362 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007363 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7364 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007365 Consumed = (getLangOptions().ObjCAutoRefCount &&
7366 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007367
7368 // Otherwise, if the getter returns an l-value, just call that.
7369 } else {
John Wiegley01296292011-04-08 18:41:53 +00007370 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007371 ExprValueKind VK = Expr::getValueKindForType(Result);
7372 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007373 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7374 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007375 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007376 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007377 }
John McCall31168b02011-06-15 23:02:42 +00007378 } else if (getLangOptions().ObjCAutoRefCount) {
7379 const ObjCMethodDecl *setter
7380 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7381 if (setter) {
7382 ObjCMethodDecl::param_iterator P = setter->param_begin();
7383 LHSTy = (*P)->getType();
7384 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7385 }
John McCall34376a62010-12-04 03:47:34 +00007386 }
7387
John McCall31168b02011-06-15 23:02:42 +00007388 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7389 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007390 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007391 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007392 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007393 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007394 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007395 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7396 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7397 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007398 }
7399}
7400
7401
Anders Carlsson806700f2008-02-01 07:15:58 +00007402/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007403/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007404/// where the declaration is needed for type checking. We only need to
7405/// handle cases when the expression references a function designator
7406/// or is an lvalue. Here are some examples:
7407/// - &(x) => x
7408/// - &*****f => f for f a function designator.
7409/// - &s.xx => s
7410/// - &s.zz[1].yy -> s, if zz is an array
7411/// - *(x + 1) -> x, if x is an array
7412/// - &"123"[2] -> 0
7413/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007414static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007415 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007416 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007417 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007418 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007419 // If this is an arrow operator, the address is an offset from
7420 // the base's value, so the object the base refers to is
7421 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007422 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007423 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007424 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007425 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007426 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007427 // FIXME: This code shouldn't be necessary! We should catch the implicit
7428 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007429 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7430 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7431 if (ICE->getSubExpr()->getType()->isArrayType())
7432 return getPrimaryDecl(ICE->getSubExpr());
7433 }
7434 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007435 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007436 case Stmt::UnaryOperatorClass: {
7437 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007438
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007439 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007440 case UO_Real:
7441 case UO_Imag:
7442 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007443 return getPrimaryDecl(UO->getSubExpr());
7444 default:
7445 return 0;
7446 }
7447 }
Steve Naroff47500512007-04-19 23:00:49 +00007448 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007449 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007450 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007451 // If the result of an implicit cast is an l-value, we care about
7452 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007453 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007454 default:
7455 return 0;
7456 }
7457}
7458
Richard Trieu5f376f62011-09-07 21:46:33 +00007459namespace {
7460 enum {
7461 AO_Bit_Field = 0,
7462 AO_Vector_Element = 1,
7463 AO_Property_Expansion = 2,
7464 AO_Register_Variable = 3,
7465 AO_No_Error = 4
7466 };
7467}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007468/// \brief Diagnose invalid operand for address of operations.
7469///
7470/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007471static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7472 Expr *E, unsigned Type) {
7473 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7474}
7475
Steve Naroff47500512007-04-19 23:00:49 +00007476/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007477/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007478/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007479/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007480/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007481/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007482/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007483static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7484 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007485 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007486 return S.Context.DependentTy;
7487 if (OrigOp->getType() == S.Context.OverloadTy)
7488 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007489 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7490 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007491 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7492 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7493 << OrigOp->getSourceRange();
7494 return QualType();
7495 }
John McCall8d08b9b2010-08-27 09:08:28 +00007496
John McCall2979fe02011-04-12 00:42:48 +00007497 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007498
John McCall8d08b9b2010-08-27 09:08:28 +00007499 // Make sure to ignore parentheses in subsequent checks
7500 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007501
John McCall4bc41ae2010-11-18 19:01:18 +00007502 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007503 // Implement C99-only parts of addressof rules.
7504 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007505 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007506 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7507 // (assuming the deref expression is valid).
7508 return uOp->getSubExpr()->getType();
7509 }
7510 // Technically, there should be a check for array subscript
7511 // expressions here, but the result of one is always an lvalue anyway.
7512 }
John McCallf3a88602011-02-03 08:15:49 +00007513 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007514 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007515 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007516
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007517 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007518 bool sfinae = S.isSFINAEContext();
7519 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7520 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007521 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007522 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007523 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007524 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007525 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007526 } else if (lval == Expr::LV_MemberFunction) {
7527 // If it's an instance method, make a member pointer.
7528 // The expression must have exactly the form &A::foo.
7529
7530 // If the underlying expression isn't a decl ref, give up.
7531 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007532 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007533 << OrigOp->getSourceRange();
7534 return QualType();
7535 }
7536 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7537 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7538
7539 // The id-expression was parenthesized.
7540 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007541 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007542 << OrigOp->getSourceRange();
7543
7544 // The method was named without a qualifier.
7545 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007546 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007547 << op->getSourceRange();
7548 }
7549
John McCall4bc41ae2010-11-18 19:01:18 +00007550 return S.Context.getMemberPointerType(op->getType(),
7551 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007552 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007553 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007554 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007555 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007556 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007557 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007558 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007559 return QualType();
7560 }
John McCall086a4642010-11-24 05:12:34 +00007561 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007562 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007563 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007564 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007565 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007566 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007567 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007568 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007569 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007570 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007571 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007572 // with the register storage-class specifier.
7573 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007574 // in C++ it is not error to take address of a register
7575 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007576 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007577 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007578 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007579 }
John McCalld14a8642009-11-21 08:51:07 +00007580 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007581 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007582 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007583 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007584 // Could be a pointer to member, though, if there is an explicit
7585 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007586 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007587 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007588 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007589 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007590 S.Diag(OpLoc,
7591 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007592 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007593 return QualType();
7594 }
Mike Stump11289f42009-09-09 15:08:12 +00007595
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007596 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7597 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007598 return S.Context.getMemberPointerType(op->getType(),
7599 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007600 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007601 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007602 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007603 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007604 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007605
Richard Trieu5f376f62011-09-07 21:46:33 +00007606 if (AddressOfError != AO_No_Error) {
7607 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7608 return QualType();
7609 }
7610
Eli Friedmance7f9002009-05-16 23:27:50 +00007611 if (lval == Expr::LV_IncompleteVoidType) {
7612 // Taking the address of a void variable is technically illegal, but we
7613 // allow it in cases which are otherwise valid.
7614 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007615 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007616 }
7617
Steve Naroff47500512007-04-19 23:00:49 +00007618 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007619 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007620 return S.Context.getObjCObjectPointerType(op->getType());
7621 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007622}
7623
Chris Lattner9156f1b2010-07-05 19:17:26 +00007624/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007625static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7626 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007627 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007628 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007629
John Wiegley01296292011-04-08 18:41:53 +00007630 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7631 if (ConvResult.isInvalid())
7632 return QualType();
7633 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007634 QualType OpTy = Op->getType();
7635 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007636
7637 if (isa<CXXReinterpretCastExpr>(Op)) {
7638 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7639 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7640 Op->getSourceRange());
7641 }
7642
Chris Lattner9156f1b2010-07-05 19:17:26 +00007643 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7644 // is an incomplete type or void. It would be possible to warn about
7645 // dereferencing a void pointer, but it's completely well-defined, and such a
7646 // warning is unlikely to catch any mistakes.
7647 if (const PointerType *PT = OpTy->getAs<PointerType>())
7648 Result = PT->getPointeeType();
7649 else if (const ObjCObjectPointerType *OPT =
7650 OpTy->getAs<ObjCObjectPointerType>())
7651 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007652 else {
John McCall3aef3d82011-04-10 19:13:55 +00007653 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007654 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007655 if (PR.take() != Op)
7656 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007657 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007658
Chris Lattner9156f1b2010-07-05 19:17:26 +00007659 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007660 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007661 << OpTy << Op->getSourceRange();
7662 return QualType();
7663 }
John McCall4bc41ae2010-11-18 19:01:18 +00007664
7665 // Dereferences are usually l-values...
7666 VK = VK_LValue;
7667
7668 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007669 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007670 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007671
7672 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007673}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007674
John McCalle3027922010-08-25 11:45:40 +00007675static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007676 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007677 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007678 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007679 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007680 case tok::periodstar: Opc = BO_PtrMemD; break;
7681 case tok::arrowstar: Opc = BO_PtrMemI; break;
7682 case tok::star: Opc = BO_Mul; break;
7683 case tok::slash: Opc = BO_Div; break;
7684 case tok::percent: Opc = BO_Rem; break;
7685 case tok::plus: Opc = BO_Add; break;
7686 case tok::minus: Opc = BO_Sub; break;
7687 case tok::lessless: Opc = BO_Shl; break;
7688 case tok::greatergreater: Opc = BO_Shr; break;
7689 case tok::lessequal: Opc = BO_LE; break;
7690 case tok::less: Opc = BO_LT; break;
7691 case tok::greaterequal: Opc = BO_GE; break;
7692 case tok::greater: Opc = BO_GT; break;
7693 case tok::exclaimequal: Opc = BO_NE; break;
7694 case tok::equalequal: Opc = BO_EQ; break;
7695 case tok::amp: Opc = BO_And; break;
7696 case tok::caret: Opc = BO_Xor; break;
7697 case tok::pipe: Opc = BO_Or; break;
7698 case tok::ampamp: Opc = BO_LAnd; break;
7699 case tok::pipepipe: Opc = BO_LOr; break;
7700 case tok::equal: Opc = BO_Assign; break;
7701 case tok::starequal: Opc = BO_MulAssign; break;
7702 case tok::slashequal: Opc = BO_DivAssign; break;
7703 case tok::percentequal: Opc = BO_RemAssign; break;
7704 case tok::plusequal: Opc = BO_AddAssign; break;
7705 case tok::minusequal: Opc = BO_SubAssign; break;
7706 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7707 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7708 case tok::ampequal: Opc = BO_AndAssign; break;
7709 case tok::caretequal: Opc = BO_XorAssign; break;
7710 case tok::pipeequal: Opc = BO_OrAssign; break;
7711 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007712 }
7713 return Opc;
7714}
7715
John McCalle3027922010-08-25 11:45:40 +00007716static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007717 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007718 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007719 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007720 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007721 case tok::plusplus: Opc = UO_PreInc; break;
7722 case tok::minusminus: Opc = UO_PreDec; break;
7723 case tok::amp: Opc = UO_AddrOf; break;
7724 case tok::star: Opc = UO_Deref; break;
7725 case tok::plus: Opc = UO_Plus; break;
7726 case tok::minus: Opc = UO_Minus; break;
7727 case tok::tilde: Opc = UO_Not; break;
7728 case tok::exclaim: Opc = UO_LNot; break;
7729 case tok::kw___real: Opc = UO_Real; break;
7730 case tok::kw___imag: Opc = UO_Imag; break;
7731 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007732 }
7733 return Opc;
7734}
7735
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007736/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7737/// This warning is only emitted for builtin assignment operations. It is also
7738/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007739static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007740 SourceLocation OpLoc) {
7741 if (!S.ActiveTemplateInstantiations.empty())
7742 return;
7743 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7744 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007745 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7746 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7747 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7748 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7749 if (!LHSDeclRef || !RHSDeclRef ||
7750 LHSDeclRef->getLocation().isMacroID() ||
7751 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007752 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007753 const ValueDecl *LHSDecl =
7754 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7755 const ValueDecl *RHSDecl =
7756 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7757 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007758 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007759 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007760 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007761 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007762 if (RefTy->getPointeeType().isVolatileQualified())
7763 return;
7764
7765 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007766 << LHSDeclRef->getType()
7767 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007768}
7769
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007770/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7771/// operator @p Opc at location @c TokLoc. This routine only supports
7772/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007773ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007774 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007775 Expr *LHSExpr, Expr *RHSExpr) {
7776 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007777 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007778 // The following two variables are used for compound assignment operators
7779 QualType CompLHSTy; // Type of LHS after promotions for computation
7780 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007781 ExprValueKind VK = VK_RValue;
7782 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007783
Douglas Gregor1beec452011-03-12 01:48:56 +00007784 // Check if a 'foo<int>' involved in a binary op, identifies a single
7785 // function unambiguously (i.e. an lvalue ala 13.4)
7786 // But since an assignment can trigger target based overload, exclude it in
7787 // our blind search. i.e:
7788 // template<class T> void f(); template<class T, class U> void f(U);
7789 // f<int> == 0; // resolve f<int> blindly
7790 // void (*p)(int); p = f<int>; // resolve f<int> using target
7791 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007792 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007793 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007794 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007795
Richard Trieu4a287fb2011-09-07 01:49:20 +00007796 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007797 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007798 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007799 }
7800
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007801 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007802 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007803 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007804 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007805 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7806 VK = LHS.get()->getValueKind();
7807 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007808 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007809 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007810 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007811 break;
John McCalle3027922010-08-25 11:45:40 +00007812 case BO_PtrMemD:
7813 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007814 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007815 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007816 break;
John McCalle3027922010-08-25 11:45:40 +00007817 case BO_Mul:
7818 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007819 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007820 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007821 break;
John McCalle3027922010-08-25 11:45:40 +00007822 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007823 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007824 break;
John McCalle3027922010-08-25 11:45:40 +00007825 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007826 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007827 break;
John McCalle3027922010-08-25 11:45:40 +00007828 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007829 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007830 break;
John McCalle3027922010-08-25 11:45:40 +00007831 case BO_Shl:
7832 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007833 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007834 break;
John McCalle3027922010-08-25 11:45:40 +00007835 case BO_LE:
7836 case BO_LT:
7837 case BO_GE:
7838 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007839 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007840 break;
John McCalle3027922010-08-25 11:45:40 +00007841 case BO_EQ:
7842 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007843 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007844 break;
John McCalle3027922010-08-25 11:45:40 +00007845 case BO_And:
7846 case BO_Xor:
7847 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007848 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007849 break;
John McCalle3027922010-08-25 11:45:40 +00007850 case BO_LAnd:
7851 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007852 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007853 break;
John McCalle3027922010-08-25 11:45:40 +00007854 case BO_MulAssign:
7855 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007856 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007857 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007858 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007859 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7860 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007861 break;
John McCalle3027922010-08-25 11:45:40 +00007862 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007863 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007864 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007865 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7866 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007867 break;
John McCalle3027922010-08-25 11:45:40 +00007868 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007869 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7870 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7871 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007872 break;
John McCalle3027922010-08-25 11:45:40 +00007873 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007874 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7875 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7876 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007877 break;
John McCalle3027922010-08-25 11:45:40 +00007878 case BO_ShlAssign:
7879 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007880 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007881 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007882 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7883 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007884 break;
John McCalle3027922010-08-25 11:45:40 +00007885 case BO_AndAssign:
7886 case BO_XorAssign:
7887 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007888 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007889 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7891 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007892 break;
John McCalle3027922010-08-25 11:45:40 +00007893 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007894 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7895 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7896 VK = RHS.get()->getValueKind();
7897 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007898 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007899 break;
7900 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007901 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007902 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007903
7904 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007905 CheckArrayAccess(LHS.get());
7906 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007907
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007908 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007909 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007910 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007911 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007912 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007913 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007914 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007915 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007916 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007917 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007918 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007919}
7920
Sebastian Redl44615072009-10-27 12:10:02 +00007921/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7922/// operators are mixed in a way that suggests that the programmer forgot that
7923/// comparison operators have higher precedence. The most typical example of
7924/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007925static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007926 SourceLocation OpLoc, Expr *LHSExpr,
7927 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007928 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007929 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7930 RHSopc = static_cast<BinOp::Opcode>(-1);
7931 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7932 LHSopc = BO->getOpcode();
7933 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7934 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007935
7936 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007937 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007938 return;
7939
7940 // Bitwise operations are sometimes used as eager logical ops.
7941 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007942 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7943 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007944 return;
7945
Richard Trieu4a287fb2011-09-07 01:49:20 +00007946 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7947 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007948 if (!isLeftComp && !isRightComp) return;
7949
Richard Trieu4a287fb2011-09-07 01:49:20 +00007950 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7951 OpLoc)
7952 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7953 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7954 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007955 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007956 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7957 RHSExpr->getLocEnd())
7958 : SourceRange(LHSExpr->getLocStart(),
7959 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007960
7961 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7962 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7963 SuggestParentheses(Self, OpLoc,
7964 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007965 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007966 SuggestParentheses(Self, OpLoc,
7967 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7968 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007969}
7970
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007971/// \brief It accepts a '&' expr that is inside a '|' one.
7972/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7973/// in parentheses.
7974static void
7975EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7976 BinaryOperator *Bop) {
7977 assert(Bop->getOpcode() == BO_And);
7978 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7979 << Bop->getSourceRange() << OpLoc;
7980 SuggestParentheses(Self, Bop->getOperatorLoc(),
7981 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7982 Bop->getSourceRange());
7983}
7984
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007985/// \brief It accepts a '&&' expr that is inside a '||' one.
7986/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7987/// in parentheses.
7988static void
7989EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007990 BinaryOperator *Bop) {
7991 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007992 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7993 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007994 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007995 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007996 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007997}
7998
7999/// \brief Returns true if the given expression can be evaluated as a constant
8000/// 'true'.
8001static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8002 bool Res;
8003 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8004}
8005
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008006/// \brief Returns true if the given expression can be evaluated as a constant
8007/// 'false'.
8008static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8009 bool Res;
8010 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8011}
8012
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008013/// \brief Look for '&&' in the left hand of a '||' expr.
8014static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008015 Expr *LHSExpr, Expr *RHSExpr) {
8016 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008017 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008018 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008019 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008020 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008021 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8022 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8023 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8024 } else if (Bop->getOpcode() == BO_LOr) {
8025 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8026 // If it's "a || b && 1 || c" we didn't warn earlier for
8027 // "a || b && 1", but warn now.
8028 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8029 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8030 }
8031 }
8032 }
8033}
8034
8035/// \brief Look for '&&' in the right hand of a '||' expr.
8036static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008037 Expr *LHSExpr, Expr *RHSExpr) {
8038 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008039 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008040 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008041 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008042 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008043 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8044 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8045 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008046 }
8047 }
8048}
8049
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008050/// \brief Look for '&' in the left or right hand of a '|' expr.
8051static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8052 Expr *OrArg) {
8053 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8054 if (Bop->getOpcode() == BO_And)
8055 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8056 }
8057}
8058
Sebastian Redl43028242009-10-26 15:24:15 +00008059/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008060/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008061static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008062 SourceLocation OpLoc, Expr *LHSExpr,
8063 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008064 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008065 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008066 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008067
8068 // Diagnose "arg1 & arg2 | arg3"
8069 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008070 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8071 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008072 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008073
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008074 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8075 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008076 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008077 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8078 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008079 }
Sebastian Redl43028242009-10-26 15:24:15 +00008080}
8081
Steve Naroff218bc2b2007-05-04 21:54:46 +00008082// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008083ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008084 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008085 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008086 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008087 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8088 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008089
Sebastian Redl43028242009-10-26 15:24:15 +00008090 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008091 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008092
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008093 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008094}
8095
John McCalldadc5752010-08-24 06:29:42 +00008096ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008097 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008098 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008099 if (getLangOptions().CPlusPlus) {
8100 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008101
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008102 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008103 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008104 } else if (Opc == BO_Assign &&
8105 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008106 UseBuiltinOperator = true;
8107 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008108 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8109 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008110 }
8111
8112 if (!UseBuiltinOperator) {
8113 // Find all of the overloaded operators visible from this
8114 // point. We perform both an operator-name lookup from the local
8115 // scope and an argument-dependent lookup based on the types of
8116 // the arguments.
8117 UnresolvedSet<16> Functions;
8118 OverloadedOperatorKind OverOp
8119 = BinaryOperator::getOverloadedOperator(Opc);
8120 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008121 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8122 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008123
8124 // Build the (potentially-overloaded, potentially-dependent)
8125 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008126 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008127 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008128 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008129
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008130 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008131 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008132}
8133
John McCalldadc5752010-08-24 06:29:42 +00008134ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008135 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008136 Expr *InputExpr) {
8137 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008138 ExprValueKind VK = VK_RValue;
8139 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008140 QualType resultType;
8141 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008142 case UO_PreInc:
8143 case UO_PreDec:
8144 case UO_PostInc:
8145 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008146 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008147 Opc == UO_PreInc ||
8148 Opc == UO_PostInc,
8149 Opc == UO_PreInc ||
8150 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008151 break;
John McCalle3027922010-08-25 11:45:40 +00008152 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008153 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008154 break;
John McCall31996342011-04-07 08:22:57 +00008155 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008156 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008157 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008158 Input = move(resolved);
8159 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8160 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008161 break;
John McCall31996342011-04-07 08:22:57 +00008162 }
John McCalle3027922010-08-25 11:45:40 +00008163 case UO_Plus:
8164 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008165 Input = UsualUnaryConversions(Input.take());
8166 if (Input.isInvalid()) return ExprError();
8167 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008168 if (resultType->isDependentType())
8169 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008170 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8171 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008172 break;
8173 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8174 resultType->isEnumeralType())
8175 break;
8176 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008177 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008178 resultType->isPointerType())
8179 break;
John McCall36226622010-10-12 02:09:17 +00008180 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008181 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008182 if (Input.isInvalid()) return ExprError();
8183 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008184 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008185
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008186 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008187 << resultType << Input.get()->getSourceRange());
8188
John McCalle3027922010-08-25 11:45:40 +00008189 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008190 Input = UsualUnaryConversions(Input.take());
8191 if (Input.isInvalid()) return ExprError();
8192 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008193 if (resultType->isDependentType())
8194 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008195 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8196 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8197 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008198 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008199 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008200 else if (resultType->hasIntegerRepresentation())
8201 break;
8202 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008203 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008204 if (Input.isInvalid()) return ExprError();
8205 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008206 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008207 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008208 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008209 }
Steve Naroff35d85152007-05-07 00:24:15 +00008210 break;
John Wiegley01296292011-04-08 18:41:53 +00008211
John McCalle3027922010-08-25 11:45:40 +00008212 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008213 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008214 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8215 if (Input.isInvalid()) return ExprError();
8216 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008217 if (resultType->isDependentType())
8218 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008219 if (resultType->isScalarType()) {
8220 // C99 6.5.3.3p1: ok, fallthrough;
8221 if (Context.getLangOptions().CPlusPlus) {
8222 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8223 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008224 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8225 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008226 }
John McCall36226622010-10-12 02:09:17 +00008227 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008228 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008229 if (Input.isInvalid()) return ExprError();
8230 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008231 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008232 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008233 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008234 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008235
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008236 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008237 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008238 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008239 break;
John McCalle3027922010-08-25 11:45:40 +00008240 case UO_Real:
8241 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008242 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008243 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008244 if (Input.isInvalid()) return ExprError();
8245 if (Input.get()->getValueKind() != VK_RValue &&
8246 Input.get()->getObjectKind() == OK_Ordinary)
8247 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008248 break;
John McCalle3027922010-08-25 11:45:40 +00008249 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008250 resultType = Input.get()->getType();
8251 VK = Input.get()->getValueKind();
8252 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008253 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008254 }
John Wiegley01296292011-04-08 18:41:53 +00008255 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008256 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008257
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008258 // Check for array bounds violations in the operand of the UnaryOperator,
8259 // except for the '*' and '&' operators that have to be handled specially
8260 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8261 // that are explicitly defined as valid by the standard).
8262 if (Opc != UO_AddrOf && Opc != UO_Deref)
8263 CheckArrayAccess(Input.get());
8264
John Wiegley01296292011-04-08 18:41:53 +00008265 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008266 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008267}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008268
John McCalldadc5752010-08-24 06:29:42 +00008269ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008270 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008271 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008272 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008273 // Find all of the overloaded operators visible from this
8274 // point. We perform both an operator-name lookup from the local
8275 // scope and an argument-dependent lookup based on the types of
8276 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008277 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008278 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008279 if (S && OverOp != OO_None)
8280 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8281 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008282
John McCallb268a282010-08-23 23:25:46 +00008283 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008284 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008285
John McCallb268a282010-08-23 23:25:46 +00008286 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008287}
8288
Douglas Gregor5287f092009-11-05 00:51:44 +00008289// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008290ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008291 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008292 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008293}
8294
Steve Naroff66356bd2007-09-16 14:56:35 +00008295/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008296ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008297 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008298 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008299 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008300 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008301 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008302}
8303
John McCall31168b02011-06-15 23:02:42 +00008304/// Given the last statement in a statement-expression, check whether
8305/// the result is a producing expression (like a call to an
8306/// ns_returns_retained function) and, if so, rebuild it to hoist the
8307/// release out of the full-expression. Otherwise, return null.
8308/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008309static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008310 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008311 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008312 if (!cleanups) return 0;
8313
8314 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008315 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008316 return 0;
8317
8318 // Splice out the cast. This shouldn't modify any interesting
8319 // features of the statement.
8320 Expr *producer = cast->getSubExpr();
8321 assert(producer->getType() == cast->getType());
8322 assert(producer->getValueKind() == cast->getValueKind());
8323 cleanups->setSubExpr(producer);
8324 return cleanups;
8325}
8326
John McCalldadc5752010-08-24 06:29:42 +00008327ExprResult
John McCallb268a282010-08-23 23:25:46 +00008328Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008329 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008330 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8331 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8332
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008333 bool isFileScope
8334 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008335 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008336 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008337
Chris Lattner366727f2007-07-24 16:58:17 +00008338 // FIXME: there are a variety of strange constraints to enforce here, for
8339 // example, it is not possible to goto into a stmt expression apparently.
8340 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008341
Chris Lattner366727f2007-07-24 16:58:17 +00008342 // If there are sub stmts in the compound stmt, take the type of the last one
8343 // as the type of the stmtexpr.
8344 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008345 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008346 if (!Compound->body_empty()) {
8347 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008348 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008349 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008350 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8351 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008352 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008353 }
John McCall31168b02011-06-15 23:02:42 +00008354
John Wiegley01296292011-04-08 18:41:53 +00008355 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008356 // Do function/array conversion on the last expression, but not
8357 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008358 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8359 if (LastExpr.isInvalid())
8360 return ExprError();
8361 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008362
John Wiegley01296292011-04-08 18:41:53 +00008363 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008364 // In ARC, if the final expression ends in a consume, splice
8365 // the consume out and bind it later. In the alternate case
8366 // (when dealing with a retainable type), the result
8367 // initialization will create a produce. In both cases the
8368 // result will be +1, and we'll need to balance that out with
8369 // a bind.
8370 if (Expr *rebuiltLastStmt
8371 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8372 LastExpr = rebuiltLastStmt;
8373 } else {
8374 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008375 InitializedEntity::InitializeResult(LPLoc,
8376 Ty,
8377 false),
8378 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008379 LastExpr);
8380 }
8381
John Wiegley01296292011-04-08 18:41:53 +00008382 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008383 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008384 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008385 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008386 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008387 else
John Wiegley01296292011-04-08 18:41:53 +00008388 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008389 StmtExprMayBindToTemp = true;
8390 }
8391 }
8392 }
Chris Lattner944d3062008-07-26 19:51:01 +00008393 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008394
Eli Friedmanba961a92009-03-23 00:24:07 +00008395 // FIXME: Check that expression type is complete/non-abstract; statement
8396 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008397 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8398 if (StmtExprMayBindToTemp)
8399 return MaybeBindToTemporary(ResStmtExpr);
8400 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008401}
Steve Naroff78864672007-08-01 22:05:33 +00008402
John McCalldadc5752010-08-24 06:29:42 +00008403ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008404 TypeSourceInfo *TInfo,
8405 OffsetOfComponent *CompPtr,
8406 unsigned NumComponents,
8407 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008408 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008409 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008410 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008411
Chris Lattnerf17bd422007-08-30 17:45:32 +00008412 // We must have at least one component that refers to the type, and the first
8413 // one is known to be a field designator. Verify that the ArgTy represents
8414 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008415 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008416 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8417 << ArgTy << TypeRange);
8418
8419 // Type must be complete per C99 7.17p3 because a declaring a variable
8420 // with an incomplete type would be ill-formed.
8421 if (!Dependent
8422 && RequireCompleteType(BuiltinLoc, ArgTy,
8423 PDiag(diag::err_offsetof_incomplete_type)
8424 << TypeRange))
8425 return ExprError();
8426
Chris Lattner78502cf2007-08-31 21:49:13 +00008427 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8428 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008429 // FIXME: This diagnostic isn't actually visible because the location is in
8430 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008431 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008432 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8433 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008434
8435 bool DidWarnAboutNonPOD = false;
8436 QualType CurrentType = ArgTy;
8437 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008438 SmallVector<OffsetOfNode, 4> Comps;
8439 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008440 for (unsigned i = 0; i != NumComponents; ++i) {
8441 const OffsetOfComponent &OC = CompPtr[i];
8442 if (OC.isBrackets) {
8443 // Offset of an array sub-field. TODO: Should we allow vector elements?
8444 if (!CurrentType->isDependentType()) {
8445 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8446 if(!AT)
8447 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8448 << CurrentType);
8449 CurrentType = AT->getElementType();
8450 } else
8451 CurrentType = Context.DependentTy;
8452
8453 // The expression must be an integral expression.
8454 // FIXME: An integral constant expression?
8455 Expr *Idx = static_cast<Expr*>(OC.U.E);
8456 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8457 !Idx->getType()->isIntegerType())
8458 return ExprError(Diag(Idx->getLocStart(),
8459 diag::err_typecheck_subscript_not_integer)
8460 << Idx->getSourceRange());
8461
8462 // Record this array index.
8463 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8464 Exprs.push_back(Idx);
8465 continue;
8466 }
8467
8468 // Offset of a field.
8469 if (CurrentType->isDependentType()) {
8470 // We have the offset of a field, but we can't look into the dependent
8471 // type. Just record the identifier of the field.
8472 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8473 CurrentType = Context.DependentTy;
8474 continue;
8475 }
8476
8477 // We need to have a complete type to look into.
8478 if (RequireCompleteType(OC.LocStart, CurrentType,
8479 diag::err_offsetof_incomplete_type))
8480 return ExprError();
8481
8482 // Look for the designated field.
8483 const RecordType *RC = CurrentType->getAs<RecordType>();
8484 if (!RC)
8485 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8486 << CurrentType);
8487 RecordDecl *RD = RC->getDecl();
8488
8489 // C++ [lib.support.types]p5:
8490 // The macro offsetof accepts a restricted set of type arguments in this
8491 // International Standard. type shall be a POD structure or a POD union
8492 // (clause 9).
8493 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8494 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008495 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008496 PDiag(diag::warn_offsetof_non_pod_type)
8497 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8498 << CurrentType))
8499 DidWarnAboutNonPOD = true;
8500 }
8501
8502 // Look for the field.
8503 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8504 LookupQualifiedName(R, RD);
8505 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008506 IndirectFieldDecl *IndirectMemberDecl = 0;
8507 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008508 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008509 MemberDecl = IndirectMemberDecl->getAnonField();
8510 }
8511
Douglas Gregor882211c2010-04-28 22:16:22 +00008512 if (!MemberDecl)
8513 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8514 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8515 OC.LocEnd));
8516
Douglas Gregor10982ea2010-04-28 22:36:06 +00008517 // C99 7.17p3:
8518 // (If the specified member is a bit-field, the behavior is undefined.)
8519 //
8520 // We diagnose this as an error.
8521 if (MemberDecl->getBitWidth()) {
8522 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8523 << MemberDecl->getDeclName()
8524 << SourceRange(BuiltinLoc, RParenLoc);
8525 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8526 return ExprError();
8527 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008528
8529 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008530 if (IndirectMemberDecl)
8531 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008532
Douglas Gregord1702062010-04-29 00:18:15 +00008533 // If the member was found in a base class, introduce OffsetOfNodes for
8534 // the base class indirections.
8535 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8536 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008537 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008538 CXXBasePath &Path = Paths.front();
8539 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8540 B != BEnd; ++B)
8541 Comps.push_back(OffsetOfNode(B->Base));
8542 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008543
Francois Pichet783dd6e2010-11-21 06:08:52 +00008544 if (IndirectMemberDecl) {
8545 for (IndirectFieldDecl::chain_iterator FI =
8546 IndirectMemberDecl->chain_begin(),
8547 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8548 assert(isa<FieldDecl>(*FI));
8549 Comps.push_back(OffsetOfNode(OC.LocStart,
8550 cast<FieldDecl>(*FI), OC.LocEnd));
8551 }
8552 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008553 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008554
Douglas Gregor882211c2010-04-28 22:16:22 +00008555 CurrentType = MemberDecl->getType().getNonReferenceType();
8556 }
8557
8558 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8559 TInfo, Comps.data(), Comps.size(),
8560 Exprs.data(), Exprs.size(), RParenLoc));
8561}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008562
John McCalldadc5752010-08-24 06:29:42 +00008563ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008564 SourceLocation BuiltinLoc,
8565 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008566 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008567 OffsetOfComponent *CompPtr,
8568 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008569 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008570
Douglas Gregor882211c2010-04-28 22:16:22 +00008571 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008572 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008573 if (ArgTy.isNull())
8574 return ExprError();
8575
Eli Friedman06dcfd92010-08-05 10:15:45 +00008576 if (!ArgTInfo)
8577 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8578
8579 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008580 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008581}
8582
8583
John McCalldadc5752010-08-24 06:29:42 +00008584ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008585 Expr *CondExpr,
8586 Expr *LHSExpr, Expr *RHSExpr,
8587 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008588 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8589
John McCall7decc9e2010-11-18 06:31:45 +00008590 ExprValueKind VK = VK_RValue;
8591 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008592 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008593 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008594 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008595 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008596 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008597 } else {
8598 // The conditional expression is required to be a constant expression.
8599 llvm::APSInt condEval(32);
8600 SourceLocation ExpLoc;
8601 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008602 return ExprError(Diag(ExpLoc,
8603 diag::err_typecheck_choose_expr_requires_constant)
8604 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008605
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008606 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008607 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8608
8609 resType = ActiveExpr->getType();
8610 ValueDependent = ActiveExpr->isValueDependent();
8611 VK = ActiveExpr->getValueKind();
8612 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008613 }
8614
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008615 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008616 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008617 resType->isDependentType(),
8618 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008619}
8620
Steve Naroffc540d662008-09-03 18:15:37 +00008621//===----------------------------------------------------------------------===//
8622// Clang Extensions.
8623//===----------------------------------------------------------------------===//
8624
8625/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008626void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008627 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008628 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008629 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008630 if (CurScope)
8631 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008632 else
8633 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008634}
8635
Mike Stump82f071f2009-02-04 22:31:32 +00008636void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008637 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008638 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008639 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008640
John McCall8cb7bdf2010-06-04 23:28:52 +00008641 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008642 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008643
John McCall3882ace2011-01-05 12:14:39 +00008644 // GetTypeForDeclarator always produces a function type for a block
8645 // literal signature. Furthermore, it is always a FunctionProtoType
8646 // unless the function was written with a typedef.
8647 assert(T->isFunctionType() &&
8648 "GetTypeForDeclarator made a non-function block signature");
8649
8650 // Look for an explicit signature in that function type.
8651 FunctionProtoTypeLoc ExplicitSignature;
8652
8653 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8654 if (isa<FunctionProtoTypeLoc>(tmp)) {
8655 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8656
8657 // Check whether that explicit signature was synthesized by
8658 // GetTypeForDeclarator. If so, don't save that as part of the
8659 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008660 if (ExplicitSignature.getLocalRangeBegin() ==
8661 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008662 // This would be much cheaper if we stored TypeLocs instead of
8663 // TypeSourceInfos.
8664 TypeLoc Result = ExplicitSignature.getResultLoc();
8665 unsigned Size = Result.getFullDataSize();
8666 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8667 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8668
8669 ExplicitSignature = FunctionProtoTypeLoc();
8670 }
John McCalla3ccba02010-06-04 11:21:44 +00008671 }
Mike Stump11289f42009-09-09 15:08:12 +00008672
John McCall3882ace2011-01-05 12:14:39 +00008673 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8674 CurBlock->FunctionType = T;
8675
8676 const FunctionType *Fn = T->getAs<FunctionType>();
8677 QualType RetTy = Fn->getResultType();
8678 bool isVariadic =
8679 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8680
John McCall8e346702010-06-04 19:02:56 +00008681 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008682
John McCalla3ccba02010-06-04 11:21:44 +00008683 // Don't allow returning a objc interface by value.
8684 if (RetTy->isObjCObjectType()) {
8685 Diag(ParamInfo.getSourceRange().getBegin(),
8686 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8687 return;
8688 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008689
John McCalla3ccba02010-06-04 11:21:44 +00008690 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008691 // return type. TODO: what should we do with declarators like:
8692 // ^ * { ... }
8693 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008694 if (RetTy != Context.DependentTy)
8695 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008696
John McCalla3ccba02010-06-04 11:21:44 +00008697 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008698 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008699 if (ExplicitSignature) {
8700 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8701 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008702 if (Param->getIdentifier() == 0 &&
8703 !Param->isImplicit() &&
8704 !Param->isInvalidDecl() &&
8705 !getLangOptions().CPlusPlus)
8706 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008707 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008708 }
John McCalla3ccba02010-06-04 11:21:44 +00008709
8710 // Fake up parameter variables if we have a typedef, like
8711 // ^ fntype { ... }
8712 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8713 for (FunctionProtoType::arg_type_iterator
8714 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8715 ParmVarDecl *Param =
8716 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8717 ParamInfo.getSourceRange().getBegin(),
8718 *I);
John McCall8e346702010-06-04 19:02:56 +00008719 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008720 }
Steve Naroffc540d662008-09-03 18:15:37 +00008721 }
John McCalla3ccba02010-06-04 11:21:44 +00008722
John McCall8e346702010-06-04 19:02:56 +00008723 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008724 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008725 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008726 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8727 CurBlock->TheDecl->param_end(),
8728 /*CheckParameterNames=*/false);
8729 }
8730
John McCalla3ccba02010-06-04 11:21:44 +00008731 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008732 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008733
John McCall8e346702010-06-04 19:02:56 +00008734 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008735 Diag(ParamInfo.getAttributes()->getLoc(),
8736 diag::warn_attribute_sentinel_not_variadic) << 1;
8737 // FIXME: remove the attribute.
8738 }
8739
8740 // Put the parameter variables in scope. We can bail out immediately
8741 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008742 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008743 return;
8744
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008745 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008746 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8747 (*AI)->setOwningFunction(CurBlock->TheDecl);
8748
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008749 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008750 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008751 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008752
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008753 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008754 }
John McCallf7b2fb52010-01-22 00:28:27 +00008755 }
Steve Naroffc540d662008-09-03 18:15:37 +00008756}
8757
8758/// ActOnBlockError - If there is an error parsing a block, this callback
8759/// is invoked to pop the information about the block from the action impl.
8760void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008761 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008762 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008763 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008764}
8765
8766/// ActOnBlockStmtExpr - This is called when the body of a block statement
8767/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008768ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008769 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008770 // If blocks are disabled, emit an error.
8771 if (!LangOpts.Blocks)
8772 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008773
Douglas Gregor9a28e842010-03-01 23:15:13 +00008774 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008775
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008776 PopDeclContext();
8777
Steve Naroffc540d662008-09-03 18:15:37 +00008778 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008779 if (!BSI->ReturnType.isNull())
8780 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008781
Mike Stump3bf1ab42009-07-28 22:04:01 +00008782 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008783 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008784
John McCallc63de662011-02-02 13:00:07 +00008785 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008786 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8787 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008788
John McCall8e346702010-06-04 19:02:56 +00008789 // If the user wrote a function type in some form, try to use that.
8790 if (!BSI->FunctionType.isNull()) {
8791 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8792
8793 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8794 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8795
8796 // Turn protoless block types into nullary block types.
8797 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008798 FunctionProtoType::ExtProtoInfo EPI;
8799 EPI.ExtInfo = Ext;
8800 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008801
8802 // Otherwise, if we don't need to change anything about the function type,
8803 // preserve its sugar structure.
8804 } else if (FTy->getResultType() == RetTy &&
8805 (!NoReturn || FTy->getNoReturnAttr())) {
8806 BlockTy = BSI->FunctionType;
8807
8808 // Otherwise, make the minimal modifications to the function type.
8809 } else {
8810 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008811 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8812 EPI.TypeQuals = 0; // FIXME: silently?
8813 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008814 BlockTy = Context.getFunctionType(RetTy,
8815 FPT->arg_type_begin(),
8816 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008817 EPI);
John McCall8e346702010-06-04 19:02:56 +00008818 }
8819
8820 // If we don't have a function type, just build one from nothing.
8821 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008822 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008823 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008824 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008825 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008826
John McCall8e346702010-06-04 19:02:56 +00008827 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8828 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008829 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008830
Chris Lattner45542ea2009-04-19 05:28:12 +00008831 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008832 if (getCurFunction()->NeedsScopeChecking() &&
8833 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008834 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008835
Chris Lattner60f84492011-02-17 23:58:47 +00008836 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008837
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008838 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8839 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8840 const VarDecl *variable = ci->getVariable();
8841 QualType T = variable->getType();
8842 QualType::DestructionKind destructKind = T.isDestructedType();
8843 if (destructKind != QualType::DK_none)
8844 getCurFunction()->setHasBranchProtectedScope();
8845 }
8846
Douglas Gregor49695f02011-09-06 20:46:03 +00008847 computeNRVO(Body, getCurBlock());
8848
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008849 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8850 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8851 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8852
Douglas Gregor9a28e842010-03-01 23:15:13 +00008853 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008854}
8855
John McCalldadc5752010-08-24 06:29:42 +00008856ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008857 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008858 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008859 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008860 GetTypeFromParser(Ty, &TInfo);
8861 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008862}
8863
John McCalldadc5752010-08-24 06:29:42 +00008864ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008865 Expr *E, TypeSourceInfo *TInfo,
8866 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008867 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008868
Eli Friedman121ba0c2008-08-09 23:32:40 +00008869 // Get the va_list type
8870 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008871 if (VaListType->isArrayType()) {
8872 // Deal with implicit array decay; for example, on x86-64,
8873 // va_list is an array, but it's supposed to decay to
8874 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008875 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008876 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008877 ExprResult Result = UsualUnaryConversions(E);
8878 if (Result.isInvalid())
8879 return ExprError();
8880 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008881 } else {
8882 // Otherwise, the va_list argument must be an l-value because
8883 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008884 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008885 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008886 return ExprError();
8887 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008888
Douglas Gregorad3150c2009-05-19 23:10:31 +00008889 if (!E->isTypeDependent() &&
8890 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008891 return ExprError(Diag(E->getLocStart(),
8892 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008893 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008894 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008895
David Majnemerc75d1a12011-06-14 05:17:32 +00008896 if (!TInfo->getType()->isDependentType()) {
8897 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8898 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8899 << TInfo->getTypeLoc().getSourceRange()))
8900 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008901
David Majnemerc75d1a12011-06-14 05:17:32 +00008902 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8903 TInfo->getType(),
8904 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8905 << TInfo->getTypeLoc().getSourceRange()))
8906 return ExprError();
8907
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008908 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008909 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008910 TInfo->getType()->isObjCLifetimeType()
8911 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8912 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008913 << TInfo->getType()
8914 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008915 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008916
8917 // Check for va_arg where arguments of the given type will be promoted
8918 // (i.e. this va_arg is guaranteed to have undefined behavior).
8919 QualType PromoteType;
8920 if (TInfo->getType()->isPromotableIntegerType()) {
8921 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8922 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8923 PromoteType = QualType();
8924 }
8925 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8926 PromoteType = Context.DoubleTy;
8927 if (!PromoteType.isNull())
8928 Diag(TInfo->getTypeLoc().getBeginLoc(),
8929 diag::warn_second_parameter_to_va_arg_never_compatible)
8930 << TInfo->getType()
8931 << PromoteType
8932 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008933 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008934
Abramo Bagnara27db2392010-08-10 10:06:15 +00008935 QualType T = TInfo->getType().getNonLValueExprType(Context);
8936 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008937}
8938
John McCalldadc5752010-08-24 06:29:42 +00008939ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008940 // The type of __null will be int or long, depending on the size of
8941 // pointers on the target.
8942 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008943 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8944 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008945 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008946 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008947 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008948 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008949 Ty = Context.LongLongTy;
8950 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008951 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008952 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008953
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008954 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008955}
8956
Alexis Huntc46382e2010-04-28 23:02:27 +00008957static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008958 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008959 if (!SemaRef.getLangOptions().ObjC1)
8960 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008961
Anders Carlssonace5d072009-11-10 04:46:30 +00008962 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8963 if (!PT)
8964 return;
8965
8966 // Check if the destination is of type 'id'.
8967 if (!PT->isObjCIdType()) {
8968 // Check if the destination is the 'NSString' interface.
8969 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8970 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8971 return;
8972 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008973
Anders Carlssonace5d072009-11-10 04:46:30 +00008974 // Strip off any parens and casts.
8975 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008976 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008977 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008978
Douglas Gregora771f462010-03-31 17:46:05 +00008979 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008980}
8981
Chris Lattner9bad62c2008-01-04 18:04:52 +00008982bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8983 SourceLocation Loc,
8984 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008985 Expr *SrcExpr, AssignmentAction Action,
8986 bool *Complained) {
8987 if (Complained)
8988 *Complained = false;
8989
Chris Lattner9bad62c2008-01-04 18:04:52 +00008990 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008991 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008992 bool isInvalid = false;
8993 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008994 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008995 ConversionFixItGenerator ConvHints;
8996 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008997
Chris Lattner9bad62c2008-01-04 18:04:52 +00008998 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00008999 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009000 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009001 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009002 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009003 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9004 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009005 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009006 case IntToPointer:
9007 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009008 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9009 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009010 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009011 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009012 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009013 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009014 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9015 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009016 if (Hint.isNull() && !CheckInferredResultType) {
9017 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9018 }
9019 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009020 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009021 case IncompatiblePointerSign:
9022 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9023 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009024 case FunctionVoidPointer:
9025 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9026 break;
John McCall4fff8f62011-02-01 00:10:29 +00009027 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009028 // Perform array-to-pointer decay if necessary.
9029 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9030
John McCall4fff8f62011-02-01 00:10:29 +00009031 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9032 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9033 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9034 DiagKind = diag::err_typecheck_incompatible_address_space;
9035 break;
John McCall31168b02011-06-15 23:02:42 +00009036
9037
9038 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009039 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009040 break;
John McCall4fff8f62011-02-01 00:10:29 +00009041 }
9042
9043 llvm_unreachable("unknown error case for discarding qualifiers!");
9044 // fallthrough
9045 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009046 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009047 // If the qualifiers lost were because we were applying the
9048 // (deprecated) C++ conversion from a string literal to a char*
9049 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9050 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009051 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009052 // bit of refactoring (so that the second argument is an
9053 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009054 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009055 // C++ semantics.
9056 if (getLangOptions().CPlusPlus &&
9057 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9058 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009059 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9060 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009061 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009062 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009063 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009064 case IntToBlockPointer:
9065 DiagKind = diag::err_int_to_block_pointer;
9066 break;
9067 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009068 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009069 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009070 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009071 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009072 // it can give a more specific diagnostic.
9073 DiagKind = diag::warn_incompatible_qualified_id;
9074 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009075 case IncompatibleVectors:
9076 DiagKind = diag::warn_incompatible_vectors;
9077 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009078 case IncompatibleObjCWeakRef:
9079 DiagKind = diag::err_arc_weak_unavailable_assign;
9080 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009081 case Incompatible:
9082 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009083 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9084 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009085 isInvalid = true;
9086 break;
9087 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009088
Douglas Gregorc68e1402010-04-09 00:35:39 +00009089 QualType FirstType, SecondType;
9090 switch (Action) {
9091 case AA_Assigning:
9092 case AA_Initializing:
9093 // The destination type comes first.
9094 FirstType = DstType;
9095 SecondType = SrcType;
9096 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009097
Douglas Gregorc68e1402010-04-09 00:35:39 +00009098 case AA_Returning:
9099 case AA_Passing:
9100 case AA_Converting:
9101 case AA_Sending:
9102 case AA_Casting:
9103 // The source type comes first.
9104 FirstType = SrcType;
9105 SecondType = DstType;
9106 break;
9107 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009108
Anna Zaks3b402712011-07-28 19:51:27 +00009109 PartialDiagnostic FDiag = PDiag(DiagKind);
9110 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9111
9112 // If we can fix the conversion, suggest the FixIts.
9113 assert(ConvHints.isNull() || Hint.isNull());
9114 if (!ConvHints.isNull()) {
9115 for (llvm::SmallVector<FixItHint, 1>::iterator
9116 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9117 HI != HE; ++HI)
9118 FDiag << *HI;
9119 } else {
9120 FDiag << Hint;
9121 }
9122 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9123
9124 Diag(Loc, FDiag);
9125
Douglas Gregor33823722011-06-11 01:09:30 +00009126 if (CheckInferredResultType)
9127 EmitRelatedResultTypeNote(SrcExpr);
9128
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009129 if (Complained)
9130 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009131 return isInvalid;
9132}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009133
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009134bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009135 llvm::APSInt ICEResult;
9136 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9137 if (Result)
9138 *Result = ICEResult;
9139 return false;
9140 }
9141
Anders Carlssone54e8a12008-11-30 19:50:32 +00009142 Expr::EvalResult EvalResult;
9143
Mike Stump4e1f26a2009-02-19 03:04:26 +00009144 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009145 EvalResult.HasSideEffects) {
9146 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9147
9148 if (EvalResult.Diag) {
9149 // We only show the note if it's not the usual "invalid subexpression"
9150 // or if it's actually in a subexpression.
9151 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9152 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9153 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9154 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009155
Anders Carlssone54e8a12008-11-30 19:50:32 +00009156 return true;
9157 }
9158
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009159 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9160 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009161
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009162 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009163 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009164 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009165 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009166
Anders Carlssone54e8a12008-11-30 19:50:32 +00009167 if (Result)
9168 *Result = EvalResult.Val.getInt();
9169 return false;
9170}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009171
Douglas Gregorff790f12009-11-26 00:44:06 +00009172void
Mike Stump11289f42009-09-09 15:08:12 +00009173Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009174 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009175 ExpressionEvaluationContextRecord(NewContext,
9176 ExprTemporaries.size(),
9177 ExprNeedsCleanups));
9178 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009179}
9180
Richard Trieucfc491d2011-08-02 04:35:43 +00009181void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009182 // Pop the current expression evaluation context off the stack.
9183 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9184 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009185
Douglas Gregorfab31f42009-12-12 07:57:52 +00009186 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9187 if (Rec.PotentiallyReferenced) {
9188 // Mark any remaining declarations in the current position of the stack
9189 // as "referenced". If they were not meant to be referenced, semantic
9190 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009191 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009192 I = Rec.PotentiallyReferenced->begin(),
9193 IEnd = Rec.PotentiallyReferenced->end();
9194 I != IEnd; ++I)
9195 MarkDeclarationReferenced(I->first, I->second);
9196 }
9197
9198 if (Rec.PotentiallyDiagnosed) {
9199 // Emit any pending diagnostics.
9200 for (PotentiallyEmittedDiagnostics::iterator
9201 I = Rec.PotentiallyDiagnosed->begin(),
9202 IEnd = Rec.PotentiallyDiagnosed->end();
9203 I != IEnd; ++I)
9204 Diag(I->first, I->second);
9205 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009206 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009207
9208 // When are coming out of an unevaluated context, clear out any
9209 // temporaries that we may have created as part of the evaluation of
9210 // the expression in that context: they aren't relevant because they
9211 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009212 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009213 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9214 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009215 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9216
9217 // Otherwise, merge the contexts together.
9218 } else {
9219 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9220 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009221
9222 // Destroy the popped expression evaluation record.
9223 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009224}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009225
John McCall31168b02011-06-15 23:02:42 +00009226void Sema::DiscardCleanupsInEvaluationContext() {
9227 ExprTemporaries.erase(
9228 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9229 ExprTemporaries.end());
9230 ExprNeedsCleanups = false;
9231}
9232
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009233/// \brief Note that the given declaration was referenced in the source code.
9234///
9235/// This routine should be invoke whenever a given declaration is referenced
9236/// in the source code, and where that reference occurred. If this declaration
9237/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9238/// C99 6.9p3), then the declaration will be marked as used.
9239///
9240/// \param Loc the location where the declaration was referenced.
9241///
9242/// \param D the declaration that has been referenced by the source code.
9243void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9244 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009245
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009246 D->setReferenced();
9247
Douglas Gregorebada0772010-06-17 23:14:26 +00009248 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009249 return;
Mike Stump11289f42009-09-09 15:08:12 +00009250
Richard Trieucfc491d2011-08-02 04:35:43 +00009251 // Mark a parameter or variable declaration "used", regardless of whether
9252 // we're in a template or not. The reason for this is that unevaluated
9253 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9254 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009255 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009256 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009257 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009258 return;
9259 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009260
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009261 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9262 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009263
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009264 // Do not mark anything as "used" within a dependent context; wait for
9265 // an instantiation.
9266 if (CurContext->isDependentContext())
9267 return;
Mike Stump11289f42009-09-09 15:08:12 +00009268
Douglas Gregorff790f12009-11-26 00:44:06 +00009269 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009270 case Unevaluated:
9271 // We are in an expression that is not potentially evaluated; do nothing.
9272 return;
Mike Stump11289f42009-09-09 15:08:12 +00009273
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009274 case PotentiallyEvaluated:
9275 // We are in a potentially-evaluated expression, so this declaration is
9276 // "used"; handle this below.
9277 break;
Mike Stump11289f42009-09-09 15:08:12 +00009278
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009279 case PotentiallyPotentiallyEvaluated:
9280 // We are in an expression that may be potentially evaluated; queue this
9281 // declaration reference until we know whether the expression is
9282 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009283 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009284 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009285
9286 case PotentiallyEvaluatedIfUsed:
9287 // Referenced declarations will only be used if the construct in the
9288 // containing expression is used.
9289 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009290 }
Mike Stump11289f42009-09-09 15:08:12 +00009291
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009292 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009293 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009294 if (Constructor->isDefaulted()) {
9295 if (Constructor->isDefaultConstructor()) {
9296 if (Constructor->isTrivial())
9297 return;
9298 if (!Constructor->isUsed(false))
9299 DefineImplicitDefaultConstructor(Loc, Constructor);
9300 } else if (Constructor->isCopyConstructor()) {
9301 if (!Constructor->isUsed(false))
9302 DefineImplicitCopyConstructor(Loc, Constructor);
9303 } else if (Constructor->isMoveConstructor()) {
9304 if (!Constructor->isUsed(false))
9305 DefineImplicitMoveConstructor(Loc, Constructor);
9306 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009307 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009308
Douglas Gregor88d292c2010-05-13 16:44:06 +00009309 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009310 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009311 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009312 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009313 if (Destructor->isVirtual())
9314 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009315 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009316 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009317 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009318 if (!MethodDecl->isUsed(false)) {
9319 if (MethodDecl->isCopyAssignmentOperator())
9320 DefineImplicitCopyAssignment(Loc, MethodDecl);
9321 else
9322 DefineImplicitMoveAssignment(Loc, MethodDecl);
9323 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009324 } else if (MethodDecl->isVirtual())
9325 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009326 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009327 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009328 // Recursive functions should be marked when used from another function.
9329 if (CurContext == Function) return;
9330
Mike Stump11289f42009-09-09 15:08:12 +00009331 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009332 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009333 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009334 bool AlreadyInstantiated = false;
9335 if (FunctionTemplateSpecializationInfo *SpecInfo
9336 = Function->getTemplateSpecializationInfo()) {
9337 if (SpecInfo->getPointOfInstantiation().isInvalid())
9338 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009339 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009340 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009341 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009342 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009343 = Function->getMemberSpecializationInfo()) {
9344 if (MSInfo->getPointOfInstantiation().isInvalid())
9345 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009346 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009347 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009348 AlreadyInstantiated = true;
9349 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009350
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009351 if (!AlreadyInstantiated) {
9352 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9353 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9354 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9355 Loc));
9356 else
Chandler Carruth54080172010-08-25 08:44:16 +00009357 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009358 }
John McCall83779672011-02-19 02:53:41 +00009359 } else {
9360 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009361 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9362 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009363 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009364 MarkDeclarationReferenced(Loc, *i);
9365 }
John McCall83779672011-02-19 02:53:41 +00009366 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009367
John McCall83779672011-02-19 02:53:41 +00009368 // Keep track of used but undefined functions.
9369 if (!Function->isPure() && !Function->hasBody() &&
9370 Function->getLinkage() != ExternalLinkage) {
9371 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9372 if (old.isInvalid()) old = Loc;
9373 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009374
John McCall83779672011-02-19 02:53:41 +00009375 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009376 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009377 }
Mike Stump11289f42009-09-09 15:08:12 +00009378
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009379 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009380 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009381 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009382 Var->getInstantiatedFromStaticDataMember()) {
9383 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9384 assert(MSInfo && "Missing member specialization information?");
9385 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9386 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9387 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009388 // This is a modification of an existing AST node. Notify listeners.
9389 if (ASTMutationListener *L = getASTMutationListener())
9390 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009391 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009392 }
9393 }
Mike Stump11289f42009-09-09 15:08:12 +00009394
John McCall15dd4042011-02-21 19:25:48 +00009395 // Keep track of used but undefined variables. We make a hole in
9396 // the warning for static const data members with in-line
9397 // initializers.
John McCall83779672011-02-19 02:53:41 +00009398 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009399 && Var->getLinkage() != ExternalLinkage
9400 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009401 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9402 if (old.isInvalid()) old = Loc;
9403 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009404
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009405 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009406 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009407 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009408}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009409
Douglas Gregor5597ab42010-05-07 23:12:07 +00009410namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009411 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009412 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009413 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009414 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9415 Sema &S;
9416 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009417
Douglas Gregor5597ab42010-05-07 23:12:07 +00009418 public:
9419 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009420
Douglas Gregor5597ab42010-05-07 23:12:07 +00009421 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009422
9423 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9424 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009425 };
9426}
9427
Chandler Carruthaf80f662010-06-09 08:17:30 +00009428bool MarkReferencedDecls::TraverseTemplateArgument(
9429 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009430 if (Arg.getKind() == TemplateArgument::Declaration) {
9431 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9432 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009433
9434 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009435}
9436
Chandler Carruthaf80f662010-06-09 08:17:30 +00009437bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009438 if (ClassTemplateSpecializationDecl *Spec
9439 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9440 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009441 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009442 }
9443
Chandler Carruthc65667c2010-06-10 10:31:57 +00009444 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009445}
9446
9447void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9448 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009449 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009450}
9451
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009452namespace {
9453 /// \brief Helper class that marks all of the declarations referenced by
9454 /// potentially-evaluated subexpressions as "referenced".
9455 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9456 Sema &S;
9457
9458 public:
9459 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9460
9461 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9462
9463 void VisitDeclRefExpr(DeclRefExpr *E) {
9464 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9465 }
9466
9467 void VisitMemberExpr(MemberExpr *E) {
9468 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009469 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009470 }
9471
9472 void VisitCXXNewExpr(CXXNewExpr *E) {
9473 if (E->getConstructor())
9474 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9475 if (E->getOperatorNew())
9476 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9477 if (E->getOperatorDelete())
9478 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009479 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009480 }
9481
9482 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9483 if (E->getOperatorDelete())
9484 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009485 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9486 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9487 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9488 S.MarkDeclarationReferenced(E->getLocStart(),
9489 S.LookupDestructor(Record));
9490 }
9491
Douglas Gregor32b3de52010-09-11 23:32:50 +00009492 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009493 }
9494
9495 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9496 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009497 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009498 }
9499
9500 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9501 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9502 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009503
9504 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9505 Visit(E->getExpr());
9506 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009507 };
9508}
9509
9510/// \brief Mark any declarations that appear within this expression or any
9511/// potentially-evaluated subexpressions as "referenced".
9512void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9513 EvaluatedExprMarker(*this).Visit(E);
9514}
9515
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009516/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9517/// of the program being compiled.
9518///
9519/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009520/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009521/// possibility that the code will actually be executable. Code in sizeof()
9522/// expressions, code used only during overload resolution, etc., are not
9523/// potentially evaluated. This routine will suppress such diagnostics or,
9524/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009525/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009526/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009527///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009528/// This routine should be used for all diagnostics that describe the run-time
9529/// behavior of a program, such as passing a non-POD value through an ellipsis.
9530/// Failure to do so will likely result in spurious diagnostics or failures
9531/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009532bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009533 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009534 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009535 case Unevaluated:
9536 // The argument will never be evaluated, so don't complain.
9537 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009538
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009539 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009540 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009541 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009542 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009543 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009544 }
9545 else
9546 Diag(Loc, PD);
9547
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009548 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009549
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009550 case PotentiallyPotentiallyEvaluated:
9551 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9552 break;
9553 }
9554
9555 return false;
9556}
9557
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009558bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9559 CallExpr *CE, FunctionDecl *FD) {
9560 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9561 return false;
9562
9563 PartialDiagnostic Note =
9564 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9565 << FD->getDeclName() : PDiag();
9566 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009567
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009568 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009569 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009570 PDiag(diag::err_call_function_incomplete_return)
9571 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009572 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009573 << CE->getSourceRange(),
9574 std::make_pair(NoteLoc, Note)))
9575 return true;
9576
9577 return false;
9578}
9579
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009580// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009581// will prevent this condition from triggering, which is what we want.
9582void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9583 SourceLocation Loc;
9584
John McCall0506e4a2009-11-11 02:41:58 +00009585 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009586 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009587
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009588 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009589 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009590 return;
9591
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009592 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9593
John McCallb0e419e2009-11-12 00:06:05 +00009594 // Greylist some idioms by putting them into a warning subcategory.
9595 if (ObjCMessageExpr *ME
9596 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9597 Selector Sel = ME->getSelector();
9598
John McCallb0e419e2009-11-12 00:06:05 +00009599 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009600 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009601 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9602
9603 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009604 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009605 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9606 }
John McCall0506e4a2009-11-11 02:41:58 +00009607
John McCalld5707ab2009-10-12 21:59:07 +00009608 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009609 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009610 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009611 return;
9612
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009613 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009614 Loc = Op->getOperatorLoc();
9615 } else {
9616 // Not an assignment.
9617 return;
9618 }
9619
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009620 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009621
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009622 SourceLocation Open = E->getSourceRange().getBegin();
9623 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9624 Diag(Loc, diag::note_condition_assign_silence)
9625 << FixItHint::CreateInsertion(Open, "(")
9626 << FixItHint::CreateInsertion(Close, ")");
9627
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009628 if (IsOrAssign)
9629 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9630 << FixItHint::CreateReplacement(Loc, "!=");
9631 else
9632 Diag(Loc, diag::note_condition_assign_to_comparison)
9633 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009634}
9635
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009636/// \brief Redundant parentheses over an equality comparison can indicate
9637/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009638void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009639 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009640 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009641 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9642 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009643 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009644 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009645 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009646
Richard Trieuba63ce62011-09-09 01:45:06 +00009647 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009648
9649 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009650 if (opE->getOpcode() == BO_EQ &&
9651 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9652 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009653 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009654
Ted Kremenekae022092011-02-02 02:20:30 +00009655 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009656 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009657 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9658 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009659 Diag(Loc, diag::note_equality_comparison_to_assign)
9660 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009661 }
9662}
9663
John Wiegley01296292011-04-08 18:41:53 +00009664ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009665 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009666 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9667 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009668
John McCall0009fcc2011-04-26 20:42:42 +00009669 ExprResult result = CheckPlaceholderExpr(E);
9670 if (result.isInvalid()) return ExprError();
9671 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009672
John McCall0009fcc2011-04-26 20:42:42 +00009673 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009674 if (getLangOptions().CPlusPlus)
9675 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9676
John Wiegley01296292011-04-08 18:41:53 +00009677 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9678 if (ERes.isInvalid())
9679 return ExprError();
9680 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009681
9682 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009683 if (!T->isScalarType()) { // C99 6.8.4.1p1
9684 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9685 << T << E->getSourceRange();
9686 return ExprError();
9687 }
John McCalld5707ab2009-10-12 21:59:07 +00009688 }
9689
John Wiegley01296292011-04-08 18:41:53 +00009690 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009691}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009692
John McCalldadc5752010-08-24 06:29:42 +00009693ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009694 Expr *SubExpr) {
9695 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009696 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009697
Richard Trieuba63ce62011-09-09 01:45:06 +00009698 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009699}
John McCall36e7fe32010-10-12 00:20:44 +00009700
John McCall31996342011-04-07 08:22:57 +00009701namespace {
John McCall2979fe02011-04-12 00:42:48 +00009702 /// A visitor for rebuilding a call to an __unknown_any expression
9703 /// to have an appropriate type.
9704 struct RebuildUnknownAnyFunction
9705 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9706
9707 Sema &S;
9708
9709 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9710
9711 ExprResult VisitStmt(Stmt *S) {
9712 llvm_unreachable("unexpected statement!");
9713 return ExprError();
9714 }
9715
Richard Trieu10162ab2011-09-09 03:59:41 +00009716 ExprResult VisitExpr(Expr *E) {
9717 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9718 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009719 return ExprError();
9720 }
9721
9722 /// Rebuild an expression which simply semantically wraps another
9723 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009724 template <class T> ExprResult rebuildSugarExpr(T *E) {
9725 ExprResult SubResult = Visit(E->getSubExpr());
9726 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009727
Richard Trieu10162ab2011-09-09 03:59:41 +00009728 Expr *SubExpr = SubResult.take();
9729 E->setSubExpr(SubExpr);
9730 E->setType(SubExpr->getType());
9731 E->setValueKind(SubExpr->getValueKind());
9732 assert(E->getObjectKind() == OK_Ordinary);
9733 return E;
John McCall2979fe02011-04-12 00:42:48 +00009734 }
9735
Richard Trieu10162ab2011-09-09 03:59:41 +00009736 ExprResult VisitParenExpr(ParenExpr *E) {
9737 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009738 }
9739
Richard Trieu10162ab2011-09-09 03:59:41 +00009740 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9741 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009742 }
9743
Richard Trieu10162ab2011-09-09 03:59:41 +00009744 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9745 ExprResult SubResult = Visit(E->getSubExpr());
9746 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009747
Richard Trieu10162ab2011-09-09 03:59:41 +00009748 Expr *SubExpr = SubResult.take();
9749 E->setSubExpr(SubExpr);
9750 E->setType(S.Context.getPointerType(SubExpr->getType()));
9751 assert(E->getValueKind() == VK_RValue);
9752 assert(E->getObjectKind() == OK_Ordinary);
9753 return E;
John McCall2979fe02011-04-12 00:42:48 +00009754 }
9755
Richard Trieu10162ab2011-09-09 03:59:41 +00009756 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9757 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009758
Richard Trieu10162ab2011-09-09 03:59:41 +00009759 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009760
Richard Trieu10162ab2011-09-09 03:59:41 +00009761 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009762 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009763 !(isa<CXXMethodDecl>(VD) &&
9764 cast<CXXMethodDecl>(VD)->isInstance()))
9765 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009766
Richard Trieu10162ab2011-09-09 03:59:41 +00009767 return E;
John McCall2979fe02011-04-12 00:42:48 +00009768 }
9769
Richard Trieu10162ab2011-09-09 03:59:41 +00009770 ExprResult VisitMemberExpr(MemberExpr *E) {
9771 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009772 }
9773
Richard Trieu10162ab2011-09-09 03:59:41 +00009774 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9775 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009776 }
9777 };
9778}
9779
9780/// Given a function expression of unknown-any type, try to rebuild it
9781/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009782static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9783 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9784 if (Result.isInvalid()) return ExprError();
9785 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009786}
9787
9788namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009789 /// A visitor for rebuilding an expression of type __unknown_anytype
9790 /// into one which resolves the type directly on the referring
9791 /// expression. Strict preservation of the original source
9792 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009793 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009794 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009795
9796 Sema &S;
9797
9798 /// The current destination type.
9799 QualType DestType;
9800
Richard Trieu10162ab2011-09-09 03:59:41 +00009801 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9802 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009803
John McCall39439732011-04-09 22:50:59 +00009804 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009805 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009806 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009807 }
9808
Richard Trieu10162ab2011-09-09 03:59:41 +00009809 ExprResult VisitExpr(Expr *E) {
9810 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9811 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009812 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009813 }
9814
Richard Trieu10162ab2011-09-09 03:59:41 +00009815 ExprResult VisitCallExpr(CallExpr *E);
9816 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009817
John McCall39439732011-04-09 22:50:59 +00009818 /// Rebuild an expression which simply semantically wraps another
9819 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009820 template <class T> ExprResult rebuildSugarExpr(T *E) {
9821 ExprResult SubResult = Visit(E->getSubExpr());
9822 if (SubResult.isInvalid()) return ExprError();
9823 Expr *SubExpr = SubResult.take();
9824 E->setSubExpr(SubExpr);
9825 E->setType(SubExpr->getType());
9826 E->setValueKind(SubExpr->getValueKind());
9827 assert(E->getObjectKind() == OK_Ordinary);
9828 return E;
John McCall39439732011-04-09 22:50:59 +00009829 }
John McCall31996342011-04-07 08:22:57 +00009830
Richard Trieu10162ab2011-09-09 03:59:41 +00009831 ExprResult VisitParenExpr(ParenExpr *E) {
9832 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009833 }
9834
Richard Trieu10162ab2011-09-09 03:59:41 +00009835 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9836 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009837 }
9838
Richard Trieu10162ab2011-09-09 03:59:41 +00009839 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9840 const PointerType *Ptr = DestType->getAs<PointerType>();
9841 if (!Ptr) {
9842 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9843 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009844 return ExprError();
9845 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009846 assert(E->getValueKind() == VK_RValue);
9847 assert(E->getObjectKind() == OK_Ordinary);
9848 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009849
9850 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009851 DestType = Ptr->getPointeeType();
9852 ExprResult SubResult = Visit(E->getSubExpr());
9853 if (SubResult.isInvalid()) return ExprError();
9854 E->setSubExpr(SubResult.take());
9855 return E;
John McCall2979fe02011-04-12 00:42:48 +00009856 }
9857
Richard Trieu10162ab2011-09-09 03:59:41 +00009858 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009859
Richard Trieu10162ab2011-09-09 03:59:41 +00009860 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009861
Richard Trieu10162ab2011-09-09 03:59:41 +00009862 ExprResult VisitMemberExpr(MemberExpr *E) {
9863 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009864 }
John McCall39439732011-04-09 22:50:59 +00009865
Richard Trieu10162ab2011-09-09 03:59:41 +00009866 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9867 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009868 }
9869 };
9870}
9871
John McCall2d2e8702011-04-11 07:02:50 +00009872/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009873ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9874 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009875
9876 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009877 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009878 FK_FunctionPointer,
9879 FK_BlockPointer
9880 };
9881
Richard Trieu10162ab2011-09-09 03:59:41 +00009882 FnKind Kind;
9883 QualType CalleeType = CalleeExpr->getType();
9884 if (CalleeType == S.Context.BoundMemberTy) {
9885 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9886 Kind = FK_MemberFunction;
9887 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9888 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9889 CalleeType = Ptr->getPointeeType();
9890 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009891 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009892 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9893 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009894 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009895 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009896
9897 // Verify that this is a legal result type of a function.
9898 if (DestType->isArrayType() || DestType->isFunctionType()) {
9899 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009900 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009901 diagID = diag::err_block_returning_array_function;
9902
Richard Trieu10162ab2011-09-09 03:59:41 +00009903 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009904 << DestType->isFunctionType() << DestType;
9905 return ExprError();
9906 }
9907
9908 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009909 E->setType(DestType.getNonLValueExprType(S.Context));
9910 E->setValueKind(Expr::getValueKindForType(DestType));
9911 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009912
9913 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009914 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009915 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009916 Proto->arg_type_begin(),
9917 Proto->getNumArgs(),
9918 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009919 else
9920 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009921 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009922
9923 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009924 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009925 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009926 // Nothing to do.
9927 break;
9928
9929 case FK_FunctionPointer:
9930 DestType = S.Context.getPointerType(DestType);
9931 break;
9932
9933 case FK_BlockPointer:
9934 DestType = S.Context.getBlockPointerType(DestType);
9935 break;
9936 }
9937
9938 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009939 ExprResult CalleeResult = Visit(CalleeExpr);
9940 if (!CalleeResult.isUsable()) return ExprError();
9941 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009942
9943 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009944 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009945}
9946
Richard Trieu10162ab2011-09-09 03:59:41 +00009947ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009948 // Verify that this is a legal result type of a call.
9949 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009950 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009951 << DestType->isFunctionType() << DestType;
9952 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009953 }
9954
John McCall3f4138c2011-07-13 17:56:40 +00009955 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009956 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9957 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9958 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009959 }
John McCall2979fe02011-04-12 00:42:48 +00009960
John McCall2d2e8702011-04-11 07:02:50 +00009961 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009962 E->setType(DestType.getNonReferenceType());
9963 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009964
Richard Trieu10162ab2011-09-09 03:59:41 +00009965 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009966}
9967
Richard Trieu10162ab2011-09-09 03:59:41 +00009968ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009969 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +00009970 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9971 assert(E->getValueKind() == VK_RValue);
9972 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009973
Richard Trieu10162ab2011-09-09 03:59:41 +00009974 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009975
John McCall2d2e8702011-04-11 07:02:50 +00009976 // Rebuild the sub-expression as the pointee (function) type.
9977 DestType = DestType->castAs<PointerType>()->getPointeeType();
9978
Richard Trieu10162ab2011-09-09 03:59:41 +00009979 ExprResult Result = Visit(E->getSubExpr());
9980 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009981
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 E->setSubExpr(Result.take());
9983 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +00009984}
9985
Richard Trieu10162ab2011-09-09 03:59:41 +00009986ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9987 ExprValueKind ValueKind = VK_LValue;
9988 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +00009989
9990 // We know how to make this work for certain kinds of decls:
9991
9992 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +00009993 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9994 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9995 DestType = Ptr->getPointeeType();
9996 ExprResult Result = resolveDecl(E, VD);
9997 if (Result.isInvalid()) return ExprError();
9998 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +00009999 CK_FunctionToPointerDecay, VK_RValue);
10000 }
10001
Richard Trieu10162ab2011-09-09 03:59:41 +000010002 if (!Type->isFunctionType()) {
10003 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10004 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010005 return ExprError();
10006 }
John McCall2d2e8702011-04-11 07:02:50 +000010007
Richard Trieu10162ab2011-09-09 03:59:41 +000010008 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10009 if (MD->isInstance()) {
10010 ValueKind = VK_RValue;
10011 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010012 }
10013
John McCall2d2e8702011-04-11 07:02:50 +000010014 // Function references aren't l-values in C.
10015 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010016 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010017
10018 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010019 } else if (isa<VarDecl>(VD)) {
10020 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10021 Type = RefTy->getPointeeType();
10022 } else if (Type->isFunctionType()) {
10023 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10024 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010025 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010026 }
10027
10028 // - nothing else
10029 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010030 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10031 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010032 return ExprError();
10033 }
10034
Richard Trieu10162ab2011-09-09 03:59:41 +000010035 VD->setType(DestType);
10036 E->setType(Type);
10037 E->setValueKind(ValueKind);
10038 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010039}
10040
John McCall31996342011-04-07 08:22:57 +000010041/// Check a cast of an unknown-any type. We intentionally only
10042/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010043ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10044 Expr *CastExpr, CastKind &CastKind,
10045 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010046 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010047 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010048 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010049
Richard Trieuba63ce62011-09-09 01:45:06 +000010050 CastExpr = result.take();
10051 VK = CastExpr->getValueKind();
10052 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010053
Richard Trieuba63ce62011-09-09 01:45:06 +000010054 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010055}
10056
Richard Trieuba63ce62011-09-09 01:45:06 +000010057static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10058 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010059 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010060 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010061 E = E->IgnoreParenImpCasts();
10062 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10063 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010064 diagID = diag::err_uncasted_call_of_unknown_any;
10065 } else {
John McCall31996342011-04-07 08:22:57 +000010066 break;
John McCall2d2e8702011-04-11 07:02:50 +000010067 }
John McCall31996342011-04-07 08:22:57 +000010068 }
10069
John McCall2d2e8702011-04-11 07:02:50 +000010070 SourceLocation loc;
10071 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010072 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010073 loc = ref->getLocation();
10074 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010075 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010076 loc = mem->getMemberLoc();
10077 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010078 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010079 diagID = diag::err_uncasted_call_of_unknown_any;
10080 loc = msg->getSelectorLoc();
10081 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010082 if (!d) {
10083 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10084 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10085 << orig->getSourceRange();
10086 return ExprError();
10087 }
John McCall2d2e8702011-04-11 07:02:50 +000010088 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010089 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10090 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010091 return ExprError();
10092 }
10093
10094 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010095
10096 // Never recoverable.
10097 return ExprError();
10098}
10099
John McCall36e7fe32010-10-12 00:20:44 +000010100/// Check for operands with placeholder types and complain if found.
10101/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010102ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010103 // Placeholder types are always *exactly* the appropriate builtin type.
10104 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010105
John McCall31996342011-04-07 08:22:57 +000010106 // Overloaded expressions.
10107 if (type == Context.OverloadTy)
10108 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010109 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010110 QualType(),
10111 diag::err_ovl_unresolvable);
10112
John McCall0009fcc2011-04-26 20:42:42 +000010113 // Bound member functions.
10114 if (type == Context.BoundMemberTy) {
10115 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10116 << E->getSourceRange();
10117 return ExprError();
10118 }
10119
John McCall31996342011-04-07 08:22:57 +000010120 // Expressions of unknown type.
10121 if (type == Context.UnknownAnyTy)
10122 return diagnoseUnknownAnyExpr(*this, E);
10123
10124 assert(!type->isPlaceholderType());
10125 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010126}
Richard Trieu2c850c02011-04-21 21:44:26 +000010127
Richard Trieuba63ce62011-09-09 01:45:06 +000010128bool Sema::CheckCaseExpression(Expr *E) {
10129 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010130 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010131 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10132 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010133 return false;
10134}